I am aware that when we initialize a string literal to a variable this literal will be stored in the string pool by the JVM. Consider the piece of code below.
System.out.println("This is a string literal");
Does the string literal within the quotes also be stored in the string pool even if I don't initialize it to a variable?
I will preface this answer by saying that there is little practical use in gaining a deep understanding of the Java string pool. From a practical perspective, you just need to remember two things:
Don't use
==to compare strings. Useequals,compareTo, or equivalent methods.Don't use explicit
String.interncalls in your code. If you want to avoid potential problems with duplicate strings, enable the string de-duplication feature that is available in modern Java GCs.This is garbled.
Firstly, you don't "initialize" a string literal. You initialize a variable.
Secondly you typically don't / shouldn't use a string literal with
new.The normal use-case for creating a string using
newis something like this:In fact, creation and interning of the
Stringobject that corresponds to a string literal, happens either at the first time that the literal is used in an expression or at an earlier time. The precise details (i.e. when it happens) are unspecified and (I understand) version dependent.The first usage might be in a variable initialization, or it might be in something else; e.g. a method call.
So to your question:
Yes, it does. If that was the first time the literal was used, the code above may be the trigger for this to happen. But it could have happened previously; e.g. if the above code was run earlier.
As a followup, you asked:
Because the JLS 3.10.5 requires that the
Stringobjects which correspond to string literals are interned:And you asked:
The original idea for interning and the string pool was to save memory. That made sense 25 years ago when the Java language was designed and originally specified. These days even a low-end Android phone has 1GB of RAM, and interning of string literals to save a few thousand bytes is kind of pointless. Except that the JLS says that this must happen.
But the answer is No, it doesn't go against the (original) purpose. This statement:
could be executed many times. You don't want / need to create a new
Stringobject for the literal each time that you execute it. The thing is that the JVM doesn't know what is going to happen.Anyway, the interning must happen because that is what the spec says.