本文將以從int類型轉(zhuǎn)為String類型的方法為例,講解從其他類型轉(zhuǎn)換到String類型的各種方法,以及其中的區(qū)別。
1.(String)強制轉(zhuǎn)換一式
Object obj = new Integer(100);
String str = (String)obj;
System.out.println(str);
【失敗】
此種情況可以在語法檢測上通過,但是運行后會報錯:
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
2.(String)強制轉(zhuǎn)換二式
String str = (String)100;
【失敗】
從圖中提示可以發(fā)現(xiàn),IDE直接報錯,提示不能從int類型轉(zhuǎn)換為java.lang.String類型。
3.String特殊轉(zhuǎn)換
String str = "" + 100;
System.out.println(str);
【成功】
參考的是Java規(guī)范。這里引用的是一個匿名的知乎用戶的回答。原文鏈接:https://www.zhihu.com/question/57105649/answer/151613096
If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.
渣翻如下
如果其中一個操作數(shù)表達式是String,那么對另一個操作數(shù)執(zhí)行字符串轉(zhuǎn)換,以在運行時產(chǎn)生一個字符串。
字符串連接的結(jié)果是對一個String對象的引用,該對象是兩個操作數(shù)字符串的連接。左側(cè)操作數(shù)的字符位于新創(chuàng)建的字符串中右側(cè)操作數(shù)的字符之前。
4.Integer.toString(int i)方法
String str = Integer.toString(100);
System.out.println(str);
【成功】
使用的是int的包裝類中實現(xiàn)的toString方法。
5.String.valueOf(int i)方法
String str = String.valueOf(100);
System.out.println(str);
【成功】
我在查看源代碼時發(fā)現(xiàn)調(diào)用的是Integer中的toString方法,也就是4的方法。
public static String valueOf(int i) {
return Integer.toString(i);
}
但是查看網(wǎng)上的資料中寫的都是調(diào)用這個方法
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
想了一下,發(fā)現(xiàn)自己有點傻,原來String.valueOf()方法經(jīng)過很多重載,可以通過傳入的參數(shù)類型加以區(qū)分,從而調(diào)用相應(yīng)的toString()方法進行類型轉(zhuǎn)換。
使用的全部是基本類型對應(yīng)的包裝類,類似的方法還有很多,例如:
public static String valueOf(long l) {
return Long.toString(l);
}
public static String valueOf(float f) {
return Float.toString(f);
}
6.總結(jié)
上述幾種成功的方法中,只有String.valueOf()方法會首先對轉(zhuǎn)換的對象進行判空檢測,如果為空,則返回“null”字符串,以至于不會報出空指針異常。
所以,在遇到字符串轉(zhuǎn)換的時候,首選String.valueOf()方法。