1

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).

2
  • 1
    Why the c++ tag. It is very different to java Commented Dec 11, 2015 at 11:36
  • 3
    Possible duplicate of Cast Double to Integer in Java Commented Dec 11, 2015 at 11:39

2 Answers 2

1

Becuase, Float is a class type. It derives from Object. But int is a primitive type. You can use floatValue() for conversion.

Sign up to request clarification or add additional context in comments.

1 Comment

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...?
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.