理解String

Java字符串常量池解析
本文探讨了Java中字符串常量池的工作原理,通过实例解释了字符串常量如何被存储和引用,以及不同字符串创建方式之间的区别。文章还介绍了字符串字面量在编译期间的处理方式,并对比了运行时字符串连接的行为。

Stringstr=”kvill;
Stringstr=newString(“kvill”);的区别:

Strings0=”kvill”;
Strings1
=”kvill”;
Strings2
=”kv”+“ill”;
System.out.println(s0
==s1); // 结果是 True
System.out.println(s0
==s2); // 结果也是 True

Java会确保一个字符串常量只有一个拷贝。
因为例子中的s0和s1中的”kvill”都是字符串常量,它们在编译期就被确定了,所以s0==s1为true;而”kv”和”ill”也都是字符串常量,当一个字符串由多个字符串常量连接而成时,它自己肯定也是字符串常量,所以 s2也同样在编译期就被解析为一个字符串常量,所以s2也是常量池中”kvill”的一个引用。
所以我们得出s0==s1==s2;

在JAVA language specification中的3.10.5 String Literals有相关说明:

the test program consisting of the compilation unit:

packagetestPackage;
classTest...{
publicstaticvoidmain(String[]args)...{
Stringhello
="Hello",lo="lo";
System.out.print((hello
=="Hello")+"");
System.out.print((Other.hello
==hello)+"");
System.out.print((other.Other.hello
==hello)+"");
System.out.print((hello
==("Hel"+"lo"))+"");
System.out.print((hello
==("Hel"+lo))+"");
System.out.println(hello
==("Hel"+lo).intern());
}

}

classOther...{staticStringhello="Hello";}
packageother;
publicclassOther...{staticStringhello="Hello";}

produces the output:

true true true true false true

This example illustrates six points:
• Literal strings within the same class in the same package represent
references to the same String object .
• Literal strings within different classes in the same package represent references
to the same String object.
• Literal strings within different classes in different packages likewise represent
references to the same String object.
• Strings computed by constant expressions are computed at compile
time and then treated as if they were literals.
• Strings computed by concatenation at run time are newly created and therefore
distinct.
The result of explicitly interning a computed string is the same string as any
pre-existing literal string with the same contents.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值