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).
Asked
Active
Viewed 388 times
0

Sebastian Brosch
- 42,106
- 15
- 72
- 87

Ram Thota
- 539
- 5
- 9
-
1Why the c++ tag. It is very different to java – Jens Dec 11 '15 at 11:36
-
3Possible duplicate of [Cast Double to Integer in Java](http://stackoverflow.com/questions/9102318/cast-double-to-integer-in-java) – Ivaylo Toskov Dec 11 '15 at 11:39
2 Answers
0
Becuase, Float
is a class type. It derives from Object
. But int
is a primitive type. You can use floatValue()
for conversion.

Q Q
- 263
- 2
- 10
-
Yes, thats fine.. Please chech the below code.... Integer i = 10; Float f = (float)i; --->(1) and Float f1 = (Float)i; ---->(2).... Here statement (1) is working but not (2)... why...? – Ram Thota Dec 28 '15 at 10:20
0
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.

Luk
- 68
- 6