JavaにおけるString.valueOf()
とObject.toString()
の違いをメモしておきます。
String.valueOf()
とObject.toString()
の違い
どちらもObject型をString型に変換してくれるメソッドですが、Object型の値がnull
の場合の挙動が異なります。
String.valueOf()
:"null"
という文字列を返すObject.toString()
:NullPointerException
が発生する
コードで書くと以下のとおりです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void main(String[] args) { | |
Object object = null; | |
String.valueOf(object); // "null"という文字列を返す | |
object.toString(); // NullPointerExceptionが発生する | |
} |
注意点として、String.valueOf(object)
は、null
を返すのではなく、"null"
という文字列を返します。
String.valueOf()
の中身を見てみるとわかりやすいかと思います。obj == null
の場合は"null"
を返し、それ以外の場合はobj.toString()
でObject型をString型に変換していますね。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String valueOf(Object obj) { | |
return (obj == null) ? "null" : obj.toString(); | |
} |
まとめ
String.valueOf()
とObject.toString()
の違いでした。Object型をString型に変換するときに、null
が値として入る可能性があるのであれば、例外が発生しないString.valueOf()
を使うのがよさそうです。