String Interning in Java

I found a question on Stack overflow: Strings are objects in Java, so why don’t we use ‘new’ to create them?

String literals [ie, Strings like "abcd" but not like new String("abcd")] in Java are interned – this means that every time you refer to “abcd“, you get a reference to a single String instance, rather than a new one each time.

String Interning is a method of storing only one copy of each distinct String Value, which must be immutable.

This article goes into more detail on actively using the intern() method to intern strings is useful in some cases.

Leave a Reply

Your email address will not be published. Required fields are marked *