温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java中int和integer的区别有哪些?

发布时间:2020-05-09 10:03:40 来源:亿速云 阅读:602 作者:小新 栏目:编程语言

这篇文章主要为大家详细介绍了java中int和integer的区别有哪些,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

java中int和integer的区别

 ● int是基本数据类型,int变量存储的是数值;Integer是引用数据类型,实际是一个对象,Integer存储的是引用对象的地址

 ● int默认值是0,Integer默认值是null;

 ● int类型直接存储数值,Integer需要实例化对象,指向对象的地址。

int和Integer所占内存比较:

Integer对象会占用更多的内存。Integer是一个对象,需要存储对象的元数据。但是int是一个原始类型的数据,所以占用的空间更少。

非new生成的Integer变量与new Integer()生成的变量比较,结果为false。

/**
 * 比较非new生成的Integer变量与new生成的Integer变量
 */public class Test {
    public static void main(String[] args) {
        Integer i= new Integer(200);
        Integer j = 200;
        System.out.print(i == j);        //输出:false
    }
}

因为非new生成的Integer变量指向的是java常量池中的对象,而new Integer()生成的变量指向堆中新建的对象,两者在内存中的地址不同。所以 输出为false。

java中int和integer的区别有哪些?

两个非new生成的Integer对象进行比较

如果两个变量的值在区间[-128,127]之间,比较结果为true;否则,结果为false。

/**
 * 比较两个非new生成的Integer变量
 */public class Test {
    public static void main(String[] args) {
        Integer i1 = 127;
        Integer j1 = 127;
        System.out.println(i1 == j1);//输出:true
        Integer i2 = 128;
        Integer j2 = 128;
        System.out.println(i2 == j2);//输出:false
    }
}

java在编译Integer i1 = 127时,会翻译成Integer i1 = Integer.valueOf(127)。

Integer变量(无论是否是new生成的)与int变量比较

只要两个变量的值是相等的,结果都为true。

/**
 * 比较Integer变量与int变量
 */public class Test {
    public static void main(String[] args) {
        Integer i1 = 200;
        Integer i2 = new Integer(200);        int j = 200;
        System.out.println(i1 == j);//输出:true
        System.out.println(i2 == j);//输出:true
    }
}

包装类Integer变量在与基本数据类型int变量比较时,Integer会自动拆包装为int,然后进行比较,实际上就是两个int变量进行比较,值相等,所以为true。

以上就是java中int和integer的区别有哪些的简略介绍,当然详细使用上面的不同还得要大家自己使用过才领会。如果想了解更多,欢迎关注亿速云行业资讯频道哦!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI