Lesson 1.3: Expressions and Output | AP CSA

Unit 1 · Lesson 1.3 · Code Mechanics

Lesson 1.3: Expressions and Assignment

Reading time: 10–14 min · Practice: 8 exercises · Mastery: applied scenario

What you'll learn in this lesson

  • 1.3.A. Use System.out.print and System.out.println correctly and predict the exact output layout when both are mixed.
  • 1.3.B. Write string literals with escape sequences (", \, ) and explain what each produces.
  • 1.3.C. Evaluate arithmetic expressions using the five operators, apply the int/double result rule, apply operator precedence rules left-to-right, and identify when an ArithmeticException will occur.

This lesson is part of the AP CSA Course and Exam Description (effective May 2027).

AP exam weight: Integer division and operator precedence appear on nearly every AP CSA exam. Expect 2–4 questions per exam combining these topics, often as predict-the-output or spot-the-error stems.

Key Vocabulary

Term Definition
print System.out.print(x) outputs x and leaves the cursor on the same line.
println System.out.println(x) outputs x then moves the cursor to a new line.
string literal A fixed sequence of characters enclosed in double quotes, e.g. "hello".
escape sequence A backslash sequence representing a special character: \n (newline), \\ (backslash), \" (double quote).
integer division Division of two int values that drops the decimal portion; 7/2 = 3.
modulo operator The % operator; returns the remainder of integer division. 7%2 = 1.
operator precedence The rules determining evaluation order: * / % are evaluated before + -.
ArithmeticException A run-time error thrown when dividing an int by zero.

Displaying output: print vs println

Java has two methods for sending text to the screen. They live on the System.out object, and the only difference between them is what happens after the output is written.

The Rule

System.out.println(x) prints x and then moves the cursor to a new line. The next print statement starts on the line below (see Oracle PrintStream docs).
System.out.print(x) prints x and leaves the cursor right there. The next print statement continues on the same line.

That one character difference—ln—controls the entire layout of your output. AP exam questions routinely mix print and println in the same code block and ask what the output looks like. The trap is assuming every statement starts a new line.

Example

System.out.print("Score: ");
System.out.println(94);
System.out.print("Grade: ");
System.out.println("A");

Output:

Score: 94
Grade: A

The first print holds the cursor on the same line, so 94 lands right after the space. Then println advances to the next line before Grade: prints.

AP Trap

Calling System.out.println() with no argument prints a blank line and advances the cursor. Students often forget this when tracing multi-line output blocks.

String literals and escape sequences

A literal is the code representation of a fixed value. The number 42 in source code is an int literal. The text "hello" is a string literal—a sequence of characters enclosed in double quotes.

Some characters cannot appear directly inside a string because Java would misread them. The solution is an escape sequence: a backslash followed by a special character that signals a different meaning.

The Three Escape Sequences on the AP Exam

\" — a literal double-quote character inside a string
\\ — a literal backslash character
\n — a newline (moves to the next line, same effect as calling println)

Example

System.out.println("She said \"hello\" to him.");
System.out.println("Path: C:\\Users\\tanner");
System.out.print("Line one\nLine two");

Output:

She said "hello" to him.
Path: C:\Users\tanner
Line one
Line two

AP Trap

\n inside a print call still causes a line break. The escape sequence controls the cursor, not the method name. Students who assume print never advances the line get this wrong every time.

Arithmetic operators

Java supports five arithmetic operators: + (addition), - (subtraction), * (multiplication), / (division), and % (remainder). Three of those are straightforward. Two are AP exam landmines.

The int/double rule: type of result depends on operand types

When both operands are int, the result is always int. When at least one operand is double, the result is double. Java does not upgrade operands for you.

The Rule

int op intint
int op doubledouble
double op doubledouble

Examples

int p = 7 + 3;        // 10 — int + int = int
double q = 7 + 3.0;   // 10.0 — int + double = double
double r = 7.0 / 2.0; // 3.5 — double / double = double
int s = 7 / 2;        // 3 — int / int = int (truncates!)

Integer division: the most tested trap on the AP exam

When both operands of / are int, Java discards the decimal portion entirely. It does not round—it truncates toward zero.

The Truncation Rule

7 / 23 (not 3.5, not 4)
1 / 40 (not 0.25)
9 / 100 (not 0.9)
13 / 43 (not 3.25)

Memorize: any int division where the numerator is smaller than the denominator produces zero.

To force real division when your variables are ints, cast one operand to double: (double) numerator / denominator. Casting is covered in Lesson 1.5.

The remainder operator %

a % b gives the remainder after dividing a by b. On the AP exam, % appears in two patterns: checking whether a number is even (n % 2 == 0) and extracting the last digit of an integer (n % 10).

Examples

int rem1 = 17 % 5;   // 2  (17 = 3*5 + 2)
int rem2 = 10 % 2;   // 0  (10 is even)
int rem3 = 7 % 10;   // 7  (7 = 0*10 + 7)
int rem4 = 100 % 7;  // 2  (100 = 14*7 + 2)

AP Scope Reminder

The AP exclusion statement says: values less than 0 for a, and values less than or equal to 0 for b, are out of scope. You will not see -7 % 3 or 5 % 0 on the exam. Do not study negative remainder behavior.

Operator precedence

When an expression contains multiple operators, Java applies them in a specific order. On the AP exam, you need exactly two rules:

Precedence Rules

Rule 1. *, /, and % are evaluated before + and -.
Rule 2. When operators have the same precedence, evaluate left to right.
Rule 3. Parentheses override everything.

Tracing a Compound Expression

int result = 2 + 3 * 4 - 6 / 2;

Step 1: 3 * 4 = 12 (multiplication has priority)

Step 2: 6 / 2 = 3 (division, same level as *, left-to-right)

Step 3: 2 + 12 = 14 (addition)

Step 4: 14 - 3 = 11 (subtraction)

result = 11

AP Trap: Mixed Types in Compound Expressions

double d = 1 + 3 / 2;

This does not evaluate to 2.5. Division happens first (3 / 2 = 1, integer division), then 1 + 1 = 2, then 2 widens to 2.0 when stored. Result: 2.0, not 2.5.

ArithmeticException: integer divide by zero

Dividing an int by the int zero causes an ArithmeticException at run time. The code compiles fine because the compiler cannot know a variable's value ahead of execution. Same rule applies to % with a zero divisor.

Scope Note

The AP exclusion statement says dividing a double by zero (which produces Infinity) is out of scope. Only int / 0 causing an ArithmeticException is tested.

▶ Java Code Editor
Try It Yourself
Write real Java, hit Run, and your code executes on a live compiler. Output is checked automatically.
Tier 2 · AP Practice

Practice Questions

Consider the following code segment.

System.out.println("Status: ");
System.out.print("OK");
System.out.println();
System.out.print("Done");

Which of the following correctly shows the output?
Before reading the options: trace the cursor position after each statement. Where does the cursor sit after each call?
A.
Status: 
OK
Done
B.
Status: OK
Done
C.
Status: 
OKDone
D.
Status: OK Done
A. Trace each call: println("Status: ") prints the text then moves to a new line. print("OK") prints OK and leaves the cursor on the same line. println() with no argument prints nothing but advances the cursor to the next line. print("Done") prints Done on that new line without advancing. B is wrong because println("Status: ") already moved to a new line before OK appeared. C is wrong because println() advances the cursor between OK and Done. D is wrong for both reasons.
Consider the following three expressions.

I. 14 / 4
II. 14.0 / 4
III. 14 / 4 * 2

Which of the expressions above evaluate to a value of type int?
A. I only
B. I and II only
C. I and III only
D. I, II, and III
C. Expression I: 14 / 4 is int divided by int, result is int (value 3). Expression II: 14.0 / 4 has a double operand, so the result is double (value 3.5). Expression III: 14 / 4 evaluates first (left-to-right) giving 3 (int), then 3 * 2 is int times int giving 6 (int). Every operation in III uses only int operands. B is wrong because II has a double operand. D is wrong for the same reason.
Consider the following code segment.

int total = 250;
int slots = 8;
int perSlot = total / slots;
int leftover = total % slots;
System.out.println(perSlot);
System.out.println(leftover);

What is printed when the code segment executes?
Predict both values first. What is 250 divided by 8 using integer division? What is the remainder?
A.
31.25
0
B.
31
2
C.
32
0
D.
31
8
B. 250 / 8: integer division truncates. 8 goes into 250 thirty-one times (8 × 31 = 248), leaving 2. So perSlot = 31 and leftover = 250 % 8 = 2. A is wrong because int division never produces a decimal. C would require rounding up (Java truncates). D has the remainder confused with the divisor.
A student wants to print exactly:

File saved to: C:\reports\q1.txt

The student writes:

System.out.println("File saved to: C:\reports\q1.txt");

Which of the following best describes the problem with this statement?
A. println should be print because the path contains a backslash.
B. String literals cannot contain a colon character; it must be replaced with \:.
C. The path separator should use a forward slash since Java only recognizes /.
D. Each backslash in the path must be written as \\ because a single \ starts an escape sequence the compiler will not recognize.
D. Inside a Java string, the backslash is the escape character. A lone \r or \q is an unrecognized escape sequence and causes a compile error. To represent a literal backslash, write \\. The correct statement is "File saved to: C:\\reports\\q1.txt". A is irrelevant. B is wrong—colons need no escaping. C is wrong—the issue is the escape sequence, not path separators.
What value is stored in result after the following statement executes?

int result = 100 - 4 * 3 + 24 / 8 % 2;
Write out each step before choosing. Apply *, /, % first (left to right), then + and - (left to right).
A. 89
B. 91
C. 87
D. 93
A. High-precedence operators left to right: 4 * 3 = 12, then 24 / 8 = 3, then 3 % 2 = 1. Expression is now 100 - 12 + 1. Left to right: 100 - 12 = 88, then 88 + 1 = 89. B comes from doing addition before subtraction. C comes from a wrong remainder. D comes from skipping the % step.
Consider the following three code segments.

I.
int m = 5;
int n = 0;
int r = m / n;
II.
double x = 5.0;
int n = 0;
double r = x / n;
III.
int m = 5;
int n = 0;
int r = m % n;

Which of the code segments above will cause an ArithmeticException at run time?
A. I only
B. II only
C. I and III only
D. I, II, and III
C. Segment I: int / int with a zero denominator causes an ArithmeticException. Segment II: dividing a double by zero does not throw an exception—it produces Infinity, a valid double value. The AP exclusion statement confirms this is out of scope. Segment III: int % int with a zero divisor also throws an ArithmeticException. Both I and III crash; II does not.
A student writes the following code to compute the average of three test scores.

int s1 = 88;
int s2 = 92;
int s3 = 79;
double avg = s1 + s2 + s3 / 3;

The student expects avg to hold 86.333.... Instead it holds a different value. Which of the following best explains why?
A. The variable avg is declared as double, so all three scores should also be declared as double to avoid a type mismatch error.
B. Division has higher precedence than addition, so s3 / 3 is evaluated first as integer division (result: 26), then added to s1 + s2, giving 206.0 rather than the average of all three.
C. The + operator performs string concatenation when mixed types are involved, so the scores are joined as text instead of summed.
D. Integer variables cannot be assigned into a double expression without an explicit cast on each variable.
B. Operator precedence: / before +. So s3 / 3 runs first: 79 / 3 = 26 (integer division, truncated). Then 88 + 92 + 26 = 206, which widens to 206.0. The fix is to parenthesize: (s1 + s2 + s3) / 3.0. A is wrong—int widens to double automatically. C is wrong—concatenation only occurs when a String is an operand. D is wrong—widening from int to double is implicit.
What is printed when the following code segment executes?

System.out.print("Row 1\nRow 2\n");
System.out.print("Row 3");
Count the newlines carefully. Each \n is a line break regardless of whether the method is print or println.
A.
Row 1\nRow 2\nRow 3
B.
Row 1 Row 2 Row 3
C.
Row 1
Row 2
Row 3
D.
Row 1
Row 2
Row 3
D. The first print contains two \n escape sequences. Each moves the cursor to a new line: Row 1, newline, Row 2, newline. The cursor is now at the start of a new line. The second print outputs Row 3 with no trailing newline. Three lines of output, no blank line at the end. A is wrong because \n is not printed literally. B is wrong because \n is not a space. C has a spurious extra blank line at the end.
PRACTICE WITH A GAME — CHOOSE ONE:

Output Predictor — Expressions & Printing

Read each code segment. Type the exact output. Then reveal the answer.

Question 1 of 6 Score: 0

        

Bug Hunt — Expressions & Printing

Each snippet has exactly one buggy line. Click it, then submit.

Bug 1 of 7 Caught: 0

Tier 3 · AP Mastery Challenge

The School Store Vending Machine

A student writes a program for the school store vending machine. Items cost between $0.25 and $2.00. The machine accepts $1 and $5 bills. After a purchase, it should display how many quarters to return as change, then display any remaining cents it cannot return as quarters. A classmate runs the program with a $1 bill and a $0.65 item and gets unexpected output.

int priceCents = 65;
int paidCents = 100;
int changeCents = paidCents - priceCents;    // line 3
int quarters = changeCents / 25;             // line 4
int remainder = changeCents % 25;            // line 5
System.out.println("Quarters: " + quarters); // line 6
System.out.println("Leftover cents: " + remainder); // line 7

Part A: Predict the output

What does the program actually print when priceCents = 65 and paidCents = 100?
Trace each line manually before selecting. What is changeCents? What are quarters and remainder?
A.
Quarters: 1
Leftover cents: 0
B.
Quarters: 1.4
Leftover cents: 10
C.
Quarters: 1
Leftover cents: 10
D.
Quarters: 2
Leftover cents: 0
C. Trace: changeCents = 100 - 65 = 35. quarters = 35 / 25 = 1 (25 goes into 35 once, with 10 left). remainder = 35 % 25 = 10. Output: Quarters: 1 and Leftover cents: 10. A is wrong: 35 is not divisible by 25. B is wrong: int division never produces a decimal. D is wrong: 25 goes into 35 only once, not twice.

Part B: Identify the crash condition

If the divisor on lines 4 and 5 were changed from the literal 25 to a variable divisor, and divisor were initialized to 0, what would happen when the program ran?
Which lines perform integer division or remainder with that divisor? What does Java do when an int is divided by zero?
A. The program would compile with an error because dividing by zero is detected at compile time.
B. The program would compile successfully but throw an ArithmeticException at run time on the first line that divides or takes the remainder with the zero divisor.
C. The program would run and silently store 0 in both quarters and remainder without crashing.
D. The program would run and store Infinity in quarters because Java promotes the result to double when division by zero occurs.
B. The compiler cannot know the value of a variable at compile time, so the code compiles without error. At run time, the first line with a zero integer divisor (either / or %) throws an ArithmeticException and the program terminates. A is wrong—the compiler does not evaluate variable values. C is wrong—Java does not silently return 0; it throws an exception. D is wrong—quarters is declared as int, not double, and integer division by zero throws an exception rather than producing Infinity.

Part C: Structured response

A new requirement says the machine should also display the total change as a decimal dollar amount (for example, $0.35). A student adds this line after line 3:

System.out.println("Change: $" + changeCents / 100);

In three to five sentences, explain why this line does not produce the expected decimal output when changeCents = 35. Identify the Java concept that causes the error, state what the line actually prints, and rewrite the line so it correctly prints Change: $0.35.

Extension · Beyond the Exam

Formatted output with printf

System.out.printf("%.2f", value) prints a decimal rounded to two places. The AP exam does not test printf or DecimalFormat, but real Java programs use them constantly. If you want $0.35 to display as exactly two decimal places instead of something like 0.35000000000000003, printf is the standard tool.

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.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]