概述
Java提供了两种类型系统,基本类型和引用类型,使用基本类型在于效率,然而很多情况下会创建对象,如果想要基本类型像对象一样操作,就可以使用基本类型对应的包装类。对应如下:
基本类型 | 对应的包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
基本数据类型转为包装类
基本数据类型转为对应的包装类对象称为装箱。
public class WrapperTest {
@Test
public void test1() {
//调用包装类的构造器
Integer integer1 = new Integer(123);
System.out.println(integer1); //123
Integer integer2 = new Integer("456");
System.out.println(integer2); //456
Float f1 = new Float(1.3f);
System.out.println(f1); //1.3
Float f2 = new Float("12.3");
System.out.println(f2); //12.3
Boolean b1 = new Boolean(true);
System.out.println(b1); //true
Boolean b2 = new Boolean("true");
System.out.println(b2); //true
Boolean b3 = new Boolean("true123");
System.out.println(b3); //false
}
}
包装类转为基本数据类型
包装类对象转为对应的基本类型称为拆箱。
public class WrapperTest {
@Test
public void test2(){
Integer integer1 = new Integer(123);
int i = integer1.intValue();
System.out.println(i+1); //124
Float f1 = new Float(1.34);
float f2 = f1.floatValue();
System.out.println(f2); //1.34
}
}
自动装箱和自动拆箱
从JDK1.5之后基本数据类型的数据和包装类之间可以自动的相互转换。
public class WrapperTest {
@Test
public void test3(){
//自动装箱:基本数据类型->包装类
int num1 = 10;
Integer num2 = num1;
boolean b1 = true;
boolean b2 = b1;
//自动拆箱:包装类->基本数据类型
int num3 = num2;
}
}
基本数据类型、包装类和String类型之间的转换
基本数据类型、包装类转为String类型:
public class WrapperTest {
// 基本数据类型、包装类->String类型
@Test
public void test4() {
int num1 = 10;
//方式1:连接运算
String str1 = num1 + "";
//方式2:调用String重载的valueOf方法
float f1 = 12.34f;
String str2 = String.valueOf(f1);
System.out.println(str2);
Double d1 = new Double(12.3);
String str3 = String.valueOf(d1);
System.out.println(str3);
}
}
String类型转为基本数据类型、包装类:
public class WrapperTest {
// String类型->基本数据类型
@Test
public void test5() {
String str1 = "123";
int num2 = Integer.parseInt(str1);
System.out.println(num2);
String str2 = "true";
boolean b1 = Boolean.parseBoolean(str2);
System.out.println(b1);
}
}