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)