首頁技術(shù)文章正文

Java中integer和int的區(qū)別|真題案例講解

更新時間:2020-10-29 來源:黑馬程序員 瀏覽量:

Integer和int的區(qū)別:

1、Integer是int的包裝類,int則是java的一種基本數(shù)據(jù)類型 ;

2、Integer變量必須實例化后才能使用,而int變量不需要 ;

3、Integer實際是對象的引用,當new一個Integer時,實際上是生成一個指針指向此對象;而int則是直接存儲數(shù)據(jù)值;

4、Integer的默認值是null,int的默認值是0;

1603958298414_Integer和int的區(qū)別.jpg


問題一:


public static void main(String[] args) {
    Integer a = 100;
    Integer b = 100;
    System.out.println(a == b);
    Integer c = 200;
    Integer d = 200;
    System.out.println(c == d);
}

請問:a==b的值以及c==d的值分別是多少?


答案: a==b為true; c==d為false

原因分析:

Integer a = 100;實際上會被翻譯為: Integer a = ValueOf(100); 從緩存中取出值為100的Integer對象;同時第二行代碼:Integer b = 100; 也是從常量池中取出相同的緩存對象,因此a跟b是相等的;而c 和 d 因為賦的值為200,已經(jīng)超過 IntegerCache.high 會直接創(chuàng)建新的Integer對象,因此兩個對象相?較肯定不相等,兩者在內(nèi)存中的地址不同。


問題二:

Integer a = 100;
int b = 100;
System.out.println(a == b);
Integer a = new Integer(100);
int b = 100;
System.out.println(a == b);

輸出結(jié)果是什么?


答案為:ture,因為a會進行自動動拆箱取出對應(yīng)的int值進行比較,因此相等。

問題三:

Integer a = new Integer(100);
Integer b = new Integer(100);
System.out.println(a == b);

輸出結(jié)果是什么?


答案為:false,因為兩個對象相比較,比較的是內(nèi)存地址,因此肯定不相等。

問題四:

最后再來一道發(fā)散性問題,大家可以思考下輸出的結(jié)果為多少:

public static void main(String[] args) throws NoSuchFieldException,
IllegalAccessException {
    Class cache = Integer.class.getDeclaredClasses()[0];
    Field myCache = cache.getDeclaredField("cache");
    myCache.setAccessible(true);
    Integer[] newCache = (Integer[]) myCache.get(cache);
    newCache[132] = newCache[133];
    int a = 2;
    int b = a + a;
    System.out.printf("%d + %d = %d", a, a, b);
}

答案為: 2 + 2 = 5. 大家可以下來好好思考下為什么會得到這個答案?

1577370495235_學IT就到黑馬程序員.gif

猜你喜歡:

Java冒泡排序算法詳細介紹

什么是MyBatis?

Java字節(jié)碼指令詳細視頻介紹 


分享到:
在線咨詢 我要報名
和我們在線交談!