字符串文字作为方法的参数 [英] string literals as argument to methods

查看:82
本文介绍了字符串文字作为方法的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中的任何String文字都是 String 类型的常量对象,并存储在String文字池中.

Any String literal in Java is a constant object of type String and gets stored in the String literal pool.

作为参数传递给方法的 String 文字也会存储在 String 文字池中吗?

Will String literals passed as arguments to the methods also get stored in the String literal pool?

例如,当我们写作时,

System.out.println("Hello");

OR

anyobj.show("Hello");

会创建 String "Hello"并将其存储在 String 文字池中吗?

will a String "Hello" be created and stored in the String literal pool?

有什么方法可以打印String文字池的内容?

Is there any way to print the contents of the String literal pool?

推荐答案

每次在代码中使用字符串字面量时(无论在何处),编译器 都会将该字符串放入符号表中并每当它在同一文件中的某处遇到相同的字符串时,都要对其进行引用.稍后这个字符串将被放置在常量池中.如果您将该字符串传递给另一个方法,它仍然使用相同的引用.字符串是不可变的,因此可以安全地重用它们.

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.

以该程序为例:

public class Test {

    public void foo() {
        bar("Bar");
    }

    public void bar(String s) {
        System.out.println(s.equals("Bar"));
    }

}

使用 javap -c -verbose 反编译后,您会发现以下内容:

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

常量池中有两个条目:一个用于 String (#2 ),它引用实际字符(#19 ).

There are two entries in constant pool: one for String (#2) referencing the actual characters (#19).

这篇关于字符串文字作为方法的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆