When + means concatenation — Aptitude Question
When + means concatenation: What does this Java program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 75 seconds
Question
What does this Java program print?
public class Main {
public static void main(String[] args) {
System.out.println(1 + 2 + "3" + 4 + 5);
}
}Options
- 339
- 1239
- 3345
- 12345
Show the answer and the worked solution
Correct answer: C. 3345
Worked solution
- 1 + 2 has two int operands, so it is ordinary addition and gives 3.
- 3 + "3" has a String operand, so it concatenates to "33".
- From that point every + has a String on the left, so "33" + 4 gives "334" and "334" + 5 gives "3345".
Answer: 3345.
The idea
The same symbol adds numbers and joins strings, and left-to-right evaluation decides which meaning applies at each step. Once a String appears, everything after it is concatenation.
Shortcut. Eliminate: 1 + 2 is added before any String appears, so the output starts with 3, not 12, which rules out 1239 and 12345; 4 and 5 are then appended as text, not summed, which rules out 339.
Common trap. 12345 assumes the String turns every + in the line into concatenation; left-to-right evaluation adds 1 + 2 before the "3" is reached.
All Programming Fundamentals questions · placement mock tests