java:==的使用

public class StringInMemory {
   public static void main(String[] args) {
        String a1="hello";
        String a2=new String("hello");
        System.out.println(a1==a2); //结果为false,a2在堆上


        String S1="hello";
        String S2=new String("hello");
        System.out.println(S1==S2.intern());  //结果为true,因为intern()是返回对象常量池中的值,如果常量池中没有它的值,那就创建一个
        //然后再返回


        String p1="hello";
        String p2="he"+"llo";
        System.out.println(p1==p2);  //结果为true ,p2中两个值相加jvm可以做优化。
        //对比:
        String m1="hello";
        String m2="he";
        String m3="llo";
        String m4=m2+m3;
        System.out.println(m1==m4);  //结果为false,m2m3两个变量相加,jvm没有办法优化成常量值,等于在堆上又生成一个对象,但并没有给他赋值
        //所以堆上的对象和常量池中的对象相比是不等的

        int i1=10;
        Integer i2=10;
        System.out.println(i1==i2);  //结果为true

        Integer w1=10;
        Integer w2=10;
        System.out.println(w1==w2);  //结果为true

        //Integer在-128到127范围内,它都在常量池中创建。如果有返回引用,没有就创建,再范围

        Integer r1=128;
        Integer r2=128;
        System.out.println(r1==r2);  //结果为false
        //因为是128 超范围了,不在常量池里

      //所以int等基本数据类型不管多少都在常量池里面,而Integer要看范围,范围内就在常量,超范围就不在了


    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值