【Java进阶】包装类

1 包装类与基本数据类

基本类型对应的包装类
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

2 包装类的常用方法

所有的包装类都在java.lang这个包中

Character和Boolean都继承自Object类,其余的数字类型都继承自Number类

方法非常多,使用时可以查看API文档

3 基本数据类型和包装类之间的转换

装箱:基本数据类型 ----> 包装类

拆箱:包装类 ----> 基本数据类型

package com.ricky.wrap;

public class WrapTest {

	public static void main(String[] args) {
		// 装箱
		// 1. 自动装箱
		int t1 = 2;
		Integer t2 = t1;
		// 2. 手动装箱
		Integer t3 = new Integer(t1);
		
		// 拆箱
		// 1. 自动拆箱
		int t4 = t2;
		// 2. 手动拆箱
		int t5 = t3.intValue();
		// 也可以拆箱为其它数据类型
		double t6 = t2.doubleValue();
	}

}

4 基本数据类型与字符串之间的转换

package com.ricky.wrap;

public class WrapTest {

	public static void main(String[] args) {
		// 基本数据类型转换为字符串
		int t1 = 2;
		String t2 = Integer.toString(t1);
		// 字符串转化为基本数据类型
		// 1. 包装类的parse方法
		int t3 = Integer.parseInt(t2);
		// 2. 包装类的valueOf 先将字符串转换为包装类,再由自动拆箱转为基本数据类型
		int t4 = Integer.valueOf(t2);
	}

}

5 默认值

基本类型默认值
byte0
short0
int0
long0L
float0.0f
double0.0d
char‘\u0000’
booleanfalse

\u:unicode编码

包装类所有的默认值为null,如果在类中使用需要格外注意

6 对象常量池

package com.ricky.wrap;

public class WrapTest {

	public static void main(String[] args) {
		Integer one = new Integer(100);
		Integer two = new Integer(100);
		// 使用了两次new关键字,因此one和two指向的是两块不同的空间
		System.out.println(one == two); // false
		
		Integer three = 100; // 自动装箱
		// three自动拆箱
		System.out.println(three == 100); // true
		
		Integer four = 100;
		// 相当于执行了Integer four = Integer.valueOf(100);
		// Java为了提高程序执行的效率,对于[-128, 127]之间的数,如果在缓存区(对象池)中有就会直接产生,没有才会实例化Integer
		System.out.println(three == four); // true
		
		Integer five = 200;
		System.out.println(five == 200); // true
		
		Integer six = 200;
		// 不在[128, 127]之间
		System.out.println(five == six); // false
	}

}

注意:所有的包装类除了Float和Double,都可以应用对象常量池

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ricky_0528

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值