Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 859
Vishrant Avatar asked Nov 24 '15 11:11

Vishrant


People also ask

Can string valueOf return null?

The String. valueOf(Object) method, as its Javadoc-generated documentation states, returns "null" if the passed in object is null and returns the results on the passed-in Object 's toString() call if the passed-in Object is not null.

What does string valueOf return in Java?

Java - String valueOf() Method This method returns the string representation of the passed argument. valueOf(boolean b) − Returns the string representation of the boolean argument.

What happens if you return null Java?

In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing. The compiler assigns null to any uninitialized static and instance members of reference type. In the absence of a constructor, the getArticles() and getName() methods will return a null reference.

Is it good practice to return null in Java?

Returning Null is Bad Practice The FirstOrDefault method silently returns null if no order is found in the database. There are a couple of problems here: Callers of GetOrder method must implement null reference checking to avoid getting a NullReferenceException when accessing Order class members.


2 Answers

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.

like image 163
Kayaman Avatar answered Sep 17 '22 14:09

Kayaman


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

The call

Objects.toString(obj, null)

returns null when object is null.

like image 44
Manuel Romeiro Avatar answered Sep 17 '22 14:09

Manuel Romeiro