The difference between String String.valueof() toString~

The difference between String String.valueof() toString~

( String  ) Coercion type conversion. When using this method, it should be noted that the type must be able to be converted to String type. Therefore, it is best to use instanceof to do a type check to determine whether it can be converted. Otherwise it is easy to throw CalssCastException exception. It can only convert objects that are originally of type String, otherwise an error will be reported;

ToString string type conversion, pay attention when using it, you must ensure that the object is not a null value, otherwise a NullPointerException will be thrown

String.valueof() will not report an error when the transferred variable is null (this method is recommended)

This method is static and can be called directly through String. It can be said to be perfect, but I am not used to writing this way. This implementation avoids the shortcomings and shortcomings of the previous two. First, let's take a look at its internal implementation mechanism:

1
2
3
public  static  String valueOf(Object obj){
     return  (obj== null ) ?  "null"  : obj.toString()
};
When object is null, the value of String.valueOf(object) is the string "null", not null! ! ! Remember to pay attention during use. .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325726785&siteId=291194637