Variables & Data Types - Complete Interactive Lesson
Part 1: Core Concepts
📦 Variables & Data Types
Part 1 of 7 — Primitive Types, Declarations, and Casting
Primitive Data Types in Java
| Type | Size | Range / Description | Example |
|---|---|---|---|
| int | 32 bits | -2,147,483,648 to 2,147,483,647 | int count = 42; |
| double | 64 bits | Decimal numbers (floating-point) | double gpa = 3.95; |
| boolean | 1 bit | true or false only | boolean passed = true; |
🔑 The AP CSA subset uses exactly three primitive types: int, double, and boolean. Java has other primitives (such as char and long), but they are outside the AP Java subset and never appear on the exam. Text is stored in a String, which is an object, not a primitive.
Declaring and Initializing Variables
// Declaration (no value yet)
int score;
// Initialization (assigning a value)
score = 95;
// Declaration + initialization in one step
double price = 19.99;
boolean isValid = true;
Naming Conventions
- camelCase for variables and methods:
studentName,calculateAverage() - PascalCase for classes:
Student,ArrayList - ALL_CAPS for constants:
final int MAX_SIZE = 100;
Concept Check 🎯
Type Casting
| Cast Type | Description | Example | Result |
|---|---|---|---|
| Widening (implicit) | Smaller type to larger; automatic | double d = 5; | d = 5.0 |
| Narrowing (explicit) | Larger type to smaller; requires cast | int n = (int) 3.9; | n = 3 (truncated) |
Integer Division vs. Double Division
int a = 7 / 2; // 3 (integer division truncates)
double b = 7 / 2; // 3.0 (still integer division, then widened)
double c = 7.0 / 2; // 3.5 (one operand is double, so double division)
double d = (double) 7 / 2; // 3.5 (cast forces double division)
The final Keyword
final double TAX_RATE = 0.08; // Cannot be reassigned
TAX_RATE = 0.10; // COMPILE ERROR!
A final variable is a constant — its value cannot change after initialization.
Applied Recall ✍️
-
In Java, dividing two integers (7 / 2) gives _______ because the decimal is truncated.
-
To force 7 / 2 to produce 3.5, you can cast one operand: (______) 7 / 2.
-
The keyword _______ makes a variable constant (its value cannot be changed).
Classify the Type 🔍
AP Exam Strategy: Variables & Types
- Integer division is tested heavily — always check if both operands are ints
- Remember: casting to int TRUNCATES (drops decimal), it does NOT round
double d = 7 / 2;is a common trick — the division happens FIRST as int (= 3), then widens to 3.0- Know that
finalprevents reassignment but the AP exam rarely tests it directly - Trace code carefully: pay attention to what TYPE each variable is declared as
AP-Style Application 🎯
Part 2: Compiling, Errors, and What a Variable Holds
📦 Variables & Data Types
Part 2 of 7 — Compiling, Errors, and What a Variable Holds
Before a Java program does anything, two things happen. The compiler checks your source code and translates it, and then the Java Virtual Machine (JVM) runs the translated program. Knowing which stage catches which mistake (CED Topic 1.1) explains most "does not compile" answer choices. Knowing what a variable actually stores (CED Topic 1.2) explains most trace questions.
| In this part |
|---|
| From source code to a running program |
| Three kinds of errors |
| Primitive variables vs. reference variables |
| Choosing a type for the data |
From Source Code to a Running Program
| Stage | What happens | What it catches |
|---|---|---|
| Write | You type source code in a .java file | Nothing yet |
| Compile | The compiler checks the syntax and the types, then translates the code into bytecode | Syntax errors and type mismatches |
| Run | The JVM executes the bytecode one statement at a time | Run-time errors (exceptions) |
| Test | You compare the output with what you expected | Logic errors |
Three Kinds of Errors
| Error | When it is found | Example | What you see |
|---|---|---|---|
| Syntax (compile-time) error | During compiling | int count = 5 (missing semicolon) | The program does not run at all |
| Run-time error (exception) | While running | int each = total / 0; | The program stops with an ArithmeticException |
| Logic error | Only by testing | double avg = (a + b) / 2; with int a and b | The program runs but prints a wrong answer |
A type mismatch is also caught by the compiler. int n = 3.5; is rejected because a double cannot be stored in an int variable without a cast.
🔑 The compiler never runs your code. It cannot know that a variable will hold 0 at run time, so
total / countcompiles even whencountturns out to be 0. That division fails only when it actually executes.
Concept Check 🎯
What a Variable Holds
A variable is a named storage location. Every variable is declared with a type, and the type decides which values it can hold and which operations are allowed on it.
| Category | Types in the AP subset | What the variable stores |
|---|---|---|
| Primitive | int, double, boolean | The value itself |
| Reference | String and every other class type | A reference to an object, or null |
int seats = 30; // stores the value 30
boolean full = false; // stores the value false
String room = "B12"; // stores a reference to a String object
Rules the Compiler Enforces
- A variable must be declared with a type before it is used, and its type never changes. After the lines above,
seats = "thirty";is a compile-time error. - A variable can be declared only once in the same scope. To change
seatslater, writeseats = 32;, notint seats = 32;. - Java is case-sensitive:
Seatsandseatsare two different identifiers.
Choosing a Type
| Data to store | Best type | Reason |
|---|---|---|
| Number of students in a class | int | A whole-number count |
| Average temperature for a week | double | Can have a fractional part |
| Whether a door is locked | boolean | Exactly two states |
| A student's name | String | Text, stored as an object |
Pick the Best Type 🔍
Worked Example: Naming the Error
int total = 17;
int count = 4
double avg = total / count;
System.out.println(avg);
Step 1 — Compile. Line 2 is missing its semicolon. That is a syntax error, so nothing runs and nothing prints.
Step 2 — Fix and run. With the semicolon added, the code compiles and prints 4.0. The correct average of 17 and 4 is 4.25, so the program still has a logic error: total / count is int division (17 / 4 is 4), and the 4 is widened to 4.0 only when it is stored.
Step 3 — Fix the logic. Write double avg = (double) total / count;. Now 17.0 / 4 is 4.25.
A separate risk. If count were 0, the statement int each = total / count; would still compile, but it would throw an ArithmeticException when it ran, because an int cannot be divided by zero.
🔑 AP Connection: When an answer choice says "Nothing is printed because of a compile-time error," check every line's types and punctuation before you start tracing values.
Applied Recall ✍️
-
The program that checks Java source code and translates it into bytecode is called the _______.
-
An error reported while a program is running, such as dividing an int by zero, is called a run-time error or an _______.
-
How many primitive types are in the AP Java subset? _______
Summary
| Question to ask | Where the answer comes from |
|---|---|
| Will this line compile? | Syntax and type rules, checked by the compiler |
| Will this line crash? | Values at run time, such as an int divided by 0 |
| Is the output right? | Testing against the expected answer |
| What does this variable hold? | Its type: a value for primitives, a reference for objects |
AP-Style Application 🎯
Segment A
int score = 88;
score = 91.5;
System.out.println(score);
Segment B (meant to print 2.5)
int apples = 10;
int people = 4;
double share = apples / people;
System.out.println(share);
Part 3: Assignment Statements and Trace Tables
📦 Variables & Data Types
Part 3 of 7 — Assignment Statements and Trace Tables
The assignment operator = is an instruction, not a statement that two things are equal. It tells Java: evaluate the expression on the right, then store the result in the variable on the left, replacing the old value (CED Topic 1.4). Tracing these updates accurately is the most-used skill on the AP CSA exam.
| In this part |
|---|
| How an assignment statement executes |
| Trace tables |
| Worked example: swapping two values |
| Common assignment mistakes |
How an Assignment Statement Executes
- Evaluate the expression on the right, using the current values of any variables.
- Store the result in the variable on the left. Its old value is gone.
int x = 5;
x = x + 3; // right side: 5 + 3 is 8, so x now holds 8
In algebra, x = x + 3 has no solution. In Java it is an ordinary update.
| Statement | Legal? | Reason |
|---|---|---|
x = 7; | Yes | A variable is on the left |
7 = x; | No | The left side must be a variable |
x + 1 = 9; | No | The left side must be a variable |
int y = x; | Yes | Copies the current value of x into y |
Copies Are Independent
For primitive types, int y = x; copies the value. Changing x afterward does not change y.
A Variable Must Be Assigned Before It Is Read
int total;
total = total + 5; // compile-time error: total might not have been initialized
A local variable has no value until something is assigned to it, so the compiler rejects any attempt to read it first.
Concept Check 🎯
Trace Tables
A trace table has one column per variable and one row per statement. Write a new value only in the column that changes.
Worked Example
int a = 3;
int b = 8;
a = b - a;
b = b - a;
a = a + b;
| After line | a | b | Work |
|---|---|---|---|
| 1 | 3 | — | |
| 2 | 3 | 8 | |
| 3 | 5 | 8 | 8 - 3 |
| 4 | 5 | 3 | 8 - 5 |
| 5 | 8 | 3 | 5 + 3 |
The final values are a = 8 and b = 3: these three lines swap the two values without a third variable.
Tracing Tips
- One assignment changes exactly one variable.
- Always use the value from the most recent row, not the starting value.
- Write intermediate work; most trace errors are arithmetic done in your head.
Worked Example: Swapping Two Values
The broken version
int first = 10;
int second = 20;
first = second; // first is 20; the 10 is lost
second = first; // second is 20
Both variables end at 20, because the original value of first was overwritten before it was saved.
The correct version uses a temporary variable
int temp = first; // temp is 10
first = second; // first is 20
second = temp; // second is 10
🔑 AP Connection: Swapping two values with a temporary variable is the core step of the selection sort and insertion sort algorithms you will trace in Unit 4.
Trace It ✍️
int p = 6;
int q = 2;
p = p * q; // line 3
q = p - q; // line 4
p = p / q; // line 5
-
The value of p after line 3 is _______.
-
The value of q after line 4 is _______.
-
The value of p after line 5 is _______.
Common Assignment Mistakes
| Mistake | Example | What actually happens |
|---|---|---|
Reading = as "is equal to" | x = x + 1; | x increases by 1 |
| Expecting a copy to stay linked | int y = x; x = 9; | y keeps the old value of x |
| Losing a value before saving it | first = second; second = first; | Both hold the old value of second |
| Declaring a variable twice | int x = 5; and later int x = 6; | Compile-time error: x is already defined |
| Reading before assigning | int t; int u = t + 1; | Compile-time error: t is not initialized |
AP-Style Application 🎯
Segment A
int x = 2;
int y = 5;
x = y;
y = x + y;
x = x * 2;
Segment B
int total = 0;
total = total + 4;
total = total * 3;
total = total - total / 2;
Part 4: Range, Overflow, Rounding, and Round-off
📦 Variables & Data Types
Part 4 of 7 — Range, Overflow, Rounding, and Round-off
Java stores every int in 32 bits, so an int has a fixed range. A double stores an approximation of most decimal values. Both facts produce surprising output, and CED Topic 1.5 tests both directly.
| In this part |
|---|
| The range of int and integer overflow |
| Rounding a double to the nearest int |
| Round-off error with double |
The Range of int
| Constant (Java Quick Reference) | Value |
|---|---|
Integer.MAX_VALUE | 2147483647, which is 2 to the 31st power minus 1 |
Integer.MIN_VALUE | -2147483648, which is negative 2 to the 31st power |
When an int expression produces a result outside this range, integer overflow occurs. Java does not report an error. The value wraps around to the other end of the range, like an odometer rolling over:
int big = Integer.MAX_VALUE;
big = big + 1;
System.out.println(big); // -2147483648
Going the other way, Integer.MIN_VALUE - 1 evaluates to Integer.MAX_VALUE.
Overflow can happen in the middle of an expression even when the final answer looks reasonable:
int a = 50000;
int b = a * a; // 2,500,000,000 is too big for an int
System.out.println(b); // -1794967296
🔑 Overflow is not an exception. The program keeps running with a wrong value, which makes it a logic error that only testing reveals.
Concept Check 🎯
Rounding to the Nearest Integer
A cast to int truncates toward zero: (int) 3.7 is 3 and (int) -3.7 is -3. To round to the nearest integer instead, shift by 0.5 first and then truncate (CED Topic 1.5):
| x | Expression | After the shift | Result |
|---|---|---|---|
| 3.7 | (int) (x + 0.5) | 4.2 | 4 |
| 3.2 | (int) (x + 0.5) | 3.7 | 3 |
| -3.7 | (int) (x - 0.5) | -4.2 | -4 |
| -3.2 | (int) (x - 0.5) | -3.7 | -3 |
Rule: for a nonnegative x use (int) (x + 0.5); for a negative x use (int) (x - 0.5).
Worked Example: Rounding an Average
int sum = 257;
int n = 3;
double avg = (double) sum / n; // 85.666...
int rounded = (int) (avg + 0.5); // (int) 86.166... is 86
The parentheses matter. (int) avg + 0.5 casts first, giving 85 + 0.5 = 85.5, a double that cannot be stored in the int rounded without another cast.
Round It 🔍
Round-off Error with double
A double stores a limited number of binary digits, so many decimals, such as 0.1, are stored as very close approximations. Arithmetic can expose the tiny difference:
double total = 0.1 + 0.2;
System.out.println(total); // 0.30000000000000004
System.out.println(total == 0.3); // false
What to Do About It
- Do not compare computed doubles with
==. Check that they are close instead:Math.abs(total - 0.3) < 0.000001(Math.absis on the Java Quick Reference). - Money is often stored as an int number of cents, because int arithmetic is exact as long as it stays in range.
- When converting a double to an int, rounding with + 0.5 protects against values like 1998.9999999999998 that are a hair below a whole number.
🔑 AP Connection: The CED separates the two problems. Overflow is an int going out of range. Round-off error is a double that cannot be stored exactly. Expect a question about each.
Applied Recall ✍️
-
The largest value an int can hold is stored in the constant Integer._______.
-
The expression (int) (7.5 + 0.5) evaluates to _______.
-
When an int result falls outside the int range and wraps around, it is called integer _______.
AP-Style Application 🎯
Segment A
double price = 19.99;
int cents = (int) (price * 100 + 0.5);
System.out.println(cents);
Part 5: Type Compatibility, Cast Placement, and Misconceptions
📦 Variables & Data Types
Part 5 of 7 — Type Compatibility, Cast Placement, and Misconceptions
Most Unit 1 "what is printed" questions turn on two decisions: will this line compile, and when does each cast and division happen? This part gives you a reliable procedure for both, then names the misconceptions that cost the most points.
| In this part |
|---|
| Which assignments compile |
| Where the cast goes |
| Worked example: computing a percentage |
| Misconceptions to retire |
Which Assignments Compile?
| Storing... into... | Compiles? | Example | Result |
|---|---|---|---|
| an int into a double | Yes (widening) | double d = 7; | d is 7.0 |
| a double into an int | Only with a cast | int n = (int) 7.9; | n is 7 |
| a double into an int, no cast | No | int n = 7.9; | Compile-time error |
| an int into a boolean | Never | boolean b = 1; | Compile-time error |
| an int into a String | No | String s = 5; | Compile-time error |
No cast converts between boolean and a number: (int) true and (boolean) 1 are both compile-time errors.
The same widening rule applies to method arguments. Math.sqrt expects a double, so Math.sqrt(16) compiles: the int 16 widens to 16.0, and the method returns 4.0.
Concept Check 🎯
Where the Cast Goes Matters
A cast applies to the single value immediately to its right, and it happens before *, / and %. To cast a whole expression, wrap the expression in parentheses.
With int a = 7; and int b = 2;:
| Expression | Steps | Result |
|---|---|---|
(double) a / b | 7.0 / 2 | 3.5 |
a / (double) b | 7 / 2.0 | 3.5 |
(double) (a / b) | (double) 3 | 3.0 |
(int) a / b | 7 / 2 | 3 |
(int) 3.5 * 2 | 3 * 2 | 6 |
(int) (3.5 * 2) | (int) 7.0 | 7 |
Worked Example: Computing a Percentage
int correct = 17;
int total = 20;
double pct1 = correct / total * 100; // 0 * 100 is 0, stored as 0.0
double pct2 = (double) correct / total * 100; // 0.85 * 100 is 85.0
double pct3 = 100 * correct / total; // 1700 / 20 is 85, stored as 85.0
- pct1 fails: 17 / 20 is int division, which gives 0 before the multiplication happens.
- pct2 is correct: the cast makes 17.0, so every later operation is double arithmetic.
- pct3 happens to work here, but only because 1700 divides evenly by 20. With
total = 30it would give 56.0 instead of about 56.67, because the division is still int division.
Evaluate the Cast 🔍
Use int a = 9; and int b = 4;.
Misconceptions to Retire
| Belief | Reality |
|---|---|
| "Storing the result in a double makes the division exact." | The right side is evaluated first: double d = 7 / 2; stores 3.0. |
| "Casting to int rounds." | It truncates toward zero. Round with + 0.5 (Part 4). |
"(double) (a / b) fixes integer division." | The int division already happened inside the parentheses. |
| "A double holds any number exactly." | Round-off error makes 0.1 + 0.2 print 0.30000000000000004. |
| "int and double mix freely in assignments." | int to double is automatic; double to int needs a cast. |
"final makes a variable read-only from the start, so it needs no value." | A final variable must be given a value once; after that it cannot be reassigned. |
Constants in Calculations
final int MAX_SCORE = 40;
int earned = 34;
double pct = 100.0 * earned / MAX_SCORE; // 3400.0 / 40 is 85.0
Starting the expression with the double literal 100.0 makes every later step double arithmetic, so the order of the remaining operations cannot cause int division.
AP-Style Application 🎯
Segment A
int a = 5;
int b = 2;
double x = a / b;
double y = (double) a / b;
double z = (double) (a / b);
System.out.println(x + " " + y + " " + z);
Segment B
int hours = 7;
int days = 2;
double perDay = (int) (hours / (double) days);
Part 6: AP-Style Practice: Tracing and Writing Declarations
📦 Variables & Data Types
Part 6 of 7 — AP-Style Practice: Tracing and Writing Declarations
This part is exam practice. Use the same three-step routine on every item:
- Check that every line compiles. Look at each declared type and each value stored in it.
- Trace with a table. Write each variable's type at the top of its column so you remember when to add ".0".
- For writing tasks, choose the type first, then the expression, then the cast.
Multiple-Choice Practice 🎯
Segment A
int m = 14;
int n = 4;
double q = m / n + m % n / 2.0;
System.out.println(q);
Segment B
int base = 9;
base = base / 2;
double half = base / 2;
int back = (int) (half * 2);
System.out.println(base + " " + half + " " + back);
FRQ-Style Task: A Step Counter
A fitness app stores int steps and double strideInches (the length of one step). There are 63,360 inches in a mile. Write statements that:
- (a) store the distance walked, in miles, in a double;
- (b) store the number of whole miles completed in an int;
- (c) store the distance rounded to the nearest mile in an int.
Worked Solution
final int INCHES_PER_MILE = 63360;
int steps = 14000;
double strideInches = 30.5;
double miles = steps * strideInches / INCHES_PER_MILE; // 427000.0 / 63360 is about 6.74
int wholeMiles = (int) miles; // 6
int roundedMiles = (int) (miles + 0.5); // (int) 7.24 is 7
Why Each Line Earns Credit
- Types match the data: a distance can be fractional, so
milesis a double; whole and rounded miles are counts, so they are ints. - No int division:
steps * strideInchesis a double (427000.0) becausestrideInchesis a double, so the division is double division. - Truncate vs. round: a plain cast truncates for (b); the + 0.5 shift rounds for (c).
- A named constant replaces the "magic number" 63360.
Where Points Are Lost
double miles = steps / INCHES_PER_MILE * strideInches; // 14000 / 63360 is 0, so miles is 0.0
The same operations in a different order give 0.0, because steps / INCHES_PER_MILE divides two ints before strideInches ever joins the expression.
Check the Solution ✍️
Use steps = 14000, strideInches = 30.5, and INCHES_PER_MILE = 63360.
-
The int expression steps / INCHES_PER_MILE evaluates to _______.
-
The value stored in wholeMiles is _______.
-
The value stored in roundedMiles is _______.
FRQ Reasoning 🎯
Part 7: Synthesis Review
📦 Variables & Data Types
Part 7 of 7 — Synthesis Review
Three questions settle almost every Unit 1 variable problem: What type is each value? Does each line compile? What value results? This review ties Parts 1–6 together around those questions.
| Question | Where you learned it | Key rule |
|---|---|---|
| What type does this variable hold? | Parts 1–2 | int, double and boolean are primitives; String is a reference type |
| Does this line compile? | Parts 2 and 5 | int to double is automatic; double to int needs a cast; boolean never converts |
| What does this line do? | Part 3 | Evaluate the right side with current values, then store |
| Is the int still in range? | Part 4 | Overflow wraps around silently |
| Is the double exact? | Part 4 | Round-off error; avoid == on computed doubles |
| Where does the cast apply? | Part 5 | To the single value immediately to its right |
One Trace, Every Skill
final int LIMIT = 3;
int a = 11;
int b = a / LIMIT;
double c = a / (double) LIMIT;
int d = (int) (c + 0.5);
a = a - b * LIMIT;
| Line | Variable changed | Work | Value |
|---|---|---|---|
| 1 | LIMIT (final) | 3 | |
| 2 | a | 11 | |
| 3 | b | 11 / 3 with int division | 3 |
| 4 | c | 11 / 3.0 | 3.666... |
| 5 | d | (int) 4.166... | 4 |
| 6 | a | 11 - 3 * 3 | 2 |
Notice how each skill shows up: the int division in line 3, the cast in line 4 that forces double division, rounding in line 5, and an update in line 6 that uses the current values of a and b. Adding LIMIT = 4; anywhere after line 1 would be a compile-time error.
Mixed Review 🎯
Segment A
int t = 25;
double h = t / 10.0;
t = t - (int) h * 10;
Final Check 🔍
AP Exam Connection
- Unit 1 (Using Objects and Methods) is weighted 15–25% of the exam, and these variable skills reappear inside every later unit.
- On free-response questions, the same decisions decide points: declaring an average as a double, forcing double division, and rounding with a cast.
- When an answer choice reads "compile-time error," check types first. When it reads "exception," look for a division by zero. When every choice is a number, build a trace table.