Predict the output · Java

String Immutability and Interning

Medium Predict the output Seen at Amazon, Microsoft, Bloomberg

What are the four lines of output?

What does this print?

public class Main {
    public static void main(String[] args) {
        String s = "hello";
        s.toUpperCase();
        s.concat(" world");
        System.out.println(s);

        String t = "hel" + "lo";
        String u = new String("hello");
        System.out.println(s == t);
        System.out.println(s == u);
        System.out.println(s.equals(u));
    }
}
  1. HELLO WORLD
    true
    false
    true
  2. hello
    true
    false
    true
  3. hello
    false
    false
    true
  4. hello world
    true
    true
    true

Check your answer

Loading the editor… (JavaScript is required to run code in your browser.)

Solution

Show the answer

The output is:

hello
true
false
true

Strings are immutable: toUpperCase() and concat() return new strings that are thrown away here, so s is still "hello". "hel" + "lo" is a compile-time constant, interned to the same pool object as "hello", so s == t is true. new String(...) always creates a new object, so s == u is false, while equals compares contents.