It is necessary to convert the value acquired by Object type to String type toString (), String.valueOf (), cast conversion, etc. There are several ways to convert, but are there any differences? Next, And what I was most interested in was when the acquired Object type value was null. I wondered if an error would occur, so I looked it up. If you put the result first ...
toString() | String.valueOf() | Cast conversion |
---|---|---|
NullPointerException | String"null" | null |
test.java
public static void main(String[] args) {
Object testNull = null; //Object type null creation
String testNullString1 = testNull.toString(); // toString()Conversion by
String testNullString2 = String.valueOf(testNull); // String.valueOf()Conversion by
String testNullString3 = (String) testNull; //Cast conversion
//Store each converted value in Map
LinkedHashMap<String,String> map= new LinkedHashMap<>();
map.put("toString()",testNullString1);
map.put("String.valueOf()",testNullString2);
map.put("Cast conversion",testNullString3);
//Output each conversion result
for(Map.Entry<String, String> mapString : map.entrySet() ) {
if(mapString.getValue() == null) {
System.out.println(mapString.getKey() +"Converted with, it becomes null.");
}else if(mapString.getValue().equals("null")) {
System.out.println(mapString.getKey() +"Converted with\"null\"become.");
}else {
System.out.println(mapString.getKey() +"Converting with is something else.");
}
}
}
Execution result 1
Exception in thread "main" java.lang.NullPointerException
at Test_CastNull.main(Test_CastNull.java:11)
"NullPointerException" occurs in toString () conversion. It seems safe not to use toString (). Then, comment out the toString () part of the above test code and execute it again.
Execution result 2
String.valueOf()Converted with"null"become.
Converted by cast conversion, it becomes null.
So, of course, you need to be careful when handling null (the one that can be).
Recommended Posts