String若干问题

主要就是string literals 1 及constant pool问题了,看以下代码。
public   class  StringExample  {
    
public static void main(String[] args) {
        String s0 
= "Programming";
        String s1 
= "Program"+"ming";
        String s2 
= new String("Programming");
        String s3 
= new String("Programming").intern();
        System.out.println(
"s0 == s1 :"+(s0==s1));
        System.out.println(
"s0 == s2 :"+(s0==s2));
        System.out.println(
"s0 == s3 :"+(s0==s3));
    }

}


运行结果:
s0 
==  s1 : true
s0 
==  s2 : false
s0 
==  s3 : true

 

public   class  StringTest {
    String s1;
    
public StringTest(){
        s1 
= "Programming";
    }

}


public   class  StringExample  {
    String s0;
    
public StringExample(){
        s0 
= "Programming";
    }

    
public static void main(String[] args) {
        System.out.println(
new StringExample().s0 == new StringTest().s1);
    }

}


运行结果:
ture

 

 


1From the Java Language Specification: “A string literal consists of zero or more characters enclosed in double quotes. Each character may be represented by an escape sequence.”

 

The “constant pool” is something that is computed at compile time and stored with the compiled .class file. It contains information on methods, classes, interfaces, …, and string literals. When the JVM loads the .class file and the s0 and s2 variables are resolved, the JVM does something called constant pool resolution. The process of constant pool resolution for string follows these steps, as taken from the Java Virtual Machine Specification (5.4):

  If another constant pool entry tagged CONSTANT_String2 and representing the identical sequence of Unicode characters has already been resolved, then the result of resolution is a reference to the instance of class String created for that earlier constant pool entry.

2This is used internal to the .class file to identify literals.
  Otherwise, if the method intern has previously been called on an instance of class String containing a sequence of Unicode characters identical to that represented by the constant pool entry, then the result of resolution is a reference to that same instance of class String.
  Otherwise, a new instance of class String is created containing the sequence of Unicode characters represented by the CONSTANT_String entry; that class instance is the result of resolution.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值