1Z0-803 · Question #211
Give: What is the result?
The correct answer is A. 1525. The result is determined by Java's string concatenation rules, where adding an integer to a string or a string to an integer performs string concatenation.
Question
Give:
What is the result?
Exhibit
Options
- A1525
- B13
- CCompilation fails
- DAn exception is thrown at runtime
- EThe program fails to execute due to runtime error
How the community answered
(45 responses)- A71% (32)
- B2% (1)
- C9% (4)
- D13% (6)
- E4% (2)
Why each option
The result is determined by Java's string concatenation rules, where adding an integer to a string or a string to an integer performs string concatenation.
In an expression like `1 + "5" + 2 + "5"`, Java evaluates from left to right. `1 + "5"` converts `1` to a string and concatenates, resulting in "15". Then, "15" + `2` converts `2` to a string and concatenates, resulting in "152". Finally, "152" + "5" concatenates to produce "1525".
This result (13) would only occur if all operands were integers and regular arithmetic addition was performed.
The expression `1 + "5" + 2 + "5"` is syntactically valid in Java and compiles successfully due to automatic type coercion for string concatenation.
No exception is thrown at runtime for this type of valid string concatenation operation.
The program will execute successfully as the operations are valid Java syntax and runtime behavior.
Concept tested: Java string concatenation and type coercion
Source: https://docs.oracle.com/javase/specs/jls/se17/html/jls-15.html#jls-15.18.1
Topics
Community Discussion
No community discussion yet for this question.
