Java之int和Integer

int是基本数据类型之一,而Integer是一个包装类。

一、默认值
Integer的默认值为:null;
int的默认值为:0;

二、在内存中的存储
(1):因为定义a后,常量池中已经有“10”这个数据了,所以再次定义相同的数据时,就会将已经存有的数据的地址赋给变量b,所以a和b的地址是相等的。

public static void main(String[] args) {
        int a = 10;
        int b = 10;
        System.out.println(a == b);//true
    }

在这里插入图片描述
(2):当比较两个不是new出来的Integer对象时,因为Integer内部已经缓存了-128到127之间的数,所以如果两个变量的值在区间[-128,127]之间,比较的结果为true,否则为false。

public static void main(String[] args) {
        Integer a = 10;
        Integer b = 10;
        Integer c = 128;
        Integer d = 128;
        System.out.println(a == b);//true
        System.out.println(c == d);//false
    }

(3):不是new出来的Integer对象指向常量池中的对象;而new出来的对象则指向堆中新建的对象,二者在内存中的地址是不一样的。

 public static void main(String[] args) {
        Integer a = 10;
        Integer b = new Integer(10);
        System.out.println(a == b);//false
    }

在这里插入图片描述
(4):基本数据类型int和包装类型Integer(无论是否new)比较时,Integer会自动拆箱为int,然后再比较。(通常情况下,Integer和int比较,只要两个变量的值是相等的,结果都为true)。

  public static void main(String[] args) {
        int a = 10;
        Integer b = 10;
        Integer c = new Integer(10);
        System.out.println(a == b);//true
        System.out.println(a == c);//true
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值