๐ What is the output of the following block of code?
String a1 = "Hello"; String a2 = "Hello"; System.out.println(a1 == a2);
โ Output: true
Both a1 and a2 point to the same string in the String pool โ so == returns true.
๐ What about this?
String b1 = new String("Hello"); String b2 = new String("Hello"); System.out.println(b1 == b2);
โ Output: false
Each new String("Hello") creates a new object in the heap, so b1 and b2 are different objects โ even though the text is the same.
๐ == checks if two variables point to the same object, not just equal text. Use .equals() to compare text.
๐ Another Example
String c1 = "Hi"; c1 = c1 + "There"; String c2 = "HiThere"; System.out.println(c1 == c2);
โ Output: false
- "Hi" is a string literal stored in the pool.
- c1 + "There" is done at runtime, so a new string "HiThere" is created in the heap.
- c1 and c2 have the same content, but point to different objects.
โ๏ธ How to Make It True
String c1 = "Hi"; c1 = c1 + "There"; String c2 = "HiThere"; String c3 = c1.intern(); System.out.println(c3 == c2);
โ Output: true
- c1 is a heap object.
- c2 is the pooled "HiThere" literal.
- c1.intern() returns the pooled version, so now c3 == c2.
Top comments (0)