Difference between casting to String and String.valueOf

前端 未结 8 2150
轮回少年
轮回少年 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:29

    The first one i.e, String.valueOf returns a string only if the object is a representable type which is a value type or a String.. Else it throws the exception.

    In the latter one, you are directly casting which can fail if the object isn't a string.

    Online example.

    http://ideone.com/p7AGh5

提交回复
热议问题