What is the difference between String.valueOf() and toString() in Java?
Why Interviewers Ask This
This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.
Answer
toString() is an instance method — calling it on a null reference throws a NullPointerException. Every class inherits it from Object, and the default implementation returns the class name plus the object's hash code. You should override it to provide meaningful output. String.valueOf() is a static method that is null-safe — if the argument is null, it returns the string "null" instead of throwing. It is overloaded for all primitive types. In practice, String.valueOf(obj) internally calls obj.toString() if obj is not null. Use String.valueOf() when the object might be null, and toString() when you are certain it is not null.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.
Previous
What are the main garbage collection algorithms in Java?
Next
What is Reactive Programming and how does Java support it?