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

Why does an error occur when trying to initialize Doubleto int, even if 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 behavior different from class Doubleand primitive type Double?

+4
source share
3 answers

When you initialize yours Doubleas follows:

Double a = 1;

There should be 2 things done:

  • Boxing intupInteger
  • Extension from IntegertoDouble

Although boxing is in order, expansion from Integerto is Doubleunacceptable. Therefore, it does not compile.

, Java , , JLS & sect; 5.2:

:

  • (§5.1.1)
  • (§5.1.2)
  • (§5.1.5)
  • (§5.1.7),
  • (. 5.1.8), .

2 nd .
3 rd .

+9

- Java, 1 Integer Double.

Double a = Double.valueOf(1); 

0

-

 Double a = 1;     equals to Double a = Integer.valueOf(1);

 Double b = 1.0;   equals to Double b = Double.valueOf(1);    

 double c = 1;     equals to double c = (double) 1;

, D.

 Double d = 1D; equals to Double d = Double.valueOf(1);
0
source

Source: https://habr.com/ru/post/1528776/


All Articles