The return type Calcolatrice.sum(listInt)
is actually an Integer
thanks to the casting at the end of sum
in your example. However, the actual result type is Double
. Obviously, this is not a good situation, but this happened because you explicitly told the compiler in the role that the return value will be of the same type as the return value.
This situation means that if you write Calcolatrice.sum(listInt).toString()
instead, you will get a ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
because you will call Integer.toString()
on Double
. In fact, your code runs System.out.println("Sum: "+ String.valueOf(Calcolatrice.sum(listInt)))
, which works because it empties to Object
(thus resolving the conflict) before calling toString
.
As @TmTron points out, you cannot use types between Double
and Integer
in a box in the same way you can do with primitives.
i.e.
int i = (int) 2.0;
follows various rules:
Integer i = (Integer) new Double(2.0)
source share