in the development often encountered from the collection class list, the map to remove the data into a string problem, if handled poorly, often encounter null pointer exception Java.lang.NullPointerException, here is a summary of the commonly used conversion to string method, and how to use the null after conversion problem.
common ways in which objects in Java are converted to string:
Method 1, String objstr = (string) obj:
Coercion type cast, object obj is null, the result is also null, However, obj must ensure that its essence is a value of type string and can be converted to a value. For example, you cannot cast (String) 123
Method 2, String Objstr = Obj.tostring method : Call the object's ToString method, you must ensure that the class or the parent class has overridden the object class's ToString method, If you do not override the ToString method, the ToString method of the object class is called by default, returning GetClass (). GetName () + ' @ ' + integer.tohexstring (hashcode ()), is not an actual string representation of obj, but must also ensure that the object obj cannot be null, and that the ToString method will report null pointer exception java.lang.NullPointerException.
Method 3, String objstr =
string.valueof (obj) : object obj is null, the conversion result is a string c10> "null", Otherwise, returns
obj.toString() the value. Note that if obj is null, the converted value is already the "null" of the string, and the null can no longer be used with obj = = nullland should be str.equals ("null"). If you already know that obj is a string type, you can directly use
Method 1 to convert to string, and the null condition to string is:
if (
objstr! = null) method of careful use 2for cases where the specific type is not known, you can use
Method 3, except that the null condition of the converted string is changed to:
if (!objstr.equals (' null ')) Test Code:
Public Static voidTeststringnull () {//String, ToString, string.valueof ()Object obj =NULL; String strbystring=(String) obj;//String strbytostring = obj.tostring (); //toString must be guaranteed not to be null, otherwise java.lang.NullPointerExceptionString strbystringvalueof =string.valueof (obj); System.out.println ("Strbystring=" +strbystring+ ", strbystringvalueof=" +strbystringvalueof); if(Strbystring = =NULL) {System.out.println ("Strbystring is null");//Execution } if(Strbystring! =NULL&& strbystring.equals ("null") {System.out.println ("Strbystring is not NULL, is \" Null\ "");//do not execute } if(strbystringvalueof = =NULL) {System.out.println ("Strbystringvalueof is null");//do not execute } if(Strbystringvalueof! =NULL&& strbystringvalueof.equals ("null") {System.out.println ("Strbystringvalueof is not NULL, is \" Null\ "");//Execution }}
Questions about NULL for Java String type conversions