1、包装类概述
针对八种基本数据类型定义相应的引用类型——包装类(封装类)。
2、基本数据类型转化为包装类
格式:包装类 变量名 = new 包装类(数据);
public class Main {
public static void main(String[] args) {
int nun = 1;
Integer integer = new Integer(nun);
System.out.println(integer.toString());
//如果填写字符串,则必须是一个数字,否则报错
Integer integer1 = new Integer("5");
System.out.println(integer1.toString());
Float aFloat = new Float(1.1f);
Float aFloat1 = new Float("1.2");
System.out.println(aFloat);
System.out.println(aFloat1);
Boolean aBoolean = new Boolean(true);
System.out.println(aBoolean);
Boolean aBoolean1 = new Boolean("true111");
System.out.println(aBoolean1);
}
}
其余类型可参考以上代码
注意
new Boolean()底层原理:如果不是null,不区分大小写为true就是true,否则为false
2、包装类转化为基本数据类型
格式:基本数据类型 变量名 = 包装类变量名.xxxValue();
public class Main {
public static void main(String[] args) {
Integer integer = new Integer(20);
int i = integer.intValue();
System.out.println(i);
Float aFloat = new Float(1.11);
float v = aFloat.floatValue();
System.out.println(v);
}
}
其余类型可参考以上代码
3、自动装箱与自动拆箱
自动装箱:基本数据类型——>包装类
public class Main {
public static void main(String[] args) {
int num = 1;
//自动装箱
Integer integer = num;
System.out.println(integer);
boolean b1 = true;
//自动装箱
Boolean bool = b1;
System.out.println(bool);
}
}
自动拆箱:包装类——>基本数据类型
public class Main {
public static void main(String[] args) {
int num = 1;
Integer integer = num;
//自动拆箱
int num2 = integer;
System.out.println(num2);
}
}
其余类型可参考以上代码
4、基本数据类型、包装类与String相互转换
基本数据类型、包装类——>String类型
public class Main {
public static void main(String[] args) {
int num = 1;
//方式一:连接运算
String str = num + "";
System.out.println(str);
//方式二:调用Strinf重载的valueOf(Xxx xxx)
String s = String.valueOf(num);
System.out.println(s);
//包装类
Double aDouble = new Double(3.3);
String s1 = String.valueOf(aDouble);
System.out.println(s1);
}
}
String类型——>基本数据类型、包装类
public class Main {
public static void main(String[] args) {
String str = "123";
//调用包装类的parseXxx(String s)
int i = Integer.parseInt(str);
System.out.println(i);
String str1 = "true";
boolean b = Boolean.parseBoolean(str1);
System.out.println(b);
}
}
其余类型可参考以上代码
觉得博主写的不错的读者大大们,可以点赞关注和收藏哦,谢谢各位!