Java mixed numeric + String concatenation: evaluate left-to-right and determine the printed result. class Q207 { public static void main(String[] args) { int i1 = 5; int i2 = 6; String s1 = "7"; System.out.println(i1 + i2 + s1); // Line 8 } }
-
A18
-
B117
-
C567
-
DCompiler error
-
E56
Answer
Correct Answer: 117
Explanation
Introduction / Context: This tests operator associativity for the + operator when mixing numeric addition and String concatenation in Java. Evaluation proceeds left-to-right; once a String is involved in a + expression, concatenation rules apply for subsequent terms.
Given Data / Assumptions:
- i1 = 5, i2 = 6, s1 = "7".
- Expression is i1 + i2 + s1.
- println converts the final expression to a String.
Concept / Approach: The + operator is left-associative. First compute 5 + 6 to produce the int 11. Then 11 + "7" triggers String concatenation, yielding "117".
Step-by-Step Solution: Compute i1 + i2 = 5 + 6 = 11. Then 11 + s1 = 11 + "7" → "117". println prints "117".
Verification / Alternative check: If you wrote i1 + (i2 + s1), then 6 + "7" becomes "67", and 5 + "67" becomes "567". Parentheses change the grouping and the result.
Why Other Options Are Wrong: "18" would require conversion of "7" to int then addition; Java does not auto-parse String to int. "567" only happens with different grouping. No compiler error is present.
Common Pitfalls: Forgetting left-to-right evaluation; assuming automatic String-to-int conversion exists.
Final Answer: 117