Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, impossible cast Object to Float.....why?

Tags:

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

like image 285
Sgotenks Avatar asked May 12 '11 16:05

Sgotenks


People also ask

Can you cast an object in Java?

Type Casting in Java – An IntroductionType Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind or Object, and the process of conversion from one type to another is called Type Casting.

How does casting objects work in Java?

Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion or type coercion. In Java, we can cast both reference and primitive data types. By using casting, data can not be changed but only the data type is changed.


2 Answers

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

like image 83
Dilum Ranatunga Avatar answered Sep 28 '22 00:09

Dilum Ranatunga


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(); 
like image 27
aioobe Avatar answered Sep 28 '22 01:09

aioobe