Topic 1.3 — Expressions and Output
Goal: generate output, use string literals (including escape sequences), and evaluate arithmetic expressions (int vs double).
The big idea
Expressions compute values. Output displays values.
On the exam, you’ll often determine the exact output of code—details like newlines, quotes, and integer division matter.
Output: print vs println
System.out.print(x)displaysxand stays on the same line.System.out.println(x)displaysxand then moves to a new line.
Example:
System.out.print("Hi ");
System.out.println("there");
System.out.print("!");
Output appears as: Hi there on one line, then ! on the next line.
String literals + escape sequences
A string literal is a sequence of characters inside double quotes.
Escape sequences you need:
\"(double quote)\\(backslash)\n(newline)
Examples:
System.out.println("She said, \"hi\".");
System.out.println("C:\\Users\\me");
System.out.print("Line1\nLine2");
Arithmetic expressions
Arithmetic expressions combine numbers/variables with operators. In this topic, the results are int or double.
Operators:
+ - * / %- If both operands are
int, the result is anint. - If at least one operand is
double, the result is adouble.
Division + remainder rules
- int ÷ int → integer portion only (truncates).
- double involved → decimal allowed.
a % bis the remainder whenais divided byb.
Examples:
System.out.println(7 / 2); // 3
System.out.println(7 / 2.0); // 3.5
System.out.println(7 % 2); // 1
System.out.println(2 % 3); // 2
Operator precedence
*,/,%happen before+,-.- Same-precedence operators evaluate left-to-right.
- Parentheses change grouping.
Example:
System.out.println(2 + 3 * 4); // 14
System.out.println((2 + 3) * 4); // 20
Divide by zero (int)
Integer division by 0 causes an exception.
System.out.println(10 / 0);
// ArithmeticException
(Stick to safe cases like the ones shown—AP-style questions avoid tricky edge cases.)
Quick self-check
- What’s the difference between
printandprintln? - What does
\"do inside a string literal? - Predict:
System.out.println(9 / 4); - Predict:
System.out.println(9 / 4.0); - Predict:
System.out.println(9 % 4);