包装类位于 java.lang 包,用法类似;

包装类

对应关系

基本数据类型与包装类的对应关系:

基本数据类型 包装类(引用数据类型)
byte Byte
boolean Boolean
short Short
char Character
int Integer
long Long
float Float
double Double

基本数据类型 变量有默认值,而包装类对象的默认值为 null;

包装类的使用示例

由于包装类的常用方法类似,此处拿Integer举例;
数字相关的包装类都继承了Number类;Byte, Short, Integer, Long, Float, Double等。
image.png 【Number 基本方法】
Number 类属于抽象类,定义了子类之间相互转换的方法;

包装类常用方法示例:

  1. public class TestInteger {
  2. public static void main(String[] args) {
  3. //1.基本数据类型转成包装类对象
  4. Integer a = new Integer(1);
  5. Integer b = Integer.valueOf(2);
  6. //2.包装类对象转成基本数据类型
  7. int c = b.intValue();
  8. double d = b.doubleValue();
  9. //3.字符串转成包装类对象
  10. Integer e = new Integer("8888");
  11. //4.包装类对象转成字符串
  12. String f = e.toString();
  13. //5.包装类中的常量
  14. System.out.println("Integer中最大值:"+Integer.MAX_VALUE);
  15. System.out.println("Size:"+Integer.SIZE);
  16. }
  17. }

自动装箱和拆箱

自动装箱:可以直接把基本数据类型的值或者变量赋值给包装类。
自动拆箱:可以把包装类的变量直接赋值给基本数据类型。

  1. // 自动装箱
  2. Integer a = 2;//相当于 Integer a = Integer.valueOf(2);
  3. // 自动拆箱
  4. int b = a; //编译器自动转为:int b = a.intValue();

整数缓存问题

缓存问题:缓存[-128,127]之间的整数,系统初始化时会创建一个缓存数组;

  1. Integer a = 124;
  2. Integer b = 124;
  3. System.out.println(a==b); // true
  4. System.out.println(a.equals(b)); // true
  5. Integer c = 128;
  6. Integer d = 128;
  7. System.out.println(c==d); // false
  8. System.out.println(c.equals(d)); // true