Java 包装类与基本数据类型的比较 整型 装箱拆箱 int Integer

主要通过打印验证包装类与基本数据类型之间的比较,讲解比较少,代码以int 和 Integer为例,看代码吧

拆装箱: jdk1.4以后,包装类提供了自动拆箱自动装箱的过程。 即java会在 int--Integer /  double--Double等包装类与对应的基本数据类型之间进行自动转换,无需代码(例如:Integer.valueOf(int)等)转换。

import java.io.*;
class test  
{
	public static void main (String[] args) throws java.lang.Exception
	{
	
	    //--------跨类型  int 与integer 拆装箱 ------------------------
	    int i = 128;                        
		Integer j = new Integer(128);       
		Integer k = 128;                    

		System.out.println(i == j);         //true 拆箱 
		System.out.println(i == k);         //true 拆箱
		System.out.println(j.equals(i));    //true 装箱 
		System.out.println(k.equals(i));    //true 装箱 
	
	    //-------同类型(Integer)-------------------------------------
        // "="给对象赋值
        // 赋值范围-128~127,使用常量池,==比较为true
		Integer i1 = 1;
		Integer j1 = 1;

		System.out.println(i1 == j1);       //true
		System.out.println(i1.equals(j1));  //true
		
        // "="给对象赋值
		//超范围(-128以下 127以上),建对象,对象间==比较为False
		Integer i11 = 128;
		Integer j11 = 128;
		System.out.println("1-2");
		System.out.println(i11 == j11);       //fale
		System.out.println(i11.equals(j11));  //true
		
		//"new" 建对象赋值,不考虑范围,对象间==比较都为False
	    Integer i2 = new Integer(1); 
		Integer j2 = new Integer(1); 

		System.out.println(i2 == j2);       //false
		System.out.println(j2.equals(i2));  //true
		
		// = & new (混合),对象间==比较都为False
		Integer i3 = 1; 
		Integer j3 = new Integer(1); 
		System.out.println("\n3");
		System.out.println(i3 == j3);       //false
		System.out.println(j3.equals(i3));  //true

	}
}

输出结果:


true
true
true
true


true
true

false
true


false
true


false
true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值