I come from Python background and taking a dive into Java world. I am trying to convert Float to int in Java. Something we do like this in Python int_var = int(float_var) Yields the following error - public class p1 { public static void main(String args[]) { Integer a = new Integer(5); Float b; b = new Float(3.14); a = (int)b; System.out.println(a); } } p1.java:7: error: inconvertible types a = (int)b; ^ required: int found: Float 1 error
- Are you aware of primitive types and their difference with their wrapper type, i.e. int vs. Integer and float vs. Float? Why are you using wrapper types instead of primitives? You shouldn't.JB Nizet– JB Nizet2013-07-26 06:53:52 +00:00Commented Jul 26, 2013 at 6:53
- Okay, guess that I got confused there.Anirudh– Anirudh2013-07-26 06:59:43 +00:00Commented Jul 26, 2013 at 6:59
- In general, never use wrapper types unless you need an Object (to be storable in a collection, for example), or a nullable primitive. Primitive types are faster and safer. There is no reason in the code you posted to use wrapper types.JB Nizet– JB Nizet2013-07-26 07:03:34 +00:00Commented Jul 26, 2013 at 7:03
Add a comment |
9 Answers
Use primitives types, and you will be fine:
int a = 5; float b = 3.14f; // 3.14 is by default double. 3.14f is float. a = (int)b; The reason it didn't work with Wrappers is those types are non-covariant, and thus are incompatible.
And if you are using Integer types (Which you really don't need here), then you should not create Wrapper type objects using new. Just make use of auto-boxing feature:
Integer a = 5; // instead of `new Integer(5);` the above assignment works after Java 1.5, performing auto-boxing from int primitive to Integer wrapper. It also enables JVM to use cached Integer literals if available, thus preventing creation of unnecessary objects.
4 Comments
Anirudh
float b = 3.14f. What is the need for the f postfix?Rohit Jain
Floating point literal
3.14 is by default double. For float, it's 3.14f.JB Nizet
To make it compile. 3.14 is a double.
ManMohan Vyas
thus are inconvertible ... wrappers are convertable through helper functions though