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));
}
}
HELLO WORLD true false true
hello true false true
hello false false true
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.
More Gotchas problems
- var in a Loop with setTimeout · Easy
- Microtasks vs Macrotasks · Medium
- Type Coercion Surprises · Medium
- Numeric Enums at Runtime · Medium
- Type Assertions Don't Convert · Easy
- readonly and as const at Runtime · Medium