Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I set a Double object equal to an int? - Java

Why do I get an error when attempting to initialize a Double to an int, even though it does not throw an exception when using the primitive type, double?

Double a = 1;   // error - incompatible types
Double b = 1.0; // OK
double c = 1;   // OK

Why is the behavior different between the class Double and the primitive type, double?

like image 888
hetelek Avatar asked Feb 25 '14 15:02

hetelek


1 Answers

When you initialize your Double as:

Double a = 1;

There needs to be done 2 things:

  • Boxing int to Integer
  • Widening from Integer to Double

Athough, boxing is fine, but widening from Integer to Double isn't valid. So, it fails to compile.

Note that, Java doesn't support Widening followed by Boxing conversion, as specified in JLS §5.2:

Assignment contexts allow the use of one of the following:

  • an identity conversion (§5.1.1)
  • a widening primitive conversion (§5.1.2)
  • a widening reference conversion (§5.1.5)
  • a boxing conversion (§5.1.7) optionally followed by a widening reference conversion
  • an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.

Your 2nd assignment goes through boxing conversion.
While 3rd assignment goes through widening conversion.

like image 165
Rohit Jain Avatar answered Oct 05 '22 01:10

Rohit Jain