AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumjavastringsoperators

~75s

When + means concatenation

What does this Java program print?

public class Main {
    public static void main(String[] args) {
        System.out.println(1 + 2 + "3" + 4 + 5);
    }
}
Show the answer and the worked solution

Correct answer: C.

3345

Worked solution

  1. 1 + 2 has two int operands, so it is ordinary addition and gives 3.
  2. 3 + "3" has a String operand, so it concatenates to "33".
  3. 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.

When + means concatenation — Aptitude Question

When + means concatenation: What does this Java program print? Answer and worked solution on CodeKairo.

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

  1. 339
  2. 1239
  3. 3345
  4. 12345
Show the answer and the worked solution

Correct answer: C. 3345

Worked solution

  1. 1 + 2 has two int operands, so it is ordinary addition and gives 3.
  2. 3 + "3" has a String operand, so it concatenates to "33".
  3. 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