π 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)