DEV Community

Akshata
Akshata

Posted on

Java String Behavior: Quick Guide

๐Ÿ”† What is the output of the following block of code?

String a1 = "Hello"; String a2 = "Hello"; System.out.println(a1 == a2); 
Enter fullscreen mode Exit fullscreen mode

โœ… 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); 
Enter fullscreen mode Exit fullscreen mode

โŒ 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); 
Enter fullscreen mode Exit fullscreen mode

โŒ 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); 
Enter fullscreen mode Exit fullscreen mode

โœ… 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)