理解String

 String str=”kvill; 
String str=new String (“kvill”);的区别:  

    String s0=”kvill”; 
    String s1
=”kvill”; 
    String s2
=”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:

package testPackage;
class Test {
   
public static void main(String[] args) {
        String hello 
= "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());
        }

}

class Other static String hello = "Hello"; }
package other;
public class Other static String hello = "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、付费专栏及课程。

余额充值