Cast object (type double) in int

Ok so if i have this code

double a=1.5;
int b=(int)a;
System.out.println(b);

Everything works fine, but

Object a=1.5;
int b=(int)a;
System.out.println(b);

gives the following error after starting (Eclipse gives no errors)

java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer

Although when I do

Object a=1.5;
double b=(double)a;
int c=(int)b;
System.out.println(c);

or

Object a=1.5;
int b=(int)(double)a;
System.out.println(b);

Now nothing is wrong.

Why should you first transfer it to double?

+4
source share
3 answers

When you declare an object Object a = 1.5, you can verify by checking System.out.println(a.getClass())that the object is actually passed to the instance Double. This may be added to again Doubledue to unpacking agreements. After that, the value Doublecan be attributed to int.

, Double int, ClassCastException, . Double Integer.

+3

Object, unboxing ... type, . -, xxxValue. :

Object x = ...;
double d = (double) x;

:

Object x = ...;
double d = ((Double) x).doubleValue();

, Double, , , x Double.

, :

Object a = Double.valueOf(1.5); // Auto-boxing in the original code
int b = ((Integer) a).intValue(); // Unboxing in the original code
System.out.println(b);

, , , Double, Integer.

+3

, . Object "double", . , int double . :

double a=1.5;
int b=(int)a;
System.out.println(b);

"1". . , , int.

, , - , . ,

Object a=1.5;
double b=(double)a;
int c=(int)b;
System.out.println(c);


Object a=1.5;
int b=(int)(double)a;
System.out.println(b);

- .

+1

All Articles