Passing null to String.valueOf in Java returns the string “null”

Passing null to String.valueOf in Java returns the string “null”

In Java, when an object containing null is passed to String.valueOf, the string “null” is returned.

The method of String.valueOf is as follows.

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

If obj is null, it returns “null”, which makes no sense.

In other words, null is also made “null” by the string, so you need to be careful.

When using String.valueOf, null should be considered.

Resolving with Objects.toString() from Java7

Objects.toString(first parameter,second parameter);

The return value of this method is of type String, and the first argument can be anything; if it is null, the second argument is returned; if it is not null, the first argument is returned as a String.

This method can be used to avoid returning the string “null”.

String str = Objects.toString(1, null);
System.out.println(str); // Returns a String type of 1.
str = Objects.toString(null, null);
System.out.println(str); // null is returned

valueOf. toString() method may fail due to null pointer, and valueOf will be “null”, so Objects.toString() is recommended.

Note that passing null directly as an argument as shown below will result in null pointer.

String.valueOf(null);

コメント

タイトルとURLをコピーしました