How does string interning work in Java 7+?

There's a thing called String Memory Pool in java, when you declare:

String str1="abc";

It goes to that memory pool and not on the heap. But when you write:

String str2=new String("abc");

It creates a full fledged object on the heap, If you again write:

String str3 = "abc"; 

It won't create any more object on the pool, it will check the pool if this literal already exists it will assign that to it. But writing:

String str4 = new String("abc");

will again create a new object on the heap

Key point is that:

A new object will always be created on the heap as many times as you keep writing:

new String("abc");

But if you keep assigning the Strings directly without using the keyword new, it will just get referenced from the memory pool (or get created if not present in the memory pool)

intern() method finds if the string is present in the memory pool if it is not it adds it to the memory pool and returns a reference to it. so after using this method the String reference of yours is not pointing to any object on the heap, it is pointing to an object in the String Memory Pool (Also, note that the memory pool only contains unique strings).


When you say new String() you get a new Object reference so consider

String a = "text";
String b = new String("text");
System.out.println(a == b);
b = b.intern();
System.out.println(a == b);

Then first a == b will display false because they are different references. If we intern() b by saying b = b.intern() we can then test again and get true. I hope that helps. The above code has worked the same way in Java since version 1.0 (and it still works this way in Java 8 today).