Card 08/ 09
All 9 cards
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.
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
| Expression | Value | Why |
|---|---|---|
1 + 2 + "3" | 33 | 1 + 2 is two numbers, so it adds; then the string joins |
"1" + 2 + 3 | 123 | The string comes first, so both + are concatenation |
9 / 2 | 4 | Two int values, so the remainder is discarded |
9 % 2 | 1 | % produces the remainder that / threw away |
2 + 3 * 4 - 6 / 2 | 11 | (3*4) and (6/2) bind first: 2 + 12 − 3 |
k++ + k | 15 | k++ 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.