1. 程式人生 > >基本型別與自動裝箱與拆箱

基本型別與自動裝箱與拆箱

先說幾個要注意的地方,然後根據以下的結論來分析兩個題目。

1.所有數值型別都有正負號

2.浮點數值有後綴f或F,表示float型別,沒有的話預設為double型別,double可加可不加字尾d或D。long型有後綴l或L

3.不同型別運算結果向右靠齊 char<short<int<float<double

4.計算機進行運算是以補碼形式進行

5.正數的補碼就是原碼,負數的補碼是除符號位以外其餘各位取反+1

6.物件包裝器類是不可變的

7.自動裝箱規範要求boolean, byte, char<=127,-128-127之間的int和short被包裝到固定的物件中

8.==運算,在兩邊是引用型別時比較兩引用是否指向同一物件,在兩邊是數值型別時,比較兩數值是否相等。當一邊是包裝型別另一邊是基本型別時,包裝型別會自動解包成基本型別來比較。

9.裝箱拆箱是編譯期認可的,而不是虛擬機器。(語法糖)

10.equals方法要為true的首要條件是同種型別的物件,如果都不是同種型別物件比較的話,肯定是false。equals方法不會處理資料轉型關係,但是會根據情況看是否需要拆包。

11.Integer.valueOf()返回一個Integer物件,Integer.intValue()返回一個int值。

一.

連結:https://www.nowcoder.com/questionTerminal/1bab09264a1c4528aa60ee9bca5f0976
來源:牛客網

public class Test2
{
    public void add(Byte b)
    {
        b = b++;
    }
    public void test()
    {
        Byte a = 127;
        Byte b = 127;
        add(++a);
        System.out.print(a + " ");
        add(b);
        System.out.print(b + "");
    }
}

答案:-128, 127

分析:

1.Byte a = 127, Byte b = 127;這兩句自動打包。

2.add(++a); 首先是Byte a解包成byte a = 127。然後執行自加操作,byte範圍是-128~127,所以自加後a變成-128。add(Byte b)的引數型別是包裝型別,又會對byte a = -128打包成Byte,但是Byte是不可變型別,所以實際上add函式並沒有更改a的值。最後a的值為-128

3.add(b); 與上面的不同之處就在於沒有自加操作,所以b還是127。

二.

周志明《深入理解java虛擬機器》316頁

	public static void main(String[] args) {
		Integer a = 1;
		Integer b = 2;
		Integer c = 3;
		Integer d = 3;
		Integer e = 321;
		Integer f = 321;
		Long g = 3L;
		System.out.println(c == d);  
		System.out.println(e == f);	 
		System.out.println(c == (a+b));	
		System.out.println(c.equals(a+b)); 
		System.out.println(g == (a+b)); 
		System.out.println(g.equals(a+b)); 
	}

答案:

true
false
true
true
true
false

分析:

1.c == d;兩個包裝型別比較,c,d的值相等並在-128-127之間,被包裝到了固定物件中。所以為true。

2.e == f;兩個包裝型別比較,e,f值相等但是不再-128-127之間,屬於兩個不同物件,false。

3.c == a+b;a+b會執行解包操作,此時c為包裝型別,a+b為基本型別,那麼c會自動解包為基本型別來比較,true。

4.c.equals(a+b);a+b首先會進行解包操作將值相加之後再進行裝箱。Integer類重寫了equals方法,比較的是Integer包裝的數值是否相等,true。

5.g = a+b; a+b進行解包成數值型別,c檢測到等號右邊變成數值型別了,自己也會拆箱成基本型別,儘管左邊是long,右邊是int,但是隻要數值相等,就沒有關係。親測了一下int a = 1;double b = 1。a == b也是true。

6.g.equals(a+b);a+b先拆箱再裝箱成為值為3的Integer型別,g為值為3的Long型,兩物件不是同一型別所以返回false,可見equals不會把Integer轉成Long。

實際上是執行了如下的操作

        Integer a = Integer.valueOf(1);  
        Integer b = Integer.valueOf(2);  
        Integer c = Integer.valueOf(3);  
        Integer d = Integer.valueOf(3);  
        Integer e = Integer.valueOf(321);  
        Integer f = Integer.valueOf(321);  
        Long g = Long.valueOf(3L);  
        System.out.println(c == d);  
        System.out.println(e == f);  
        System.out.println(c.equals(Integer.valueOf(a.intValue() + b.intValue())));  
        System.out.println(g.longValue() == (long)(a.intValue() + b.intValue()));  
        System.out.println(g.equals(Integer.valueOf(a.intValue() + b.intValue())));