codeCrawler codeCrawler - 6 months ago 7x
Java Question

Does intern() ever create a literal in the pool?

String s1=new String("abcd");

it is said that
will create a string literal in the pool if it is not already present.

My question is when will this scenario arise that string object is present but not the literal? And the intern() will have to actually go and create a new literal and then return the reference to literal.


For example:

String first = "ab";
String second = "cd";
String interned = first.concat(second).intern();

Most of the strings in a program are dynamically created: by concatenating values, receiving them over a socket, reading them from files or databases, or from the console or a GUI.

Note that your terminology is wrong. intern() doesn't create a String literal. It adds a String to the pool, and String literals (i.e. Strings appearing literally in the byte-code, like "abcd"), are stored in the pool, along with explicitly interned Strings.