Search code examples
javacastingprimitive-typesreference-type

Why does casting a primitive type to a reference type is giving compilation error?


I am wondering why casting a primitive data type (int for instance) to a reference type (Long for instance) does not compile?

BinaryOperator<Long> add = (x, y) -> x + y;
System.out.println(add.apply((Long)8, (Long)5)); //this line does not compile
System.out.println(add.apply((long)8, (long)5)); // this line does compile

I will be happy to have some detailed answer. Thank you.


Solution

  • Because this

    Long l = 1; 
    

    means assigning an int (literal number without floating part are int) to an Object, here a Long.
    The autoboxing feature introduced in Java 5 doesn't allow to box from an int to something else than a Integer. So Long is not acceptable as target type but this one would be :

    Integer i = 1;  
    

    In your working example you convert the int to a long : (long)8.
    So the compiler can perfectly box long to Long.