Boxed Primitives and Equivalence

后端 未结 4 995
伪装坚强ぢ
伪装坚强ぢ 2020-12-06 10:36

So I was asked this question today.

Integer a = 3;
Integer b = 2;
Integer c = 5;
Integer d = a + b;
System.out.println(c == d);

What will t

4条回答
  •  时光取名叫无心
    2020-12-06 11:16

    Boxed values between -128 to 127 are cached. Boxing uses Integer.valueOf method, which uses the cache. Values outside the range are not cached and always created as a new instance. Since your values fall into the cached range, values are equal using == operator.

    Quote from Java language specification:

    If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

    http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7

提交回复
热议问题