String.valueOf() vs. Object.toString()

后端 未结 10 776
挽巷
挽巷 2020-12-12 10:21

In Java, is there any difference between String.valueOf(Object) and Object.toString()? Is there a specific code convention for these?

10条回答
  •  忘掉有多难
    2020-12-12 10:46

    There is one more major difference between the two methods is when the object we are converting is an array.

    When you convert an array using Object.toString() you will get some kind of garbage value(@ followed by hashcode of array).

    To get a human-readable toString(), you must use String.valueOf(char[]); plz note that this method works only for Array of type char. I would recommend using Arrays.toString(Object[]) for converting arrays to String.

    Second difference is when the object is null, ValueOf() returns a String "null", while toString() will return null pointer exception.

提交回复
热议问题