Java programming — Predict the console output for the following program (string concatenation and evaluation order): class SC2 { public static void main(String [] args) { SC2 s = new SC2(); s.start(); } void start() { int a = 3; int b = 4; System.out.print(" " + 7 + 2 + " "); System.out.print(a + b); System.out.print(" " + a + b + " "); System.out.print(foo() + a + b + " "); System.out.println(a + b + foo()); } String foo() { return "foo"; } }

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:

  • a = 3 and b = 4 are integers.
  • Method foo() returns the string "foo".
  • System.out.print calls are executed from left to right on one line, then a final println appends line termination.


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:

  • Options with leading 9 or repeated 34 sequences misapply numeric addition versus string concatenation.
  • Only one option preserves numeric addition for a + b before converting to string in the last println.


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

More Questions from Operators and Assignments

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion