Expressions & Operators - Complete Interactive Lesson
Part 1: Core Concepts
➗ Expressions & Operators
Part 1 of 7 — Arithmetic, Assignment, and the Modulus Operator
Arithmetic Operators
| Operator | Operation | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 6 * 7 | 42 |
/ | Division | 7 / 2 | 3 (int) or 3.5 (double) |
% | Modulus (remainder) | 7 % 3 | 1 |
🔑 Modulus (%) returns the remainder after division. It is essential for checking even/odd, extracting digits, and cycling through values.
Modulus Use Cases
| Expression | Result | Use Case |
|---|---|---|
n % 2 == 0 | true if n is even | Even/odd check |
n % 10 | Last digit of n | Extracting ones digit |
n / 10 | Removes last digit | Extracting tens digit (int division) |
n % 3 == 0 | true if n divisible by 3 | Divisibility check |
Compound Assignment Operators
| Operator | Equivalent To | Example |
|---|---|---|
+= | x = x + n | x += 5; |
-= | x = x - n | x -= 3; |
*= | x = x * n | x *= 2; |
/= | x = x / n | x /= 4; |
%= | x = x % n | x %= 3; |
++ | x = x + 1 | x++; |
-- | x = x - 1 | x--; |
Concept Check 🎯
Order of Operations (Precedence)
| Priority | Operators | Description |
|---|---|---|
| 1 (highest) | () | Parentheses |
| 2 | * / % | Multiplication, division, modulus |
| 3 | + - | Addition, subtraction |
| 4 (lowest) | = += -= etc. | Assignment |
Example Traces
int result = 2 + 3 * 4; // 2 + 12 = 14 (not 20)
int result2 = (2 + 3) * 4; // 5 * 4 = 20
int result3 = 10 - 4 / 2; // 10 - 2 = 8 (not 3)
int result4 = 15 % 4 + 2; // 3 + 2 = 5
String Concatenation with +
String name = "AP";
int score = 5;
System.out.println(name + " Score: " + score);
// Output: AP Score: 5
// Watch for this trick:
System.out.println(1 + 2 + " cats"); // "3 cats" (1+2 computed first)
System.out.println("cats " + 1 + 2); // "cats 12" (string concat left to right)
Applied Recall ✍️
-
The expression 23 % 5 evaluates to _______.
-
In Java, multiplication and division have _______ precedence than addition and subtraction.
-
The expression "Score: " + 3 + 4 evaluates to the string "_______".
Evaluate the Expression 🔍
AP Exam Strategy: Expressions & Operators
- Modulus (%) appears on almost every AP exam — know how to extract digits and check divisibility
- Watch for operator precedence tricks — always evaluate * / % before + -
- String concatenation with + is a classic trap:
1 + 2 + " cats"vs"cats " + 1 + 2 - Trace code step by step — do not try to evaluate complex expressions in your head all at once
- Remember: integer division and modulus work together.
123 / 10 = 12and123 % 10 = 3
AP-Style Application 🎯
Part 2: Output with print and println
➗ Expressions & Operators
Part 2 of 7 — Output with print and println
Almost every AP CSA trace question ends with "What is printed?" To answer exactly, you need to know where each line break comes from, how string literals are written, and how an expression is turned into text (CED Topic 1.3).
| In this part |
|---|
| print vs. println |
| Escape sequences |
| Building output with concatenation |
print vs. println
| Statement | What it does |
|---|---|
System.out.print(x); | Displays x and leaves the cursor on the same line |
System.out.println(x); | Displays x, then moves to the next line |
System.out.println(); | Displays nothing and moves to the next line (ends the current line) |
Worked Example
System.out.print("AP ");
System.out.print("CSA");
System.out.println("!");
System.out.println("Done");
Output:
AP CSA!
Done
Trace: the first two calls stay on one line, giving AP CSA. The println("!") adds the ! and then ends the line, so Done starts on a new line.
🔑 The line break comes after the text, not before it.
printlnnever starts a new line before printing; it ends the line after printing.
Literals
A literal is a fixed value written directly in code.
| Literal | Type |
|---|---|
"Hello" | String (in double quotes) |
42 | int |
3.0 | double (has a decimal point) |
true | boolean |
Concept Check 🎯
Segment A
System.out.print("one");
System.out.println("two");
System.out.print("three");
System.out.println();
System.out.println("four");
Escape Sequences
Some characters cannot be typed directly inside a string literal. An escape sequence starts with a backslash. The AP subset uses three:
| Escape sequence | Prints |
|---|---|
\" | a double quotation mark |
\\ | a single backslash |
\n | a line break |
Worked Example
System.out.println("She said \"hi\"\nC:\\temp");
Output:
She said "hi"
C:\temp
Trace: \" prints a quotation mark without ending the string, \n breaks the line, and \\ prints one backslash. The println then ends the second line.
Read the Literal 🔍
Building Output with Concatenation
Java evaluates the whole expression inside the parentheses before printing it. Part 1 showed that + works left to right and switches to concatenation once a String is involved. Here is how that plays out in realistic output lines:
int wins = 7;
int games = 10;
System.out.println("Record: " + wins + "-" + (games - wins));
System.out.println("Win rate: " + (double) wins / games);
System.out.println(wins + games + " total, " + wins * 2 + " points");
Output:
Record: 7-3
Win rate: 0.7
17 total, 14 points
| Line | Why |
|---|---|
| 1 | The parentheses force games - wins (3) to be computed as a number before it is joined. |
| 2 | The cast and / have higher precedence than +, so 7.0 / 10 = 0.7 is computed first. |
| 3 | wins + games is int addition (17) because no String has appeared yet; wins * 2 is done before its +. |
A Compile-Time Trap
System.out.println("Diff: " + games - wins); // does not compile
"Diff: " + games becomes the String "Diff: 10", and Java cannot subtract an int from a String. Parentheses fix it: "Diff: " + (games - wins).
AP-Style Application 🎯
Segment B
int a = 4;
int b = 6;
System.out.print(a + b);
System.out.println(" " + a + b);
System.out.println(a * b + "!");
Applied Recall ✍️
-
The method that displays its argument and then moves to a new line is System.out._______.
-
The escape sequence for a line break is a backslash followed by the letter _______.
-
System.out.println("Score: " + 3 * 4); prints Score: _______
Part 3: Precedence, Associativity, and Type Promotion
➗ Expressions & Operators
Part 3 of 7 — Precedence, Associativity, and Type Promotion
Part 1 gave the precedence table. This part covers the two rules that decide the hard cases: operators at the same level run left to right, and the type of each operation is decided one operation at a time. It ends with the one arithmetic run-time error in Unit 1: dividing an int by zero.
| In this part |
|---|
| Left to right within a precedence level |
| Type promotion, one operation at a time |
| Worked example: converting temperatures |
| Dividing by zero |
Left to Right Within a Precedence Level
*, / and % share one precedence level, and + and - share a lower one. When operators share a level, Java applies them left to right.
| Expression | Steps | Result |
|---|---|---|
20 / 4 * 5 | 20 / 4 = 5, then 5 * 5 | 25 |
20 / (4 * 5) | 4 * 5 = 20, then 20 / 20 | 1 |
17 % 5 * 3 | 17 % 5 = 2, then 2 * 3 | 6 |
10 - 4 - 3 | 10 - 4 = 6, then 6 - 3 | 3 |
2 * 7 / 4 | 2 * 7 = 14, then 14 / 4 | 3 |
7 / 4 * 2 | 7 / 4 = 1, then 1 * 2 | 2 |
The last two rows use the same numbers and get different answers. With int division, the order of * and / changes the result, so you cannot rearrange them the way you would in algebra.
Full Precedence Order (AP subset)
- Parentheses
- Casts and unary minus, such as
(int)and-x *,/,%+,-- Assignment:
=,+=,-=,*=,/=,%=
Concept Check 🎯
Type Promotion Happens One Operation at a Time
Each operator looks only at its own two operands:
- int with int gives an int (division truncates).
- If either operand is a double, the other is promoted and the result is a double.
A double that appears later in an expression cannot undo an int division that already happened.
| Expression | Step by step | Result |
|---|---|---|
3 / 2 * 2.0 | 3 / 2 = 1 (int); 1 * 2.0 = 2.0 | 2.0 |
3 * 2.0 / 2 | 3 * 2.0 = 6.0; 6.0 / 2 = 3.0 | 3.0 |
1 / 2 + 1 / 2.0 | 1 / 2 = 0; 1 / 2.0 = 0.5; 0 + 0.5 | 0.5 |
5 + 7 / 2 * 1.0 | 7 / 2 = 3; 3 * 1.0 = 3.0; 5 + 3.0 | 8.0 |
Worked Example: Converting Temperatures
The formula is F = 9/5 × C + 32.
int c = 25;
double f1 = 9 / 5 * c + 32; // 9 / 5 is 1, so 1 * 25 + 32 = 57, stored as 57.0
double f2 = 9.0 / 5 * c + 32; // 1.8 * 25 + 32 = 77.0
double f3 = c * 9 / 5 + 32; // 225 / 5 = 45, then 45 + 32 = 77, stored as 77.0
- f1 is wrong because
9 / 5is int division. - f2 is right: the double literal 9.0 makes every later operation double arithmetic.
- f3 is right only by luck. With
c = 26,234 / 5is 46, giving 78.0 instead of the true 78.8.
Track the Type 🔍
Dividing by Zero
Dividing an int by the int zero throws an ArithmeticException at run time:
int students = 0;
int perStudent = 120 / students; // compiles, then throws ArithmeticException
The code compiles, because the compiler does not track the value of students. The error appears only when the division executes. In the next topic you will guard against this with an if statement that checks the divisor first.
🔑 AP Connection:
ArithmeticExceptionis the only exception CED Topic 1.3 attaches to arithmetic. When a multiple-choice option says an exception is thrown, look for an int/or%whose right operand can be 0.
AP-Style Application 🎯
Segment A
int total = 45;
int groups = 4;
double avg = total / groups * 1.0;
double avg2 = 1.0 * total / groups;
System.out.println(avg + " " + avg2);
Evaluate ✍️
-
50 / 10 / 5 evaluates to _______.
-
50 / (10 / 5) evaluates to _______.
-
2 + 3 * 4 % 5 evaluates to _______.
Part 4: Integer Division and Modulus Patterns
➗ Expressions & Operators
Part 4 of 7 — Integer Division and Modulus Patterns
Integer division and % are partners. For nonnegative ints, a / b counts how many whole groups of b fit into a, and a % b is what is left over. Together they solve a family of problems that appears on nearly every AP CSA exam: unit conversions, making change, pulling digits out of a number, and wrapping around a cycle.
| In this part |
|---|
| The division identity |
| Worked examples: time and coins |
| Digit patterns |
| Wraparound and divisibility |
The Division Identity
For nonnegative a and positive b:
a == (a / b) * b + a % b
| a | b | a / b | a % b | Check |
|---|---|---|---|---|
| 50 | 12 | 4 | 2 | 4 * 12 + 2 = 50 |
| 47 | 5 | 9 | 2 | 9 * 5 + 2 = 47 |
| 30 | 6 | 5 | 0 | 5 * 6 + 0 = 30 |
| 3 | 7 | 0 | 3 | 0 * 7 + 3 = 3 |
Read the first row as: 50 eggs fill 4 cartons of 12, with 2 eggs left over.
Facts That Follow
a % bis always between 0 andb - 1.- When
ais smaller thanb,a / bis 0 anda % bisaitself. This last row is the most common trap:3 % 7is 3, not 0. a % b == 0exactly whenbdividesaevenly.
The examples in this lesson use nonnegative operands, which is how % appears in AP problems.
Concept Check 🎯
Worked Example 1: Seconds to Hours, Minutes, Seconds
int totalSeconds = 7385;
int hours = totalSeconds / 3600; // 2
int minutes = totalSeconds % 3600 / 60; // 185 / 60 is 3
int seconds = totalSeconds % 60; // 5
System.out.println(hours + "h " + minutes + "m " + seconds + "s");
Output: 2h 3m 5s
| Step | Work |
|---|---|
| Whole hours | 7385 / 3600 = 2 (7200 seconds used) |
| Seconds left after the hours | 7385 % 3600 = 185 |
| Whole minutes in those | 185 / 60 = 3 |
| Seconds left over | 7385 % 60 = 5 |
% and / share a precedence level, so totalSeconds % 3600 / 60 runs left to right: the remainder first, then the division.
Worked Example 2: Making Change
int cents = 87;
int quarters = cents / 25; // 3
cents = cents % 25; // 12
int dimes = cents / 10; // 1
cents = cents % 10; // 2
int nickels = cents / 5; // 0
int pennies = cents % 5; // 2
The pattern repeats: / counts the coins of one size, and % keeps the amount still owed. 3 quarters + 1 dime + 0 nickels + 2 pennies = 75 + 10 + 0 + 2 = 87 cents.
Convert 500 Minutes 🔍
Use int n = 500; (a number of minutes).
Digit Patterns
Part 1 used n % 10 and n / 10. The general rule: dividing by 10, 100 or 1000 removes digits from the right, and % 10, % 100 or % 1000 keeps digits from the right.
| Goal (n = 4729) | Expression | Result |
|---|---|---|
| Ones digit | n % 10 | 9 |
| Tens digit | n / 10 % 10 | 2 |
| Hundreds digit | n / 100 % 10 | 7 |
| Last two digits | n % 100 | 29 |
| Drop the last two digits | n / 100 | 47 |
Worked Example: Digit Sum of a Three-Digit Number
int n = 583;
int sum = n % 10 + n / 10 % 10 + n / 100; // 3 + 8 + 5 = 16
n / 10 % 10 runs left to right: 583 / 10 = 58, then 58 % 10 = 8. In Unit 2 you will repeat this with a loop to handle numbers of any length.
Wraparound and Divisibility
| Pattern | Example | Result |
|---|---|---|
| Clock hours numbered 0 to 11 | (9 + 5) % 12 | 2 |
| Days numbered 0 (Sunday) to 6 (Saturday) | (4 + 10) % 7 | 0, a Sunday |
| Divisibility test | n % 3 == 0 | true when 3 divides n |
% k always lands in the range 0 to k - 1, so adding first and then taking % k wraps any total back into the cycle.
AP-Style Application 🎯
Segment A
int n = 9046;
int a = n / 100 % 10;
int b = n % 100 / 10;
System.out.println(a + b);
Applied Recall ✍️
-
1234 / 100 % 10 evaluates to _______.
-
(10 + 15) % 12 evaluates to _______.
-
After as many quarters (25 cents each) as possible are taken out of 140 cents, the number of cents left is _______.
Part 5: Compound Assignment and Tracing Updates
➗ Expressions & Operators
Part 5 of 7 — Compound Assignment and Tracing Updates
Compound assignment operators combine an arithmetic operation with assignment (CED Topic 1.6). Part 1 listed them. This part traces them, including the case that catches most students: the entire right side is evaluated before the operator is applied.
| In this part |
|---|
| The whole right side goes first |
| ++ and -- |
| Worked example: a trace table of updates |
| += with Strings |
The Whole Right Side Goes First
x op= expression; means x = x op (expression); — with parentheses around the entire right side.
int x = 4;
x *= 2 + 3; // x = 4 * (2 + 3) = 20, not 4 * 2 + 3 = 11
Each row below starts fresh with x = 10:
| Statement | Means | New x |
|---|---|---|
x += 5; | x = x + 5 | 15 |
x -= 2 * 3; | x = x - (2 * 3) | 4 |
x *= 1 + 1; | x = x * (1 + 1) | 20 |
x /= 4; | x = x / 4 | 2 |
x %= 4; | x = x % 4 | 2 |
x /= 2 + 3; | x = x / (2 + 3) | 2 |
Type Still Matters
- With an int,
/=truncates:int y = 7; y /= 2;leavesyat 3. - With a double, it does not:
double d = 7; d /= 2;leavesdat 3.5.
++ and --
count++; adds 1 to count, and count--; subtracts 1. In AP CSA these appear only as standalone statements (and in for loop headers). Using them inside a larger expression, such as y = x++ + 1;, or in prefix form (++x) is outside the course.
Concept Check 🎯
Worked Example: A Trace Table of Updates
int a = 5;
int b = 3;
a += b; // line 3
b *= a - 6; // line 4
a %= b; // line 5
b -= a; // line 6
a++; // line 7
| After line | a | b | Work |
|---|---|---|---|
| 2 | 5 | 3 | |
| 3 | 8 | 3 | 5 + 3 |
| 4 | 8 | 6 | 3 * (8 - 6) |
| 5 | 2 | 6 | 8 % 6 |
| 6 | 2 | 4 | 6 - 2 |
| 7 | 3 | 4 | 2 + 1 |
Line 4 is where most mistakes happen. Writing 3 * 8 - 6 = 18 ignores the implied parentheses; the right side a - 6 is 2, and 3 * 2 = 6.
+= with Strings
+= also works on a String variable: s += x; means s = s + (x);. Because the right side is still evaluated first, it can behave differently from writing the + signs out:
String code = "A";
code += 1 + 2; // code = "A" + (1 + 2), which is "A3"
code += "B" + 4; // code = "A3" + ("B" + 4), which is "A3B4"
String other = "A";
other = other + 1 + 2; // left to right: "A1", then "A12"
The first line adds 1 + 2 as numbers because both are ints and they are evaluated before the String is involved. In the last line, other + 1 is already a String, so the 2 is joined as text.
Trace It ✍️
int p = 12;
p -= 4; // line 2
p *= p - 5; // line 3
p %= 7; // line 4
p++; // line 5
-
The value of p after line 2 is _______.
-
The value of p after line 3 is _______.
-
The value of p after line 5 is _______.
AP-Style Application 🎯
Segment A
String s = "x";
s += 2 + 3;
s = s + 2 + 3;
System.out.println(s);
Segment B
int total = 100;
total /= 3;
total *= 3;
total += total % 4;
Part 6: AP-Style Practice: Tracing and Writing Expressions
➗ Expressions & Operators
Part 6 of 7 — AP-Style Practice: Tracing and Writing Expressions
This part is exam practice. For every trace item:
- Mark the types of every variable before you compute anything.
- Evaluate one operator at a time in precedence order, left to right within a level, writing each intermediate value.
- Watch for the moment a String appears, because every
+after it joins text.
Multiple-Choice Practice 🎯
Segment A
int x = 17;
int y = 5;
x %= y;
y += x * 2;
System.out.println(x + y + "" + x * y);
Segment B
double d = 7 / 2 + 7 % 2 / 2.0;
int k = (int) (d * 10) % 4;
FRQ-Style Task: Height Conversion
A program stores a height as int totalInches. Write statements that:
- (a) print the height in the form
5 ft 7 in; - (b) store the height in meters in a double (1 inch is 2.54 centimeters, and 100 centimeters is 1 meter).
Worked Solution
int totalInches = 67;
int feet = totalInches / 12; // 5
int inches = totalInches % 12; // 7
System.out.println(feet + " ft " + inches + " in");
double meters = totalInches * 2.54 / 100; // 170.18 / 100, about 1.70
Why Each Line Earns Credit
/and%by 12 split the inches into whole feet and leftover inches.- The spaces live inside the String literals, so the output reads
5 ft 7 in, not5ft7in. totalInches * 2.54is a double, so the division by 100 is double division.
Where Points Are Lost
int feet = totalInches / 12.0; // does not compile: the result is a double
double meters = totalInches * 254 / 10000; // 17018 / 10000 is 1, stored as 1.0
The second line uses whole numbers to avoid the decimal 2.54, but 17018 / 10000 is int division, so the answer collapses to 1.0.
Check the Solution 🔍
Now suppose totalInches = 75.
FRQ Reasoning 🎯
Part 7: Synthesis Review
➗ Expressions & Operators
Part 7 of 7 — Synthesis Review
Every expression question in this topic is answered the same way: find the order, track the type, watch for Strings. This table ties Parts 1–6 together.
| Skill | Part | Key rule |
|---|---|---|
Arithmetic and % | 1, 4 | a / b counts whole groups, a % b is the leftover |
| Output | 2 | println ends the line after printing; \n, \" and \\ are escapes |
| Order of operations | 1, 3 | Parentheses, casts, then * / %, then + -, left to right within a level |
| Type of each operation | 3 | int with int gives an int; one double makes it a double |
| Run-time error | 3 | int / or % by zero throws an ArithmeticException |
| Compound assignment | 5 | x op= e means x = x op (e) |
| String concatenation | 1, 2, 5 | Once a String appears, every later + joins text |
One Trace, Every Skill
int a = 29;
int b = 4;
b += a % b * 2; // b = 4 + (1 * 2) = 6
double r = a / b + a % b / 2.0; // 4 + 5 / 2.0 = 6.5
System.out.print(a / b + "R" + a % b); // prints 4R5 with no line break
System.out.println(" " + r); // prints a space, then 6.5, and ends the line
Output: 4R5 6.5
| Step | Skill used |
|---|---|
a % b * 2 | % and * left to right: 29 % 4 = 1, then 1 * 2 = 2 |
b += ... | The whole right side first: 4 + 2 = 6 |
a / b | int division: 29 / 6 = 4 |
a % b / 2.0 | 29 % 6 = 5, then 5 / 2.0 = 2.5, a double |
a / b + "R" + a % b | The int 4 joins "R", then 5 is joined as text |
print then println | One output line |
Mixed Review 🎯
Segment A
int a = 23;
int b = 4;
System.out.print(a / b + " ");
System.out.print(a % b + " ");
System.out.println((double) a / b);
Final Check 🔍
AP Exam Connection
- Expressions appear inside nearly every question on the exam, including every free-response question. A single int division in the wrong place can cost a point on an otherwise correct method.
- In free-response code, compute averages and percentages with a double operand early in the expression, and use
/and%together for conversions. - In multiple choice, when the answer choices differ only in a ".0", a joined digit, or a line break, slow down and trace each operator.