问题
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?
回答1:
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
).
回答2:
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?
回答3:
As for inspecting the String literal pool, @Puneet seems to have written a tool for that.
来源:https://stackoverflow.com/questions/11169641/string-literals-as-argument-to-methods