Java, impossible cast Object to Float.....why?
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();
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()
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
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);