16

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?

Radu Murzea
  • 10,724
  • 10
  • 47
  • 69
a Learner
  • 4,944
  • 10
  • 53
  • 89
  • 3
    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. Does not matter what happens to it (what you do with it) later on. – Thilo Jun 23 '12 at 12:53
  • 2
    You can print out all String literals in the symbol table of a .class with `javap` command. It will lists String literals that is used in the code. – nhahtdh Jun 23 '12 at 12:56

3 Answers3

22

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

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
5

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?

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
1

As for inspecting the String literal pool, @Puneet seems to have written a tool for that.

Community
  • 1
  • 1
Thilo
  • 257,207
  • 101
  • 511
  • 656