Java

  1、装箱与拆箱

  装箱,将基本数据类型转为包装类型。拆箱,将包装类型转为基本数据类型。

        // Byte, Short, Integer, Long, Double, Float, Boolean, Character
        // 自动装箱,将基本数据类型转为包装类型
        Integer i1 = 200;
        Integer i2 = 200;
        // 自动拆箱,将包装类型转为基本数据类型
        int i3 = i1;
        int i4 = i2;

   

2、基本数据类型与包装类型

  

  

  3、装箱与拆箱如何实现

  装箱的时候JVM自动调用的是Integer的valueOf(value)方法。拆箱时JVM自动调用Integer的intVlue()方法。装箱与拆箱的实现过程即为:装箱过程是通过调用包装器的valueOf(value)方法实现的,而拆箱过程是通过调用包装器的 xxxValue()方法实现的。(xxx代表对应的基本数据类型),包装类型做算术运算时,会自动拆箱为基本数据类型再进行。

 

4、面试中常见的问题

4.1 整形类型

        // Byte, Short, Integer, Long, Double, Float, Boolean, Character
        // 自动装箱,将基本数据类型转为包装类型
        Integer i1 = 200;
        Integer i2 = 200;
        // 自动拆箱,将包装类型转为基本数据类型
        int i3 = 127;
        int i4 = 127;
        
        System.out.println(i1 == i2);
        System.out.println(i3 == i4);

  输出结果:

  false

  true

  原因需要查看Integer.valueOf(int i)方法。

  

4.2 浮点类型

        Double d1 = 2.3;
        Double d2 = 2.3;
        System.out.println(d1 == d2);
        
        Double d3 = 1000.1;
        Double d4 = 1000.1;
        System.out.println(d3 == d4);

  输出结果:

  false

  false

4.3 综合

    public static void main(String[] args) {
        
        Integer a1 = 1;
        Integer a2 = 2;
        Long b1 = 2L;
        Long b2 = 3L;
        
        // ture
        System.out.println(b2 == (a1+a2));
        // true
        System.out.println(b2 == (a1+b1));
        // false
        System.out.println(b2.equals(a1+a2));
        // true
        System.out.println(b2.equals(a1+b1));
    }

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/Latiny/p/10573338.html