java装箱和拆箱

Java 提供两种不同的类型:引用类型和原始类型(或内置类型)。Int是java的原始数据类型,Integer是java为int提供的封装类。Java为每个原始类型提供了封装类。


原始类型封装类:
boolean  Boolean
char  Character
byte  Byte
short   Short
intInte  ger
long  Long
float  Float
double  Double

引用类型和原始类型的行为完全不同,并且它们具有不同的语义。引用类型和原始类型具有不同的特征和用法,它们包括:大小和速度问题,这种类型以哪种类型的数据结构存储,当引用类型和原始类型用作某个类的实例数据时所指定的缺省值。对象引用实例变量的缺省值为 null,而原始类型实例变量的缺省值与它们的类型有关。

public class AutZhun {
    /**
     * 测试自动装箱,自动拆箱
     * 
     * @author clc
     * @param args
     */
    public static void main(String[] args) {
        test();
    }
    static void test() {
        Integer a = new Integer(1234);
        Integer a1 = 890;// jdk5.0之后 . 自动装箱,编译器帮我们改进代码:Integer a1 = new
                            // Integer(1000);
        int b = a1.intValue();
        System.out.println(b);
        int b1 = a1; // 自动拆箱,编译器改进:b.intValue();
        Integer a2 = null;
        // int c=a2;//空指针异常;
        System.out
                .println("---------------------------------------------------------------------------");
        Integer q1 = 1234;
        Integer q2 = 1234;
        System.out.println(q1 == q2);
        System.out.println(q1.equals(q2));
        System.out
                .println("------------------------------------------------------------------------------");
        // [-128,127]之间的数,仍然当做基本数据类型来处理。
        Integer q3 = 123;
        Integer q4 = 123;
        System.out.println(q3 == q4);
        System.out.println(q3.equals(q4));
    }
}

 

posted @ 2017-05-31 10:19  路迢迢  阅读(364)  评论(0编辑  收藏  举报