New误解

问题:
public class ckeef


{  public static void main(String args[])


    {  String s1,s2,s3,s4;


       s1=new String("we are students");


       s2="We are students";
       s3="We are students";


s4=new String(s1);


System.out.println(s1.equals(s2));    


       System.out.println(s3==s2);         //s2和s3为什么是对的??


       System.out.println(s1.equals(s4));    


       System.out.println(s1==s4);       //s1和s4的引用不是一样的么?为什么输出的是false??


    }


}


答案:
这个确实是容易引起混乱的。。。让人疑惑的。。。


关键在于。。。你要理解s1=new String("we are students");
 s2="We are students";
这两个是不一样的。。。。new是用新建一个对象的方法。。。。而后一种是放在常量池中的。。。你一下次再用这种方法去创建的时候。。。就会去常量池里面找,所以
s2="We are students";
       s3="We are students";


这两个是相同的。。。指向常量池中的"We are students";。。。


而s1=new String("we are students");
       s4=new String(s1);
这两个是不同的对象。。。。。尽管他们的内容是一样的。。。
就像有两个人。。。他们的名字是相同的。。。。但是并不是一样的人。。。。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值