Any String literal in Java is a constant object of type String and gets stored in the String literal pool.
Will String literals passed as arguments to the methods also get stored in the String literal pool?
For example when we write,
System.out.println("Hello");
OR
anyobj.show("Hello");
will a String “Hello” be created and stored in the String literal pool?
Is there any way to print the contents of the String literal pool?
Every time you use a String literal in your code (no matter where) the compiler will place that string in the symbol table and reference it every time it encounters the same string somewhere in the same file. Later this string will be placed in the constant pool. If you pass that string to another method, it still uses the same reference. String are immutable so it is safe to reuse them.
Take this program as an example:
After decompiling with
javap -c -verboseyou’ll find out the following:There are two entries in constant pool: one for
String(#2) referencing the actual characters (#19).