2

The following code compiles fine and yields true in java. I have read that java won't do two conversions at once, like when assigning an int literal value(or variable) to a Double wrapper reference. So why is it that this compiles fine in comparison with using = operator?

double double1 = 3.00;
Integer wInt = new Integer("3");
if(wInt == double1);
al gh
  • 508
  • 2
  • 15

1 Answers1

6

Like other mathematical operators such as +, the == operator performs binary numeric promotion on its operands.

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

  1. If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

  2. Widening primitive conversion (§5.1.2) is applied to convert either or both operands...

The compiler first unboxes the Integer to an int, then widens the int to a double. It will perform both if the unboxing occurs first.

Java will perform both conversions implicitly for many operators:

Binary numeric promotion is performed on the operands of certain operators:

  • The multiplicative operators *, /, and % (§15.17)

  • The addition and subtraction operators for numeric types + and - (§15.18.2)

  • The numerical comparison operators <, <=, >, and >= (§15.20.1)

  • The numerical equality operators == and != (§15.21.1)

  • The integer bitwise operators &, ^, and | (§15.22.1)

  • In certain cases, the conditional operator ? : (§15.25)

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • so your explanation is that "two conversions" are allowed only when Unboxing happens first, but not the other way around? (Boxing and then converting) – al gh Sep 20 '19 at 21:49
  • @AndyTurner I thought including `?:` in the quote at the bottom was sufficient. – rgettman Sep 20 '19 at 21:51
  • 1
    @aligh Yes, that's what the quote from the JLS explicitly states. The conversions happen "in order". – rgettman Sep 20 '19 at 21:51
  • It may actually do a total of **four** conversions. Example: If expression is `Byte + Short`, then it will do `Byte → byte` *(unbox)*, `byte → int` *(widen)*, `Short → short` *(unbox)*, and `short → int` *(widen)*. – Andreas Sep 20 '19 at 21:57