【尚硅谷-Java学习】6.3 包装类

包装类Wrapper

基本数据类型仅仅是变量,之前所说的面向对象相关的内容都无法使用。

为使基本数据类型也能具有类的特征,针对8中基本数据类型封装了8个包装类:
在这里插入图片描述

一、基本数据类型、包装类、String类的转换

1. 基本数据类型 与 包装类

<1>基本数据类型 —> 包装类
  • int num1 = 10;
    基本数据类型转换成包装类:Integer in1 = new Integer(num1);
  • 还可以将String转换成Integer:Integer in2 = new Integer("123");
  • boolean–>Boolean:忽略大小写的。
<2>包装类 —>基本数据类型
  • 调用包装类的xxxValue方法。例如:int i1 = in1.intValue();
<3>自动装箱、自动拆箱
  • 自动装箱:有int i1 = 12;
    那么有Integer in1 = i1;
  • 自动拆箱:int i2 = in1;

2. 基本数据类型/包装类 与String

<1>基本数据类型/包装类 —> String

使用String.valueOf():

int i1 = 12;Integer in1 = 22;
那么String s1 = String.valueOf(i1);
String s1 = String.valueOf(in2);

<2> String —> 基本数据类型/包装类

使用包装类的parsexxx方法:

String s1 = "true";
那么boolean b1 = Boolean.parseBoolean(s1);

二、练习

练习1.

Object o1 = true?new Integer(1) : new Double(2.0);
System.out.println(o1);

输出:
1.0

Object o2;
if(true){
	o2 = new Integer(1);
}else{
	o2 = new Double(2.0);
}
System.out.println(o2);

输出:
1

判断语句 ?语句1:语句2 结构有一个要求:语句1和语句2需要是同类型,因此Integer转换成Double。

练习2.

		Integer i = new Integer(1);
		Integer j = new Integer(1);
		System.out.println(i==j);//false
		
		Integer m = 1;
		Integer n = 1;
		System.out.println(m==n);//true
		
		Integer x = 128;
		Integer y = 128;
		System.out.println(x==y);//false

Integer内部定义了缓存IntegerCache结构,缓存中定义了数组Integer[ ],保存了-128 到 127 范围的整数。如果使用自动装箱的方式,在该范围内的赋值可以直接使用数组中的元素(不用 new)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值