Expressions &
Output()
Master how Java evaluates expressions and prints results with System.out.print and System.out.println.
What Is an Expression?
An expression is any valid combination of variables, values, operators, and method calls that Java evaluates to produce a single result. Every expression has a type and a value.
"Hello" + " World" evaluates to a StringAnatomy of System.out
Java provides two primary methods for printing to the console. Both belong to the System.out object, which represents the standard output stream.
Types of Expressions in Java
Java expressions fall into several categories. The AP exam focuses on arithmetic, String, and boolean expressions, each following specific evaluation rules.
+, -, *, /, % to compute numeric resultsMath.abs(-5) return a valueOperator Precedence Rules
Java evaluates expressions using a strict order of operations, similar to math. Higher-precedence operators are evaluated first, left to right within the same level.
Integer Division & Modulo
When both operands are int values, Java performs integer division: it truncates (drops) the decimal portion. The % (modulo) operator returns the remainder.
String Concatenation with +
The + operator is overloaded in Java. When at least one operand is a String, it concatenates. Evaluation proceeds left to right, which is crucial for mixed expressions.
print vs println
| System.out.print | System.out.println | |
|---|---|---|
| Newline after output? | No | Yes |
| Empty call allowed? | No (compile error) | Yes (prints blank line) |
| Use case | Building output on one line | Printing complete lines |
| Typical AP usage | Loops printing horizontally | Most standard output |
How to Trace Output
Follow these steps to determine what a print statement produces:
*, /, % before +, -+ is arithmetic or concatenation at each stepExample 1: Basic Arithmetic
Example 2: Mixed Concatenation
Example 3: print vs println
Escape Sequences
Java uses backslash \ as an escape character inside Strings to represent special characters that cannot be typed directly.
Casting & Type Promotion
Java automatically promotes int to double in mixed expressions. You can also explicitly cast to control the type of a result.
Common Mistakes
Quick Reference Table
| Expression | Result | Type |
|---|---|---|
7 / 2 |
3 | int |
7.0 / 2 |
3.5 | double |
7 % 2 |
1 | int |
"A" + 1 + 2 |
"A12" | String |
1 + 2 + "A" |
"3A" | String |
"A" + (1 + 2) |
"A3" | String |
(double)(7 / 2) |
3.0 | double |
(double) 7 / 2 |
3.5 | double |
Question 1 of 5
What is the output of the following statement?System.out.println(10 / 3);
Question 2 of 5
What is the output of the following code?System.out.println("Result: " + 2 + 3);
Question 3 of 5
What is the output of the following code?
Question 4 of 5
What is the value of result after this line executes?double result = (double)(9 / 2);
Question 5 of 5
What does this statement print?System.out.println(5 + 3 + " apples and " + 2 + 1 + " oranges");