Skip to content

Instantly share code, notes, and snippets.

@eribeiro
Created May 8, 2012 21:07
Show Gist options
  • Save eribeiro/2639281 to your computer and use it in GitHub Desktop.
Save eribeiro/2639281 to your computer and use it in GitHub Desktop.
public class Casting {
public static void main(String[] args) {
// Those below are objects that get autoboxed automatically
Integer i = 0;
Long l = 0L;
Double d = 0D;
Float f;
Float f2 = 1f;
f = (float) d; // This you are getting an object and trying to cast to a primitive of different type
f = (float) f2; // This sucks! It probably is the reason of confusion...
f = (float) (double) d; // This works because you are unboxing the Double object "(double) d" then casting to float
f = (float) d.doubleValue(); // This works!
f = d.floatValue(); // And this too, of course
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment