While I'm doing typecast from float to int type and typecast from Integer to int it is working. But while i am trying to typecast from Float to int type I'm getting the error as "incompatible type". Why can't we typecast from wrapper to primitive type (Except for its own primitive type).
- 1Why the c++ tag. It is very different to javaJens– Jens2015-12-11 11:36:01 +00:00Commented Dec 11, 2015 at 11:36
- 3Possible duplicate of Cast Double to Integer in JavaIvaylo Toskov– Ivaylo Toskov2015-12-11 11:39:04 +00:00Commented Dec 11, 2015 at 11:39
2 Answers
Becuase, Float is a class type. It derives from Object. But int is a primitive type. You can use floatValue() for conversion.
1 Comment
Well that's kind of what makes the difference between wrapper classes and primitives. It wrapps the value around a Class with useful methods. That's why for converting to int, you'd have to either use
Float f; int i = (int)(f.floatValue()); or of course
Float f; int i = f.intValue(); In the sense that a wrapper is a class that wrapps around a certain value, it's more logical to extract a value from that class rather than converting a class to a value.
Note the source code for java.lang.Float: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Float.java#Float.intValue%28%29 Maybe that makes things clearer.