一、基本数据类型的包装类(以int和Integer为例)
概述
基本数据类型的创建和使用非常方便,但是我们无法通过基本数据类型调用一些功能来操作这些数据。
现在将这些基本数据类型封装成一个类,就可以在这个类中定义一些专门操作这些数据的功能
这种类就是基本数据类型的包装类。
1.1 基本数据类型与包装类的关系
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
1.2 装箱和拆箱
装箱:基本类型—>包装类
1、使用包装类的构造函数
- new Integer(int)
- new Integer(String):当字符串不是整数类型的字符串时会发生NumberFormatException异常
2、 使用包装类的静态方法 - valueOf(int)
- valueOf(String):当字符串不是整数形式的字符串时会发生NumberFormatException异常
拆箱:包装类->基本类型
1、使用包装类的成员方法
- intValue(Integer)
1.3 自动装箱和自动拆箱
jdk1.5以后,基本类型与其包装类可以实现自动的转换
自动装箱:它隐含着new Integer(t);
int t = 3;
Integer i = t;
自动拆箱:它隐含着i。intValue();
Integer i = new Integer(666);
int k = i;
1.4 包装类的功能
获取指定类型的最大最小值
Integer.MAX_VALUE
Integer.MIN_VALUE
常用方法:
1、max(int,int)
2、min(int,int)
3、toBinaryString(int)
4、toOctalString(int)
5、toHexString(int)
1.5 基本类型/包装类与字符串的转换
1、基本类型/包装类->String
- 空串的拼接
- 包装类的静态toString(数据)方法
- String的静态value(数据)方法
2、String->基本类型/包装类
- 包装类的构造函数
- 包装类的静态valueOf(String)方法
- 包装类的静态parseXxx(String)方法