Short on time? This page is the recap. For explanations and worked examples, use the full study guide.
Recap
System.out.println(x)displaysxand moves to a new line.System.out.print(x)displaysxand stays on the same line.- A string literal is characters in double quotes. Escape sequences start with a backslash:
\"is a double quote,\\is a backslash and\nis a new line. Each is one character. - The arithmetic operators are
+,-,*,/and%. - Two
intoperands give anint. At least onedoubleoperand gives adouble. - Integer division keeps only the integer part of the quotient:
7 / 2is 3. a % bis the remainder whenais divided byb:17 % 5is 2.- Dividing an
intby the integer zero throws anArithmeticException.
Key relationships
| Expression | Value | Reason |
|---|---|---|
7 / 2 |
3 |
integer division |
7 / 2.0 |
3.5 |
one operand is a double |
7 % 2 |
1 |
7 = 3 * 2 + 1 |
2 + 3 * 4 |
14 |
* before + |
(2 + 3) * 4 |
20 |
parentheses first |
20 / 4 / 2 |
2 |
left to right: 5, then 2 |
7 / 2 * 2.0 |
6.0 |
7 / 2 is 3 first, then 3 * 2.0 |
n % 10 |
last digit of n |
remainder after removing groups of ten |
n / 10 |
n without its last digit |
integer division by ten |
197 / 60 and 197 % 60 |
3 and 17 | whole hours and leftover minutes |
Assumptions and conventions
%is used with a non-negative first operand and a positive second operand in this course.- The result type is decided one operation at a time, in evaluation order.
- Expressions that give special
doublevalues (such as infinity) are outside the course. - No calculator is allowed on the exam, so evaluate by hand, one step per line.
Mistakes to avoid
- Expecting
7 / 2to be 3.5. - Thinking integer division rounds instead of truncating.
- Evaluating strictly left to right without applying precedence.
- Forgetting that equal-precedence operators go left to right (
10 - 4 - 3is 3). - Writing a lone backslash in a string, or forgetting the closing quote.
- Using
printwhenprintlnis needed, so the output runs together. - Dividing by a variable that holds 0, which compiles but throws an exception.
Quick self-check
- What does
System.out.print("a"); System.out.println("b"); System.out.print("c");leave on screen? (abon the first line andcon the second, with the cursor still after thec.) - Evaluate
5 + 7 % 3 * 2. (7 % 3 is 1; 1 * 2 is 2; 5 + 2 is 7.) - Evaluate
9 / 2 + 9 / 2.0. (4 + 4.5 = 8.5.) - What is
345 % 100? (45.) - What happens when
int n = 0; System.out.println(10 % n);runs? (It compiles; at run time anArithmeticExceptionis thrown.)
Next: practice questions.