ExerciseWarm-up
Warm-up
Make == lie to you
5 minfresher0–3 yrs
One concept, guided. Near-impossible to fail.
What this teaches
- Identical literals are one pooled object, so == accidentally works
- Anything concatenated at runtime is a fresh object, so == fails
- The compiler folds constant expressions before interning them
- equals() is the only comparison that survives contact with real input
Starter
Starter.java
/**
* Warm-up: the string pool, and why == is a trap.
*
* Predict every line before you run it. Write your prediction down — the point
* of this exercise is the lines you get wrong.
*/
public class Starter {
public static void main(String[] args) {
String a = "java";
String b = "java";
String c = new String("java");
String d = "ja" + "va";
String half = "ja";
String e = half + "va";
System.out.println("a == b : " + (a == b));
System.out.println("a == c : " + (a == c));
System.out.println("a == d : " + (a == d));
System.out.println("a == e : " + (a == e));
System.out.println("a.equals(e) : " + a.equals(e));
// TODO 1: add one line that makes `a == e` true, without changing how
// e is built.
// TODO 2: make `half` final and re-run. Does `a == e` change?
// Explain the result in a comment — it is about when the value is
// known, not about mutability.
// TODO 3: print two strings that are == to each other where neither is
// written as a literal anywhere in this file.
}
}Run it locally:
cd exercises/java/strings/string-immutability-and-pool/01-warmup
javac Starter.java -d /tmp/out && java -cp /tmp/out StarterDone when
- You produce two strings that are equals() but not ==
- You produce two that are == without either being written as a literal
- You can say which line javac folded and which one it did not
← Back to Why is String immutable, and what is the string pool?