Warm‑up: String immutability + == vs equals() + intern() (with answer)
Warm‑up: You have two strings created in different ways (literal and new String()). Task: 1) Print whether '==' is true/false 2) Print whether equals() is true/false 3) Use intern() and check '==' again Implement ONLY: warmUp() to print 3 lines.
public class Main {
// ✅ TODO: Student must implement only this method
static void warmUp() {
// TODO:
// - create a as literal, b as new String(...)
// - print: (a==b), a.equals(b)
// - intern b and print: (a==bInterned)
throw new UnsupportedOperationException("TODO");
}
public static void main(String[] args) {
warmUp();
}
}
Answer (Logic + Code)
Logic: - '==' compares references, not content. - equals() compares content. - intern() returns pooled reference for same content, so '==' can become true.
String a = "Hello α/β ✅";
String b = new String("Hello α/β ✅");
System.out.println("a==b : " + (a == b));
System.out.println("a.equals(b) : " + a.equals(b));
String bi = b.intern();
System.out.println("a==b.intern() : " + (a == bi));