【Java】用Integer举例来了解装箱和拆箱的用法和理解

java中的装箱和拆箱。

package integer;

public class Demo1 {
		public static void main(String[] args) {
			//类型转换:装箱
			//基本类型
			int num1 = 18;
			//使用Integer类创建对象
			Integer integer1 = new Integer(num1);
			Integer integer2 = Integer.valueOf(num1);
			System.out.println("------装箱------");
			System.out.println(integer1);
			System.out.println(integer2);
			//类型转换:拆箱
			
			Integer integer3 = new Integer(100);
			int num2 = integer3.intValue();
			System.out.println("-------拆箱------");
			System.out.println(num2);
			
			//JDK1.5之后,提供自动装箱和拆箱
			int age = 30;
			//自动装箱
			Integer integer4 = age;
			System.out.println("------自动装箱-----");
			System.out.println(integer4);
			//自动拆箱
			int age2 = integer4;
			System.out.println("-------自动拆箱------");
			System.out.println(age2);
		}
}

打印结果为:
------装箱------
18
18
-------拆箱------
100
------自动装箱-----
30
-------自动拆箱------
30

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值