Vishrant
Vishrant

Reputation: 16638

Why "null" String is returned in String.valueOf instead of java null?

I was checking String.valueOf method and found that when null is passed to valueOf it returns "null" string instead of pure java null.

My question is why someone will return "null" string why not pure java null.

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

I am asking this because developer will have to check with equals method for "null" string and not like stringObj != null.

[update]: okay there were down votes for this question, I am not raising question in the api but in my current company there are lot of api which returns "null" string instead of pure java null that is why I asked this question to know whether is it a best practice to return "null" string if we found null string object.

Upvotes: 21

Views: 27112

Answers (4)

Bargle Burlap
Bargle Burlap

Reputation: 1

I would only use valueOf for displaying something directly. It doesn't offer robust enough validation and sanity checking to pass the output directly into a database, and could lead to incomplete data or data corruption.

Using the following query I discovered there were null-values in the columns.

Select * from tableName x where x.name is null

Upvotes: -2

Manuel Romeiro
Manuel Romeiro

Reputation: 1061

You are looking for Objects#toString(java.lang.Object,java.lang.String)

The call

Objects.toString(obj, null)

returns null when object is null.

Upvotes: 29

SacJn
SacJn

Reputation: 777

Because you only want a string representation of null and so it did. Purpose of this method is to return the String representation.

Check link String.valueOf

Upvotes: 1

Kayaman
Kayaman

Reputation: 73558

Because String.valueOf() returns a String representation, which for a null is "null".

The developer shouldn't be checking the return value at all, since it's meant for display purposes, not for checking whether a reference was null or not.

Upvotes: 23

Related Questions