Difficulty: Medium
Correct Answer: 72 7 34 foo34 7foo
Explanation:
Introduction / Context:This Java question tests how the + operator behaves with strings versus integers, and how evaluation order affects the final output when mixing numeric addition and string concatenation.
Given Data / Assumptions:
Concept / Approach:In Java, + performs numeric addition for numeric operands, but if either operand is a String, the operation becomes string concatenation from that point onward. Evaluation proceeds left to right.
Step-by-Step Solution:
Step 1: System.out.print(" " + 7 + 2 + " ") => " " + 7 => " 7"; then + 2 => " 72"; then + " " => " 72 ".Step 2: System.out.print(a + b) => 3 + 4 => 7.Step 3: System.out.print(" " + a + b + " ") => " " + 3 => " 3"; then + 4 => " 34"; then + " " => " 34 ".Step 4: System.out.print(foo() + a + b + " ") => "foo" + 3 => "foo3"; then + 4 => "foo34"; then + " " => "foo34 ".Step 5: System.out.println(a + b + foo()) => 3 + 4 => 7; then 7 + "foo" => "7foo".Verification / Alternative check:Manually run a small snippet or mentally simulate left-to-right concatenation rules to confirm each segment, ensuring where numeric addition ends and string concatenation begins.
Why Other Options Are Wrong:
Common Pitfalls:Forgetting that once a String is involved, all subsequent + operations in that expression become concatenations, and misreading whitespace in the printed tokens.
Final Answer:72 7 34 foo34 7foo
Discussion & Comments