Cast object (type double) to int

前端 未结 3 1343
北海茫月
北海茫月 2020-12-11 08:31

Okay, 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;
in         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-11 09:15

    When you declare the object Object a = 1.5 you can tell by checking System.out.println(a.getClass()) that the object is in fact cast to a Double instance. This can again be cast to a double because of unboxing conventions. After that the double value can be cast to an int.

    There are however no unboxing conventions to cast from a Double instance to an int, so the runtime will issue an ClassCastException if you try and do that. It cannot directly go from Double to Integer.

提交回复
热议问题