Java基础:装箱和拆箱

一:装箱操作和拆箱操作

public class IntergerDemo {
	public static void main(String[] args) {
		//装箱操作:把一个基本类型的值,转换为对应包装类
		//方式一:
		Integer num1 = new Integer(17);
		//方式二:
		Integer num2 = Integer.valueOf(17);
		//拆箱操作:把包装类的对象,转换为对应的基本类型变量
		int num3 = num1.intValue();
		int num4 = (int) num2.doubleValue();
		System.out.println(num1);
		System.out.println(num2);
		System.out.println(num3);
		System.out.println(num4);
	}

}

二:自动装箱和自动拆箱

  1. 自动装箱:可以把基本类型变量直接赋给对应的包装类型变量
  2. 自动拆箱:允许把包装类对象直接赋值给对应的基本数据类型变量
		Integer num5 = 12;//自动装箱
		int num6 = num5;//自动拆箱
		System.out.println(num5);
		System.out.println(num6);

三:解释 Object obj = 17;

  1. Integer i = 17;//装箱操作
  2. Object obj = i;//自动转换类型(对象的上桩型对象)

四:常用方法,类型转换

  1. public abstract int intValue();返回指定数字的值为 int
  2. public abstract long longValue();返回指定数字的值为 long
  3. public abstract float floatValue();返回指定数字的值为 float
  4. public abstract double doubleValue();返回指定数字的值为 double
  5. public byte byteValue();返回指定数字的值为 byte
  6. public short shortValue();返回指定数字的值为 short
		Float num = 123.12f;
		int i = num.intValue();
		short s = num.shortValue();
		System.out.println(i);
		System.out.println(s);
		System.out.println(num);

五:String类型和包装类型之间的转换

  1. String类型转换成包装类,以Interger为例
      	//把String转换为包装类类型
		String str = "1111111123";
		Integer i1 = Integer.valueOf(str);
  1. 把包装类转换成String类型
		Float f = 123.1232322f;
		String str1 = f.toString();
		System.out.println(str1);
  1. 把String转换成基本数据类型
		String input = "123456";
		int n = Integer.parseInt(input);
		System.out.println(n);
  1. 把基本数据类型转成String
String str2 = 17+"";

六:包装类中的缓存设计

  1. Byte,Short,Integer,Long 在[-128,127]范围,就获取缓存地址;char在[0,127]]范围,就获取缓存地值
  2. Byte,Short,Integer,Long 不在[-128,127]范围,就开辟新的内存空间
		Integer in = Integer.valueOf(45);
		Integer in1 = Integer.valueOf(45);
		System.out.println(in == in1);//ture
		Integer in2 = Integer.valueOf(450);
		Integer in3 = Integer.valueOf(450);
		System.out.println(in2 == in3);//false

七:Integer和int的区别(包装类和基本数据类型的区别)

  1. 默认值:int为0;Integer既可以表示null,又可以表示0
  2. 包装类中提供了该类类型相关的很多算法
  3. 在集合框架中,只能存贮对象类型,不能存贮基本数据类型
  4. Integer和int是同一种数据类型吗?不是
  5. 方法中的基本数据类型变量存储到栈中,包装类型存放到堆中
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值