1. 包装类基础
所谓包装类,就是针对八种基本数据类型定义的八种相应的引用类型,比如 int => Integer。Java最重要的概念就是类,万物都是类。一个普通的基本数据类型变量只能存储数据,没有任何额外作用,但是类中是可以定义方法的,比如排序,进制转换等,都是可以在包装类中直接调用的,效率很高。只有实现了万物皆类,Java才是真正的面向对象。
基本数据类型 | 包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char | Character |
其中,Byte、Short、Integer、Long、Float、Double 这六种包装类拥有共同的父类:Number。
2. 基本数据类型 => 包装类
- 转换方法:使用包装类的构造器
a. 比如 Integer 的构造器就有两个:
@Deprecated(since="9", forRemoval = true)
public Integer(int value) {
this.value = value;
}
@Deprecated(since="9", forRemoval = true)
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
Integer d1 = new Integer(123) ; // OK
Integer d2 = new Integer("321") ; // OK
System.out.println(d1);
System.out.println(d2);
System.out.println(d1 + d2);
Integer 的第二个构造器用String作为入参,其格式必须符合数值格式,否则会抛出异常。
Integer integer = new Integer("321abc") ; // ERROR
b. Float、Double 等也都有两个构造器
@Deprecated(since="9", forRemoval = true)
public Float(double value) {
this.value = (float)value;
}
@Deprecated(since="9", forRemoval = true)
public Float(String s) throws NumberFormatException {
value = parseFloat(s);
}
- 转换意义
- 在Java开发中,很多方法的入参类型必须是一个类,这样以来基本数据类型是无法传入的,就需要转换成包装类进行传参。
- 在后面学到的集合中,集合元素必须都得是类,这样以来就需要将基本数据类型转换为包装类了
- 总结一句话就是:Java万物皆类
3. 包装类 => 基本数据类型
转换方法:调用包装类的 XxxValue 方法
public class test { public static void main(String[] args) { Integer d1 = new Integer(123); int i1 = d1.intValue(); Float f1 = new Float(12.3); float fl1 = f1.floatValue(); System.out.println(i1); // 123 System.out.println(fl1); // 12.3 } }
意义:
包装类是无法做加减乘除等算术运算的,因此需要转换为基本数据类型来做运算。
4. 自动装箱与自动拆箱
先看段代码:
package pkg2;
public class Test {
public static void main(String[] args) {
Test t1 = new Test();
int id = 123 ;
t1.method(t1);
}
public void method(Object o){
System.out.println(o.toString());
}
}
可见,上述代码是没有任何错误与异常的,但是这显然与前文讲的不符合,因此基本数据类型是无法作为类进行传参的。
在 Java 5.0 之后,引用了自动装箱和自动拆箱的功能,让JDK自动进行基本数据类型和包装类之间的转换,省去了调用构造器的环节:
int id = 123 ;
Integer integer = id ; // 自动装箱 => Integer integer = new Integer(id) ;
int id2 = integer ; // 自动拆箱 => int id2 = integer.intValue();
5. 基本数据类型 <=> String 型
【基本数据类型 => String型】
方式1:借助空字符 “” 进行拼接运算
int num1 = 10 ; String str1 = num1 + "" ; System.ou.println(str1) ; // "10"
方式2:调用 String 中的静态方法:ValueOf
double num1 = 12.3; String str1 = String.valueOf(num1) ; System.out.println(str1); // "12.3"
【String => 基本数据类型】
只有一个方式:调用包装类的静态 parseXxx 方法:public static int parseInt(String s) throws NumberFormatException { return parseInt(s,10); } public static float parseFloat(String s) throws NumberFormatException { return FloatingDecimal.parseFloat(s); } public static boolean parseBoolean(String s) { return "true".equalsIgnoreCase(s); } // ...
public class Test { public static void main(String[] args) { String str1 = "1234" ; int id1 = Integer.parseInt(str1) ; float f1 = Float.parseFloat(str1) ; boolean b1 =Boolean.parseBoolean(str1) ; System.out.println(id1); System.out.println(f1); System.out.println(b1); } }