包装器类
我们知道Java的数据类型有基本数据类型和引用数据类型
同时基本数据类型又细分,分成四个种类的基本数据类型
一共有八种基本数据类型
引入
Java的八种数据类型只能表示一种数值,但是Java作为面向对象编程,处理的基本单位是对象。
为了能将基本数据类型视为对象处理,连接其相关方法,Java提供了包装类
概念
Java可以直接处理基本数据类型,有些情况下需要将其作为对象来处理,这时就需要将其转化为包装器类型。
Java八种数据类型对应相应的包装器类
基本数据类型
包装器类
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double
char
Character
boolean
Boolean
使用
创建
构造方法:Integer i = new Integer(10);
调用包装器类型的ValueOf()方法Double d = Double.valueOf(2.5);
特点
对象一旦赋值,其值不能再改变
类型转换
当程序进行数据操作时,需要将包装器类转换为基本数据类型
包装器类有包装好的方法进行转换。
包装器类
方法
返回的基本数据类型
Byte
byteValue()
byte
Short
shortValue()
short
Integer
intValue()
int
Long
longValue()
long
Double
doubleValue()
double
Float
floatValue()
float
Character
charValue()
char
Boolean
booleanValue()
boolean
自动装箱
装箱与拆箱
箱子代表数据的封装
装箱就是把数据装入箱子里
拆箱就是把数据从箱子里拿出
装箱:将基本数据类型转换为包装器类。
拆箱:将包装器类转换为基本数据类型。
Integer i = new Integer(1);
//拆箱
int j = i.intValue();
j++;
//装箱
i = new Integer(j);
自动装箱
手动装、拆箱很麻烦,代码臃肿。
Java提供了自动装箱机制。
Integer i = new Integer(1);
//自动装箱
i++;
自动装箱后,引用指向的内存地址不同。
方法重载问题
基本数据类型加宽与方法重载
在Java中,基本数据类型会被加宽到更宽泛的基本数据类型
public class PrintStr{
//基本数据类型
public void print(int i){
System.out.println("int");
}
//包装器类
public void print(Short){
System.out.println("int");
}
}
public class Demo{
public static void main(String args[]){
PrintStr ps = new PrintStr();
//基本数据类型
short s = 2;
ps.print(s);
}
}
short被加宽到int,
同时基本数据类型和包装器类型是不同的数据类型。
int
自动装箱与方法重载
int会被自动装箱,调用Integer参数的方法
public class PrintStr{
//基本数据类型
public void print(short s){
System.out.println("short");
}
//包装器类
public void print(Integer i){
System.out.println("Integer");
}
}
public class Demo{
public static void main(String args[]){
PrintStr ps = new PrintStr();
//基本数据类型
int i = 2;
ps.print(i);
}
}
Integer
可变元参数与方法重载
public class PrintStr{
//基本数据类型
public void print(int i,int j){
System.out.println("int,int");
}
public void print(short ...i){
System.out.println("short...");
}
//包装器类
public void print(Short i,Short j){
System.out.println("Short,Short");
}
}
public class Demo{
public static void main(String args[]){
PrintStr ps = new PrintStr();
//基本数据类型
short i = 2;
short j = 2;
ps.print(i,j);
}
}
int,int
规则
能否直接匹配
加宽后能否直接匹配
装箱后能否直接匹配
先装箱后加宽后能否直接匹配
有不定长参数能否匹配
博客相关java项目:查看Github项目
对应github项目:Demo6
导入项目的方法:Java基础——Java如何导入本地项目