All three convert a value to its text form, but they handle null differently. obj.toString() throws NullPointerException when obj is null. String.valueOf(obj) returns the text "null". Concatenation with "" also produces "null", but it reads poorly and creates an extra operation.
Key Points: • String.valueOf() works for objects and primitives, and is null-safe for objects. • toString() is an instance method, so it needs a non-null object. Integer.toString(int) is the static version for primitives. • "" + value works, but it's less clear about intent, and some linters flag it. • Objects.toString(obj, "default") lets you choose the text for null instead of "null". • Watch out: String.valueOf((char[]) null) throws NullPointerException, because it calls the char[] overload.
Code Example:
import java.util.Objects;
public class ToStringNullSafety {
public static void main(String[] args) {
Integer count = 42;
Integer missing = null;
System.out.println(String.valueOf(count) + ", " + count.toString() + ", " + ("" + count));
System.out.println("valueOf(null): " + String.valueOf(missing));
System.out.println("\"\" + null: " + ("" + missing));
System.out.println("Objects.toString: " + Objects.toString(missing, "N/A"));
try {
missing.toString();
} catch (NullPointerException e) {
System.out.println("toString() on null: NullPointerException");
}
System.out.println("Primitive: " + String.valueOf(3.5) + ", " + Integer.toString(255, 16));
}
}Output:
42, 42, 42 valueOf(null): null "" + null: null Objects.toString: N/A toString() on null: NullPointerException Primitive: 3.5, ff
Good to Know: Getting the text "null" back is not always good: it can end up in a database column or a JSON field and look like real data. In business code, Objects.toString(value, "") or an explicit default is often safer than String.valueOf().
Interview Tip: A concise interview answer is:
"toString() is an instance method, so it throws NullPointerException on a null reference. String.valueOf() is null-safe and returns the text 'null', and concatenating with an empty string does the same but is less readable. When I need a custom value for null, I use Objects.toString(value, 'default')."
Previous question: Why is using + to concatenate Strings in a loop slow, and what should you use instead?
Next question: What is the difference between isEmpty() and isBlank(), and how do you safely check for null or empty Strings?