包装类的笔试题以及int与包装类Integer的区别

包装类的笔试题以及int与包装类Integer的区别

package lesson06;

public class Demo08 {

	public static void main(String[] args) {
		//包装类的深挖,会有笔试题
		int num = 50;//基本数据类型
		Integer inum = new Integer(50); //引用数据类型
		Integer inum2 = new Integer("50");//引用数据类型
		
		//装箱:把基本数据类型转换成对应包装类
		//拆箱:把包装类转换成基本数据类型
		
		//笔试题1
		System.out.println(num==inum);//true  Integer与int运算或赋值时会对应自动拆箱
		System.out.println(inum==inum2);//false
		
		//如何装箱??把基本数据类型转换成对应包装类  用包装类的valueOf(基本数据类型)
		Integer inum3 = Integer.valueOf(50); 
		
		//如何拆箱?? 
		int num2 = inum;  //自动拆箱
		byte b1= inum.byteValue();   //Integer===>byte
		short st = inum.shortValue(); //Integer===>short
		long lg = inum.longValue(); //Integer===>long
		int num3=inum.intValue();  //Integer===>int
		
		
		//=======int与包装类Integer的区别=========
		//区别=======
		//1.基本数据类型不同赋值为null,引用数据类型可以被赋值为null
		//int age = null;
		int age = 30;
		Integer age2 = null; //Integer它是引用数据类型,可以被赋值为null
		
		//2.用int和Integer定义数组的话,int型数组初始值为0,Integer初始值为null 
		int[] num1s = new int[5];
		Integer[] num2s = new Integer[5];
		System.out.println(num1s[0]);
		System.out.println(num2s[0]);
		
		//3.Integer如果直接赋值,不是new的时候 。如果赋值在[-128,127]之间,第一个赋值的变量,会有缓存,第二个变量在直接赋值时,取第一个变量缓存
		int nonum = 100;
		Integer nonum1 = 100;
		Integer nonum2 = 100;
		Integer nonum3 = new Integer(100);
		Integer nonum4 = -129;
		Integer nonum5 = -129;
		
		System.out.println(nonum==nonum1);  //true
		System.out.println(nonum2==nonum3); //false
		//====为啥???
		System.out.println(nonum2==nonum1); //true
		System.out.println(nonum4==nonum5); //false 为啥???
		
		//Integer如果直接赋值,不是new的时候 。如果赋值在[-128,127]之间,第一个赋值的变量,会有缓存,第二个变量在直接赋值时,取第一个变量缓存
		
       
	}

}

 


版权声明:本文为m0_43443133原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。