☕ Java Advanced

What is the difference between String.valueOf() and toString() in Java?

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.