Java String.valueOf() vs toString() behavior with null objects

A small Java concept I revisited this week: Difference between String.valueOf() and toString() At first glance, both convert objects to String: String.valueOf(obj) obj.toString() But their behavior is different when the object is null. Example: Object obj = null; String.valueOf(obj); // returns "null" obj.toString();  // throws NullPointerException So why does this happen? Let’s look at the internal working. Inside the String class, String.valueOf(Object obj) is implemented like this: public static String valueOf(Object obj) {  return (obj == null) ? "null" : obj.toString(); } This means: • If the object is null → it safely returns the string "null" • Otherwise → it calls obj.toString() But when we directly call: obj.toString() Java tries to invoke a method on a null reference, which immediately throws a NullPointerException. Why this matters in real applications: When converting values (like IDs, numbers, or objects) to String, String.valueOf() is often safer because it avoids unexpected crashes. Small details like this make Java code more reliable. Always interesting how tiny language features can prevent real production bugs. Which one do you usually use in your projects? #Java #BackendEngineering #SoftwareEngineering #JavaTips #LearningInPublic

This is one of those small Java details that can prevent runtime surprises.

but the question is if String.valueOf already handle both null and toString why should we use toString directly

RIDDHI RADIA I have used object.toString() mostly to display the object contents, but i think given that it can give null pointer exception, we should always use this with the null check.

You can use it gets non localised value of number objects like Integer - helps much in kotlin java interop

Interesting explanation...One thing I’m curious to know ... Is this the reason why many logging frameworks prefer String.valueOf() internally to prevent NullPointerException when logging potentially null objects?”

Great breakdown! I've used both methods, but seeing the internal logic really clarifies how Java handles null safety behind the scenes.

See more comments

To view or add a comment, sign in

Explore content categories