包装类以及包装类,基本数据类型和String之间的转换
1. 为什么要使用包装类?
为了使得基本数据类型的变量具备引用数据类型变量的相关特征(比如:封装性、继承性、多态性),我们给各个基本数据
类型的变量都提供了对应的包装类。
byte -> Byte
short -> Short
int -> Integer
long -> Long
float -> Float
double ->Double
//上面是父类为Number的
char -> Character
boolean -> Boolean
2. 基本数据类型 与 包装类之间的转换
①(装箱)基本数据类型 ---> 包装类:
使用包装类的构造器,从 JDK 9 开始,包装类的构造函数已被标记为 @Deprecated
Integer obj1 = new Integer(4);//使用构造函数函数
Float f = new Float("4.56");
调用包装类的valueOf(xxx xx)
Integer obj2 = Integer.valueOf(4);//使用包装类中的valueOf方法
②(拆箱)包装类 ---> 基本数据类型:调用包装类的xxxValue()
注意:原来使用基本数据类型变量的位置,改成包装类以后,对于成员变量来说,其默认值变化了!
包装过的是null
jdk5.0新特性:自动装箱、自动拆箱。
Float f1 = 12.3F;
Boolean bb1 = true;
boolean b1 = bb1;
3. String 与 基本数据类型、包装类之间的转换
基本数据类型、包装类 ---> String类型:
① 调用String的重载的静态方法valueOf(xxx xx)
int a = 10;
//String str = a;//错误的
String str = String.valueOf(a);
② 基本数据类型的变量 + ""
int a = 10;
String str = a + "";
String类型 ---> 基本数据类型、包装类: 调用包装类的静态方法:parseXxx()
public static int parseInt(String s):将字符串参数转换为对应的int基本类型。public static long parseLong(String s):将字符串参数转换为对应的long基本类型。public static double parseDouble(String s):将字符串参数转换为对应的double基本类型。
String s1 = "123";
int i1 = Integer.parseInt(s1);
System.out.println(i1 + 10);
String s2 = "true";
boolean b1 = Boolean.parseBoolean(s2);
方式总结:

注意点
包装类缓存机制
当通过自动装箱机制创建包装类对象时,首先会判断数值是否在-128—-127的范围内,如果满足条件,则会从缓存(常量池)中寻找指定数值,若找到缓存,则不会新建对象,只是指向指定数值对应的包装类对象,否则,新建对象。
| 包装类 | 缓存对象 |
|---|---|
| Byte | -128~127 |
| Short | -128~127 |
| Integer | -128~127 |
| Long | -128~127 |
| Float | 没有 |
| Double | 没有 |
| Character | 0~127 |
| Boolean | true和false |
Integer a = 1;
Integer b = 1;
System.out.println(a == b);//true
Integer i = 128;
Integer j = 128;
System.out.println(i == j);//false
Integer m = new Integer(1);//新new的在堆中
Integer n = 1;//这个用的是缓冲的常量对象,在方法区
System.out.println(m == n);//false
Integer x = new Integer(1);//新new的在堆中
Integer y = new Integer(1);//另一个新new的在堆中
System.out.println(x == y);//false
Double d1 = 1.0;
Double d2 = 1.0;
System.out.println(d1==d2);//false 比较地址,没有缓存对象,每一个都是新new的
类型转换问题
Integer i = 1000;
double j = 1000;
System.out.println(i==j);//true 会先将i自动拆箱为int,然后根据基本数据类型“自动类型转换”规则,转为double比较
Integer i = 1000;
int j = 1000;
System.out.println(i==j);//true 会自动拆箱,按照基本数据类型进行比较
Integer i = 1;
Double d = 1.0
System.out.println(i==d);//编译报错

浙公网安备 33010602011771号