This is an original sample question written by itmoshi based on the exam objectives.
Show answer and explanation
Answer:A The output is 33206.
Why it is correct
Because * binds tighter than +, the expression groups as (((1 + 2) + "3") + (4 * 5)) + 6, and the + operators are evaluated left to right. 1 + 2 are both ints, so they are added to give 3; 3 + "3" has a String operand, so it concatenates to "33"; the product 4 * 5, which is 20, is appended to give "3320"; and appending 6 gives "33206". Once the left side is a String, every following + is concatenation.
The other options
- ✗ B This adds 20 and 6 as numbers (26) before concatenating. Once the left operand is a String, every later + concatenates, so 20 and 6 are never added together.
- ✗ C This treats 1 + 2 as concatenation too. Before any String appears, + between ints is ordinary addition.
- ✗ D Joining a String and an int with + is valid; the int is converted to a string automatically. A compilation error would occur if, for example, you assigned a String to an int variable.
Key takeaway
Evaluating +: * and / bind tighter than +, and a chain of + groups left to right. Each + concatenates if either of its operands is a String and adds only when both are numeric. In this expression the + with "3" produces a String, so every later + in the chain concatenates. Use parentheses for parts you want added numerically.