一、基本概念
- 概念:基本数据类型对应引用类型,称之为基本数据类型的包装类。
二、基本数据类型对应的包装类:
基本数据类型 | 包装类名 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
三、数据之间转换【了解】
-
int 和 Integer 之间的转换
(1) int -----> Integer
a. Integer i1 = new Integer(12); // 借助构造方法
b. Integer i2 = Integer.valueOf(12); // 借助Integer类中的静态方法
(2) Integer ----> int
a. int a1 = i1.intValue() ; // 借助Integer类中的成员方法 intValue()
-
String 和 Integer之间的转换
(1) String ----> Integer
a. Integer i3 = new Integer(“123”); // 借助Integer类中的构造方法
b. Integer i4 = Integer.valueOf(“123”); // 借助Integer类中静态方法
扫描二维码关注公众号,回复: 12198566 查看本文章(2)Integer ----> String
a. String s1 = i4.toString();
b. String s2 = i4+""; //借助字符串的拼接
-
int 和 String 之间的转换
(1) int —> String
a. int a = 3; String s3 = a+"";
(2) String ----> int 【开发应用重点】
int a = Integer.parseInt(“123”); // 借助 Integer类中静态方法
注意:将String类型的数据转换为 int/Integer类型的数据,要求要转换的String数据类型必须是纯数字,否则运行报错,错误信息如下:
java.lang.NumberFormatException (数字格式转换异常).
四、自动装箱、自动拆箱
-
JDK5.0之后提供自动装箱和自动拆箱的功能,基本数据类型和对应包装类型之间可以相互自动转换。
-
自动装箱:基本数据类型可以直接赋值给其对应的包装类型。
自动拆箱:包装类型的引用可以直接赋值给对应的基本数据类型的变量。
-
自动装箱和自动拆箱案例:
Integer i = 12; // 自动装箱 int a = i ; // 自动拆箱
-
自动装箱实现的原理:自动装箱底层调用的时Integer类中静态的valueOf方法:
public static Integer valueOf(int i) { if (i >= -128 && i <= 127) return IntegerCache.cache[i+(-IntegerCache.low)]; // 如果 传入数据不在-128~127之间,则new Integer类型对象 return new Integer(i); }
注意:Java中将 -128127常用数据段的内容进行了预先的包装处理,转换数据只要在-128127之间不需要每次创建对象,而是从处理结果中直接获取即可,-128~127处理结果存储在缓冲区中、常量池。
面试题目:分析两个打印语句打印输出的结果,并说明原因。
Integer i1 = 12;
Integer i2 = 12; System.out.println(i1==i2); // true
Integer i3 = 150;
Integer i4 = 150 ;
System.out.println(i3==i4); // false
五、包装类实际开发应用【开发重点】
-
可以用于区分有效数据和无效数据:例如 0 和 null , 0.0 和 null.
-
场景:开发时,通常将类中属性定义为基本数据类型对应包装类型。区分有效数据和无效数据的,例如 null 和 0,null 和 0.0等。
-
案例如下:
public class TestStudent { public static void main(String[] args) { Student s1 = new Student("张三",23); Student s2 = new Student("lily",25,0.0); System.out.println(s1); System.out.println(s2); /* 打印输出结果如下: name=张三, age=23, score=null(没有考试) name=lily, age=25, score=0.0(成绩为0分) */ } } class Student { private String name; private Integer age ; private Double score; public Student() { } public Student(String name, Integer age) { super(); this.name = name; this.age = age; } public Student(String name, Integer age, Double score) { this.name = name; this.age = age; this.score = score; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Double getScore() { return score; } public void setScore(Double score) { this.score = score; } @Override public String toString() { return "name=" + name + ", age=" + age + ", score=" + score; } }