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

~60s

String methods return new strings

What does this Java program print?

public class Main {
    public static void main(String[] args) {
        String s = "placement";
        s.toUpperCase();
        s.concat(" test");
        System.out.println(s);
    }
}
Show the answer and the worked solution

Correct answer: A.

placement

Worked solution

  1. Strings are immutable, so toUpperCase and concat cannot change s; they build and return new strings.
  2. Neither return value is assigned to anything, so both new strings are discarded immediately.
  3. s still refers to the original object and placement is printed.

Answer: placement.

The idea

Every String method that looks like a mutation is really a factory. The fix is s = s.toUpperCase(), and forgetting the assignment is one of the most common Java mistakes.

Shortcut. Neither call's return value is assigned, and a String never changes in place, so s prints exactly as declared.

Common trap. "PLACEMENT test" assumes both methods modify s in place; each builds a new String that is thrown away at once.

String methods return new strings — Aptitude Question

String methods return new strings: 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) {
        String s = "placement";
        s.toUpperCase();
        s.concat(" test");
        System.out.println(s);
    }
}

Options

  1. placement
  2. PLACEMENT
  3. placement test
  4. PLACEMENT test
Show the answer and the worked solution

Correct answer: A. placement

Worked solution

  1. Strings are immutable, so toUpperCase and concat cannot change s; they build and return new strings.
  2. Neither return value is assigned to anything, so both new strings are discarded immediately.
  3. s still refers to the original object and placement is printed.

Answer: placement.

The idea

Every String method that looks like a mutation is really a factory. The fix is s = s.toUpperCase(), and forgetting the assignment is one of the most common Java mistakes.

Shortcut. Neither call's return value is assigned, and a String never changes in place, so s prints exactly as declared.

Common trap. "PLACEMENT test" assumes both methods modify s in place; each builds a new String that is thrown away at once.

All Programming Fundamentals questions · placement mock tests