本篇文章解决问题
1. 包装类的使用
包装类的使用
包装类的使用:
- Java提供了8种基本数据类型包装类的使用,使得基本数据类型的变量具有类的特征
-
基本数据类型、包装类、String三者之间的相互转换
// 基本数据类型转换为包装类 // 调用包装类的构造器 public class Test1 { public static void main(String[] args) { int num = 10; Integer in1 = new Integer(num); Integer in2 = new Integer("123"); //Integer in3 = new Integer("asc")会报异常 System.out.println(in1.toString()); System.out.println(in2.toString()); Float f1 = new Float(1.2f); Float f2 = new Float("1.2f"); System.out.println(f2.toString()); Boolean b1 = new Boolean(true); Boolean b2 = new Boolean("true"); Boolean b3 = new Boolean("123true");//输出False } }
// 包装类转换为基本数据类 // 调用包装类Xxx的xxxValue()方法 public class Test2 { public static void main(String[] args) { Integer in1 = new Integer(123); int i1 = in1.intValue(); System.out.println(i1); Float f1 = new Float(1.23); float f2 = f1.floatValue(); System.out.println(f2); } }
// 自动装箱和自动拆箱 public class Test3 { public static void main(String[] args) { //自动装箱:基本数据类型--->包装类 int i1 = 123; Integer in1 = i1; System.out.println(in1.toString()); //自动拆箱:包装类--->基本数据类型 float f2 = 1.23f; Float f1 = f2; System.out.println(f1); } }
// 基本数据类型、包装类----->String public class Test4 { public static void main(String[] args) { // 方式一:采用拼接 int i1 = 123; String s1 = i1 + ""; System.out.println(s1); // 方式二:使用String.valuOf() float f1 = 1.23f; String s2 = String.valueOf(f1); System.out.println(s2); Double d1 = new Double(1.22); String s3 = String.valueOf(d1); System.out.println(s3); } }
// String----->基本数据类型、包装类 // 调用方法parseXxx(String s) public class Test5 { public static void main(String[] args) { String s1 = "123"; int i = Integer.parseInt(s1); System.out.println(i); String s2 = "true"; boolean b1 = Boolean.parseBoolean(s2); System.out.println(b1); } }