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
).