string literals as argument to methods

南笙酒味 提交于 2020-08-06 07:29:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!