文章目录
包装类
什么是包装类
java提供了8种基本数据类型对应的包装类,使得基本数据类型的变量具有类的特征。
* byte Byte
* short Short
* int Integer
* long Long
* float Float
* double Double
* char Character
* boolean Boolean
基本数据类型–>包装类
调用包装类的构造器:
int num1 = 10;
Integer in1 = new Integer(num1);
System.out.println(in1.toString());
Integer in2 = new Integer("123");
System.out.println(in2.toString());//数字字符串也可以
//报异常,只能使用对应数据类型的字符串,含有其他类型会报错
Integer in3 = new Integer("123abc");
System.out.println(in3.toString());
Float f1 = new Float(12.3f);
Float f2 = new Float("12.3");
System.out.println(f1);
ystem.out.println(f2);
//布尔类型是特例,只要不是标准的true就都是false
Boolean b1 = new Boolean(true);
Boolean b2 = new Boolean("TrUe");
System.out.println(b2);
Boolean b3 = new Boolean("true123");
System.out.println(b3);//false
包装类–>基本数据类型
调用包装类Xxx的xxxValue(),xxx为具体的基本数据类型。
Integer in1 = new Integer(12);
int i1 = in1.intValue();
System.out.println(i1 + 1);
Float f1 = new Float(12.3);
float f2 = f1.floatValue();
System.out.println(f2 + 1);
自动装箱与自动拆箱
JDK 5.0 新特性:自动装箱 与自动拆箱。
public void method(Object obj){
System.out.println(obj);
}
public void test(){
int num1 = 10;
method(num1);//按理来说基本数据类型是不能直接放入该方法中,但有了自动装箱的新特性,num1被自动装箱成包装类。
//自动装箱:基本数据类型 --->包装类
int num2 = 10;
Integer in1 = num2;//自动装箱
boolean b1 = true;
Boolean b2 = b1;//自动装箱
//自动拆箱:包装类--->基本数据类型
int num3 = in1;//自动拆箱
}
基本数据类型、包装类与String的转换
基础数据类型、包装类–>String
方式1:连接运算
int num1 = 10;
String str1 = num1 + "";
方式2:调用String的valueOf(Xxx xxx)
int num1 = 10;
float f1 = 12.3f;
String str2 = String.valueOf(f1);//"12.3"
Double d1 = new Double(12.4);
String str3 = String.valueOf(d1);
System.out.println(str2);
System.out.println(str3);//"12.4"
String–>基础数据类型、包装类
调用包装类的parseXxx(String s)
public void test5(){
String str1 = "123";
int num2 = Integer.parseInt(str1);
System.out.println(num2 + 1);
String str2 = "true1";
boolean b1 = Boolean.parseBoolean(str2);
System.out.println(b1);
}
public void test3() {
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;//相当于new了一个Integer对象
Integer y = 128;//相当于new了一个Integer对象
System.out.println(x == y);//false
}
Integer内部定义了IntegerCache结构,IntegerCache中定义了Integer[],保存了从-128-127范围的整数。如果我们使用自动装箱的方式,给Integer赋值的范围在-128-127范围内时,可以直接使用数组中的元素,不用再去new了,此时地址是一样的,所以使用==是true,如果不在该范围的数,则是false。目的:提高效率。