1

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.

Raman Mishra
  • 2,635
  • 2
  • 15
  • 32
ecdhe
  • 421
  • 4
  • 17
  • Does `(Long)8l` compile? And here's a further [https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.7](hint). – biziclop Apr 05 '18 at 14:34

2 Answers2

4

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.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • Although in the case of `int` to `Long` the answer is true, it isn't 100% correct, as autoboxing will happily convert from a compile-time constant `int` to `Short` for example. – biziclop Apr 05 '18 at 14:39
  • My question concerns the pre-autoboxing phase, that is the casting. Still have not truly understood why the compiler rejects this cast operation: (Long)5 – ecdhe Apr 05 '18 at 14:47
  • 1
    @biziclop I would not specify this point as it is a corner case but for short literals you are right. – davidxxx Apr 05 '18 at 14:47
  • 1
    You cannot cast a primitive to a reference as you would. `5` is a primitive and casting it to `Long` should **first** respect autoboxing rules (here the boxing part : primitive to Object). In this specific case, `5` (an `int`) cannot be boxed to a `Long`. That's all. – davidxxx Apr 05 '18 at 14:51
  • @davidxxx Thank you so much – ecdhe Apr 05 '18 at 15:39
0

The long is a primitive data type, but Long is a (wrapper) class.

The following should work.

System.out.println(add.apply(Long.valueOf(8), Long.valueOf(5)));
casillas
  • 16,351
  • 19
  • 115
  • 215
  • Thank you for your reply. I ain't asking for the solution to my problem. I would rather like to know why the casting operation (Long)5 for instance fails. – ecdhe Apr 05 '18 at 14:50