java中int和integer的区分
● int是基础数据范例,int变量存储的是数值;Integer是援用数据范例,现实是一个对象,Integer存储的是援用对象的地点。
● int默认值是0,Integer默认值是null;
● int范例直接存储数值,Integer须要实例化对象,指向对象的地点。
【引荐进修:Java视频教程】
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。
两个非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的区分是什么?的细致内容,更多请关注ki4网别的相干文章!