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) displays x and stays on the same line.
  • System.out.println(x) displays x and 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 an int.
  • If at least one operand is double, the result is a double.

Division + remainder rules

  • int ÷ int → integer portion only (truncates).
  • double involved → decimal allowed.
  • a % b is the remainder when a is divided by b.

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

  1. What’s the difference between print and println?
  2. What does \" do inside a string literal?
  3. Predict: System.out.println(9 / 4);
  4. Predict: System.out.println(9 / 4.0);
  5. Predict: System.out.println(9 % 4);

← Back to Unit 1 topics