Lesson 1.2: Variables and Data Types | AP CSA
Lesson 1.2: Variables and Data Types
What you’ll learn in this lesson
- 1.2.A. Identify the most appropriate data type category (primitive vs. reference) for a particular specification, and recognize the three primitive types used in AP CSA.
-
1.2.B. Declare variables to store numbers and Boolean values using
int,double, andboolean, with the correct syntax for naming and initialization.
This lesson is part of the AP CSA Course and Exam Description (effective May 2027).
AP exam weight: Variable declarations and data type selection appear in nearly every MCQ on the exam, usually as part of larger code segments. The exclusion statement matters too: AP CSA only tests int, double, and boolean for primitives, so anything involving long, float, short, byte, or char is a trap distractor by definition.
What is a variable, and why do we need types?
A program that just prints “Hello, World” isn’t very useful. Real programs work with data, test scores, prices, names, true/false flags, and that data has to live somewhere while the program runs. That somewhere is a variable: a named storage location that holds a value, where the value can change as the program executes.
Definition
A variable is a storage location that holds a value, which can change while the program is running. Every variable has a name and an associated data type. A variable of a primitive type holds a primitive value from that type.
Naming a storage location is only half the picture. Java is a statically typed language, which means every variable also has a fixed data type that the compiler tracks. The data type tells Java two things: what set of values can be stored there, and what operations are allowed on those values. Storing the number 42 behaves very differently from storing the text "42", one is an integer you can do arithmetic on, the other is a string of characters.
The two categories: primitive vs. reference
Java divides every data type into one of two categories. Primitive types directly hold simple values like numbers and Boolean truth values. Reference types are used to define objects, things like String, Scanner, and any class you write yourself. The CED is explicit about this distinction because it’s the foundation for everything you’ll learn about objects in Unit 1, classes in Unit 3, and collections in Unit 4.
For now, the important thing is that primitives hold the value itself, while references hold a way to find an object that lives elsewhere in memory. In Lesson 1.2 we work entirely with primitives. Reference types come in lesson 1.5 when you create your first String object.
Exclusion statement: AP exam scope
The AP Computer Science A course and exam uses only three primitive types: int, double, and boolean. The other five Java primitives, long, short, byte, float, and char, are explicitly excluded from the AP CSA exam. If you see any of those five in an answer choice, the choice is wrong by definition of the course scope.
The three primitive types in AP CSA
Each of the three has a specific job, defined by what values it can hold:
-
int. Stores an integer (a whole number, positive, negative, or zero). Examples:0,42,-7,1000000. Theinttype cannot store decimals. -
double. Stores a real number, including decimals. Examples:3.14,-0.5,2.0,99.99. Usedoubleany time the value has a fractional part or could need one. -
boolean. Stores exactly one of two values:trueorfalse. No quotes, no capitals. Usebooleanfor yes/no flags, on/off states, and the result of comparisons.
Example: picking the right type
A program that tracks how many students are in a classroom should use int because you cannot have 24.5 students. A program that tracks the average exam grade should use double. The average of 87, 91, and 95 is 91.0, but the average of 87, 90, and 92 is 89.666..., which an int would truncate to 89. A program that tracks whether the lights in the building are on should use boolean; the lights are either on or off, nothing in between.
Declaring variables: the syntax
To declare a variable in Java, you write the data type, then the variable name, optionally followed by = and an initial value, and finally a semicolon. The pattern is:
dataType variableName = initialValue;
Concrete examples that follow the AP CSA scope:
int score = 0;
double price = 19.99;
boolean isPassing = true;
You can also declare a variable without giving it an initial value, int score; is legal, but the variable then has no usable value, and Java will refuse to let you use it in an expression until you assign one. This is called definite assignment, and on the AP exam any code that reads from an uninitialized local variable is a syntax/compile error.
Variable naming rules
Java imposes a small set of rules for variable names. They are not optional, breaking them produces a syntax error and the compiler refuses to compile the program:
- Must start with a letter, an underscore (
_), or a dollar sign ($), never a digit. - After the first character, can contain letters, digits, underscores, and dollar signs.
- Cannot be a Java reserved word (
int,double,boolean,class,if, etc.). - Case sensitive:
scoreandScoreare two different variables. - Convention (not a rule, but expected on the exam): use camelCase. The first word is lowercase; subsequent words start with a capital letter. So
numStudents, notnum_studentsorNumStudents.
Key insight
The data type a programmer chooses is a design decision, not a Java decision. Java will happily let you store the number of students in a double, the program compiles and runs. But on the AP exam, “which is the most appropriate data type” questions have one right answer: the type that exactly matches the values the specification allows. Whole-number quantities use int. Quantities with fractional parts use double. Yes/no states use boolean. Picking a wider type “just in case” is wrong on the exam, even though it might be reasonable engineering elsewhere.
Key vocabulary
| Term | Definition |
|---|---|
| Data type | A set of values plus the operations defined on those values. Categorized as either primitive or reference. |
| Primitive type | A data type that directly holds a simple value. AP CSA uses three: int, double, boolean. |
| Reference type | A data type used to define an object. Lesson 1.5 introduces String as the first reference type. |
| Variable | A named storage location that holds a value. The value can change during execution; the data type cannot. |
int |
Primitive type storing integers (whole numbers, positive, negative, or zero). No decimal portion. |
double |
Primitive type storing real numbers, including decimal values. |
boolean |
Primitive type storing exactly one of true or false (lowercase, no quotes). |
| Declaration | The statement that creates a variable. Has the form dataType name = value; with the initial value optional. |
| Definite assignment | The Java rule that a local variable must be assigned a value before it is read. Reading an unassigned local is a compile error. |
Tier 2 Practice Check your understanding
Six exercises covering data type categories, the three primitives in scope, declaration syntax, and the AP exam exclusions. Watch out for distractors that use Java types outside AP CSA scope. They appear constantly on the real exam as wrong answers.
- The three primitive types used in this course are
int,double, andboolean. - A primitive type defines a set of values and a corresponding set of operations on those values.
- The
floattype is a valid primitive in AP CSA for storing decimal numbers, since it is shorter thandouble.
int, double, and boolean, and a data type is defined as a set of values plus the operations on them. Statement III is the trap: float exists in Java but is explicitly excluded from AP CSA. The exclusion statement names long, short, byte, float, and char as out of scope. Recognize all five. They appear as wrong answers throughout the exam.
int numStudents = 25;
double price = 19.99;
int 1stPlace = 100;
boolean hasPassed = false;
1stPlace as a syntax error. Options A, B, and D all follow the rules: valid type, valid name starting with a letter, valid initial value, semicolon at the end. Renaming option C to firstPlace or place1 would make it valid.
intdoublebooleanint for counts of indivisible things. double for measurements and averages that can have fractional parts. boolean for yes/no states. Reference types, like String, introduced in Lesson 1.5, for everything that isn’t a primitive. Names, sentences, and lists of values are all reference types.
int
double
boolean
int. Anything with a fractional component (temperature, prices with cents) calls for double. Anything with exactly two states (locked/unlocked, won/not won) calls for boolean. The trap on the real exam is picking double for things that should be int “to be safe”. On the AP exam, the most appropriate type is the one that exactly matches the values allowed.
float is in the chip bank as a distractor because it’s a real Java type but is explicitly out of AP CSA scope. The CED specifies double as the only primitive for decimal values.
int, because money amounts should be stored as whole numbers to avoid rounding errors.boolean, since the bill is either paid or unpaid.String, because dollar amounts are usually displayed with a dollar sign.double, because the bill must be able to store decimal values such as 28.47.double is the only AP CSA primitive type that fits. Option A is wrong because int cannot store cents (and the exam does not expect students to do the “store money as integer pennies” engineering trick, that’s outside the AP scope). Option B confuses storing the value with storing a payment status. Option C, String, is a reference type used for text display, not arithmetic; you cannot add two String bills together with a + in the math sense.
Practice with a game — choose one:
Spot the bug in each Java code snippet. Lesson 1.2 focus: primitives, declaration syntax, and type matching.
Click on the line that contains the bug:
Variables Bug Hunt Complete!
Java Wordle: Variables
Guess the Java keyword. Lesson 1.2 focus: primitive types, declaration keywords, naming traps.
The Library Checkout System
Mr. Chen’s computer science class is designing a small library checkout system. The program needs to track, for each book: the book’s ID number (whole numbers from 1 up to several thousand), the late fee owed on the book (which can include cents), and whether the book is currently checked out. One student suggests declaring the variables this way, all in their main method:
double bookId = 4271.0;
int lateFee = 2.50;
boolean isCheckedOut = "true";
Mr. Chen looks at the declarations and tells the student that two of the three will not compile, and the third compiles but uses an inappropriate type for the AP CSA design standard.
Part A: Which declaration is technically valid but uses the wrong type?
double bookId = 4271.0; compiles, but a book ID is a whole number, so int is the appropriate type.int lateFee = 2.50; compiles, but should use double for clarity.boolean isCheckedOut = "true"; compiles, but Boolean values shouldn’t be in quotes.double bookId = 4271.0; is the one that compiles but uses the wrong type. The syntax is valid Java, but a book ID is always a whole number, so the appropriate AP CSA type is int. B is wrong because int lateFee = 2.50; does not compile at all (decimal value into an int variable). C is wrong because "true" is a String literal, not a Boolean, so that declaration also fails to compile. D is wrong because option A does compile.
Part B: Which declaration has a clear syntax error?
double bookId = 4271.0;
int lateFee = 2.50; (storing a decimal value into an int variable).boolean isCheckedOut = "true";
int lateFee = 2.50; is the clearest type-mismatch error: the right side is a double literal (2.50) and the variable is declared int. Java refuses to implicitly narrow a double to an int. A is wrong because double bookId = 4271.0; is perfectly valid syntax (a double can hold 4271.0). C also fails to compile, but D over-claims: while C does have a type mismatch, the question asks for the clearest single example, and only one answer can be correct in standard AP MCQ format.
Part C: Structured response
In four to six sentences, rewrite all three declarations correctly so they compile and use the most appropriate AP CSA primitive type for what each value represents. Then explain in one or two sentences why a String in quotes (like "true") is not the same as the Boolean value true in Java, even though they look similar.
Scoring rubric
bookId as int bookId = 4271; (correct type for whole number).
Full 1 pt
lateFee as double lateFee = 2.50; (correct type for decimal value).
Full 1 pt
isCheckedOut as boolean isCheckedOut = true; (Boolean literal, no quotes).
Full 1 pt
String "true" (text/characters) and the boolean value true (a primitive truth value).
Partial 0.5 pt
long, float, etc.) in the rewrites.
Zero 0 pt
Sample full-credit response
The corrected declarations are: int bookId = 4271; because book IDs are whole numbers; double lateFee = 2.50; because a late fee can have cents; and boolean isCheckedOut = true; because checkout status is exactly true or false. The original isCheckedOut = "true"; would not compile because "true" in double quotes is a String, a sequence of four characters: t, r, u, e. The boolean literal true is a primitive value, not a string. Java’s static type checking refuses to assign a String to a boolean variable because they are entirely different types, even though they look similar to a human reader.
Common AP exam traps
The exam tests these same mistakes year after year. Spotting them in May starts with recognizing them now.
Trap 1: Out-of-scope primitives as distractors
Answer choices that mention long, short, byte, float, or char are always wrong on the AP CSA exam by definition of course scope. If you see them, eliminate them immediately. The only correct primitives are int, double, and boolean.
Trap 2: Storing decimals in int
An assignment like int x = 2.5; does not compile. Java refuses to assign a double value to an int variable without explicit conversion (covered in Lesson 1.3). The compiler reports a type mismatch error.
Trap 3: Confusing "true" with true
A Boolean literal is true or false, lowercase, no quotes. Quoting them turns them into String values, which cannot be assigned to a boolean variable. The exam tests this directly.
Trap 4: Variable names that start with a digit
int 1stPlace is a syntax error. The first character must be a letter, an underscore, or a dollar sign. place1 and firstPlace are valid; 1stPlace is not.
Why money is usually not stored as double in real systems
The AP exam expects double for any quantity with a decimal part, including money. In real production systems, though, financial software almost never uses double for money. The reason is that double stores values in binary floating-point format, which cannot exactly represent simple decimals like 0.1. Adding 0.1 + 0.2 in Java produces 0.30000000000000004, close, but not exact. Over millions of transactions, those rounding errors compound. Real banking software uses arbitrary-precision decimal types (Java’s BigDecimal, or in some languages a dedicated “money” type) that store the digits exactly. This is beyond the AP CSA scope, but it’s worth knowing that “the most appropriate type on the exam” and “the most appropriate type in industry” are not always the same answer.
This material extends beyond the AP CSA curriculum. Skip it if you’re focused on exam prep.
Deep dive: more on this topic
Java Language Specification: Types and Values
Official documentation defining all of Java’s primitive and reference types.
AP CSA Vocabulary List
150+ terms with AP-exam definitions.
Unit 1 Study Guide
Full unit overview with examples and practice.
Daily Practice Question
A new AP CSA question every day, free.
Get the AP CSA daily practice question by email
Free, daily, takes 90 seconds. Built by an AP CSA teacher with a 54.5% 5-rate.
Start daily practice →Get in Touch
Whether you're a student, parent, or teacher — I'd love to hear from you.
Just want free AP CS resources?
Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]