Difference between casting to String and String.valueOf

前端 未结 8 2122
轮回少年
轮回少年 2020-12-02 12:10

What is the difference between

Object foo = \"something\";
String bar = String.valueOf(foo);

and

Object foo = \"something\"         


        
8条回答
  •  一生所求
    2020-12-02 12:23

    String.valueOf(foo) invokes foo's .toString() method and assigns the result to the the bar. It is null and type safe operation.

    Casting will just assign foo to the bar, if the types are matching. Otherwise, the expression will throw a ClassCastException.

提交回复
热议问题