(String)、toString()和String.valueOf()的區(qū)別

本文將以從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()方法。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,837評論 18 139
  • Lua 5.1 參考手冊 by Roberto Ierusalimschy, Luiz Henrique de F...
    蘇黎九歌閱讀 13,877評論 0 38
  • java中String的常用方法 1、length()字符串的長度 例:char chars[]={'a','b'...
    赤赤有名閱讀 2,094評論 0 10
  • 才離開沒多久就開始 擔(dān)心今天的你過得好不好 整個畫面是你 想你想的睡不著 嘴嘟嘟那可愛的模樣 還有在你身上香香的味...
    L君幽默閱讀 415評論 0 0
  • 進入我鏡頭中的這對母子很偶然。我本來是想要拍她們背后緊閉的大門的照片,沒想到母子倆闖入了我的鏡頭,那么自然,那么美...
    茶葉蛋的Cha閱讀 374評論 0 3