Search code examples
javatype-conversionwrapperprimitiveboxing

equal(=). Why for primitive widening is works but for wrapper not?


I noticed surprising behaviour

code 1:

double dPrimitive = 1; //valid line of code

It is valid string and code compiles good - expected result for me.

code 2:

Double dWrapper = 1 ; // invalid line of code

It is INvalid string and code doesn't compile - UNexpected result for me.

Type mismatch: cannot convert from int to Double

Why for primitive widening is works bit for wrapper - not ?


Solution

  • I found decision:

    widening -> boxing - invalid conversion chain

    boxing -> wideining - valid conversion chain

    this code:

     Object  d=1;
     System.out.println(d.getClass());
    

    returns

    class java.lang.Integer