Java autoboxing rules

江枫思渺然 提交于 2019-11-28 07:41:36

Unboxing will be happing when arithmetic operators, comparison operators appear.

eg:

Integer a = 10;
a = a+10; //1.unboxing a to int 2.calculate a+10 3.boxing 20 to Integer.
System.out.print(a > 10); //1.unboxing a to int 2. compare

But when == appear, it depends.

If boxing type appear on both side, it will compare the reference.But if base type appear on one side, and the other side is a boxing type, the boxing type will unboxing to base type.

eg:

Integer a = new Integer(129);
Integer b = new Integer(129);
System.out.println(a == b); // compare reference return false
System.out.println(a == 129); // a will unboxing and compare 129 == 129 return true

PS: In Java.lang.Integer Cache to support the object identity semantics of autoboxing for values between -128 and 127 (inclusive) as required by JLS. See source code

So:

Integer a = 127;
Integer b = 127; //cached, the same as b a==b return ture

Integer c = 129;
Integer d = 129; // not cached, c==d return false

Here is the Tutorial for Autoboxing and Unboxing.

You can also go through JLS#5.1.7. Boxing Conversion and JLS#5.1.8. Unboxing Conversion

0.0 / 0.0 is NaN you can not compare infinity at least in maths. I guess that is why this comparison does not work.

From JLS #4.2.3. Floating-Point Types, Formats, and Values

Positive zero and negative zero compare equal; thus the result of the expression 0.0==-0.0 is true and the result of 0.0>-0.0 is false

NaN is unordered, so:

  • The numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN (§15.20.1).

  • The equality operator == returns false if either operand is NaN.

  • In particular, (x=y) will be false if x or y is NaN.

  • The inequality operator != returns true if either operand is NaN (§15.21.1).

  • In particular, x!=x is true if and only if x is NaN.

If you check Double#equals method it has two exceptions

also has the value true. However, there are two exceptions:

  • If d1 and d2 both represent Double.NaN, then the equals method returns true, even though Double.NaN==Double.NaN has the value false.

  • If d1 represents +0.0 while d2 represents -0.0, or vice versa, the equal test has the value false, even though +0.0==-0.0 has the value true.

This definition allows hash tables to operate properly.

== can only be used for checking if the variables are equal or not if the variables are primitive types. For object variables, == is used to compare the reference of the objects. If you want to compare the values of the objects, use .equals() method.

I would not recommend comparing boxed ints with ==, as it works only for some values.

Unboxing will happen for arithmetic operators, comparison operators.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!