Card 08/ 09

ExerciseDifficulty: Intermediate1 min

Six Expressions: Write Down the Value First

Six lines, each printing one value. Write all six answers down before you open the reveal — guessing and checking one at a time teaches much less than committing to all six.

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
9 / 24Two int values, so the remainder is discarded
9 % 21% produces the remainder that / threw away
2 + 3 * 4 - 6 / 211(3*4) and (6/2) bind first: 2 + 12 − 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 — which is why an expression that uses a variable twice and increments it once is a line to rewrite rather than a line to reason about.