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?
Is there any way to print the contents of the String literal pool? String literals passed as arguments are also String literals, so: yes. Why would they be any different? This all happens when the String is created.
A String literal is a reference to an instance of the String class (Java 8 Language Specification - 3.10. 5 String Literals), so it's perfectly normal to be able to call methods on it. There's no difference between references to String instances (like variables) and String literals, they're one and the same.
A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string. You must always prefix wide-string literals with the letter L.
A string literal is a sequence of zero or more characters enclosed within single quotation marks. The following are examples of string literals: 'Hello, world!' 'He said, "Take it or leave it."'
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:
public class Test {
public void foo() {
bar("Bar");
}
public void bar(String s) {
System.out.println(s.equals("Bar"));
}
}
After decompiling with javap -c -verbose
you'll find out the following:
const #2 = String #19; // Bar
//...
const #19 = Asciz Bar;
public void foo();
//...
1: ldc #2; //String Bar
public void bar(java.lang.String);
//...
4: ldc #2; //String Bar
There are two entries in constant pool: one for String
(#2
) referencing the actual characters (#19
).
will String literals passed as arguments to the methods also get stored in string pool?
Of course. Why would you expect them to be any different?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With