Java, impossible cast Object to Float.....why?
Solution 1
Because you are relying on autoboxing when you wrote
Object prova = 9.2;
If you want it to be a Float, try
Object prova = 9.2f;
Remember that java.lang.Float and java.lang.Double are sibling types; the common type is java.lang.Number
If you want to express a Number in whatever format, use the APIs, for example Number.floatValue()
Solution 2
Because prova
is a Double
, and Double
is not a subtype of Float
.
Either you could start with a float literal: 9.2f
(in which case prova
would actually be a Float
) or, you could it like this:
Float prova2 = ((Double) prova).floatValue();
Solution 3
9.2
is a double literal. Try 9.2f
instead.
Object prova = 9.2f; // float literal is auto-boxed to a Float
System.out.println(prova);
Float prova2 = (Float) prova; // Float can be cast to Float, while Double cannot
System.out.println(prova2);
The error message (which you probably should have included in your question) explains it quite well also:
Exception in thread "main" java.lang.ClassCastException:
java.lang.Double cannot be cast to java.lang.Float
Solution 4
Because if you don't specify, it will be a double. If you want it to be a float, you need
Object prova = 9.2F;
System.out.println(prova);
Float prova2 = (Float) prova;
System.out.println(prova2);
Related videos on Youtube
Sgotenks
Updated on July 09, 2022Comments
-
Sgotenks over 1 year
Why this works:
Object prova = 9.2; System.out.println(prova); Double prova2 = (Double) prova; System.out.println(prova2);
And this doesn't?
Object prova = 9.2; System.out.println(prova); Float prova2 = (Float) prova; System.out.println(prova2);
I lost 1 hour in my java android application cause of this thing so i had to cast it in a double and than the double in a float or i had an exception
-
Anon almost 13 yearsIf you read the exception text from the latter (which I'm assuming is
ClassCastException
), and then look at the inheritance hierarchy forFloat
andDouble
, the answer should be apparent.
-