1Z0-819 · Question #157
Given: public class Tester { public static void main(String[] args) { int x = 4; int y = 2; System.out.println("x+y=" + (x+y)); } } What is the result?
The correct answer is B. x+y=6. Option B is correct because (x+y) is wrapped in parentheses, forcing arithmetic addition first - 4 + 2 = 6 - and the result 6 is then concatenated with the string "x+y=", producing x+y=6. Why the distractors fail: C (x+y=42) is the classic trap: without parentheses, Java would…
Question
Options
- AAn exception is thrown at runtime.
- Bx+y=6
- Cx+y=42
- Dx+y=x+y
How the community answered
(41 responses)- A12% (5)
- B78% (32)
- C2% (1)
- D7% (3)
Explanation
Option B is correct because (x+y) is wrapped in parentheses, forcing arithmetic addition first - 4 + 2 = 6 - and the result 6 is then concatenated with the string "x+y=", producing x+y=6.
Why the distractors fail:
- C (
x+y=42) is the classic trap: without parentheses, Java would concatenate left-to-right, treating4and2as strings and producing"x+y=42"- but the parentheses prevent this. - D (
x+y=x+y) would only occur ifxandywere literal strings rather thanintvariables; since they are integers, their values are used. - A (exception) is wrong because this is valid, compilable Java with no runtime errors.
Memory tip: In Java string concatenation, parentheses = math first. Think of it as the compiler doing the arithmetic homework inside the parentheses before joining it to the string.
Topics
Community Discussion
No community discussion yet for this question.