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.
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.
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.
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.
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.
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.
You are looking for Objects#toString(java.lang.Object,java.lang.String)
The call
Objects.toString(obj, null)
returns null when object is null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With