1

I came across this piece of legacy code (Java 6) (that's simplified version that pinpoints my issue):

Object o;
o = new Long (3L);
Double d;
d = (Double) o;

This one above is obviously not working as wrappers can be cast only to corresponding primitive types. I fixed this by:

Long toConvert = (Long) o;
String convert = toConvert.toString();
d= Double.parseDouble(convert);

and it works fine, except being ugly. I tried another solution:

d = (double) o;

and I worked as well, but when I checked this solution (pure curiosity) in new Java 8 project I got

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double

Does Java 6 differs from Java 8 when it comes to primitive wrappers in a way that can explain observed behaviour?

Tarun
  • 986
  • 6
  • 19
Jarek Soja
  • 31
  • 6
  • Are you working with Javac? Or the Eclipse compiler (ECJ)? – Lii Feb 08 '19 at 09:14
  • 3
    Here is a question about a thing that sounds relevant: https://stackoverflow.com/questions/30120861/is-casting-from-number-to-double-allowed-in-java-7-autoboxing (maybe it is a duplicate). Apparently the behaviour of casts changed somewhat in Java 7. – Lii Feb 08 '19 at 09:14
  • Thank you, i wouldn't say it's duplicate, but I'm sure it's relevant! – Jarek Soja Feb 08 '19 at 09:19
  • The question about which compiler you use is also important! The linked question mentions that Javac and the Eclipse compiler has differences here. And exactly which versions do you use? – Lii Feb 08 '19 at 09:24
  • Interestingly, if `o` is of type `Long`, the conversion succeeds... – Sweeper Feb 08 '19 at 09:27

0 Answers0