Card 08/ 09

ExerciseDifficulty: Intermediate1 min

Practice: Evaluating Six Java Expressions

Strings, division, remainders, precedence and an increment: write every value down first.

The types of the operands, the values either side of an operator, choose what + and / do, *, / and % bind before + and -, and k++ produces the old value. Use those rules to write down the value each of the six lines prints, all six before opening the answer, because committing to all six teaches more than checking one at a time.

java
System.out.println(1 + 2 + "3");
System.out.println("1" + 2 + 3);
System.out.println(9 / 2);
System.out.println(9 % 2);
System.out.println(2 + 3 * 4 - 6 / 2);
int k = 7; System.out.println(k++ + k);
The six values, and the rule behind each one
Each expression, its value, and why
ExpressionValueWhy
1 + 2 + "3"331 + 2 is two numbers, so it adds; then the string joins
"1" + 2 + 3123The string comes first, so both + are concatenation, joining text
9 / 24Two int values, so the remainder is discarded
9 % 21% produces the remainder that / threw away
2 + 3 * 4 - 6 / 2113 * 4 and 6 / 2 bind first, giving 2 + 12 minus 3
k++ + k15k++ produces 7 and leaves k at 8; then 7 + 8

The last one is the only one worth arguing with. Both halves read k, and between the two reads the increment has already happened. An expression that uses a variable twice and increments it once is a line to rewrite rather than a line to reason about.