Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is difference between null and "null" of String.valueOf(String Object)

in my project ,Somewhere I have to use if n else condition to check the null variables

String stringValue = null;
String valueOf = String.valueOf(stringValue);

but when i check the condition like

  if (valueOf == null) {
        System.out.println("in if");
    } else {
        System.out.println("in else");
    }

then output is "in else" ,why this is happening?

like image 843
arvin_codeHunk Avatar asked Nov 27 '12 05:11

arvin_codeHunk


People also ask

What is the difference between null and string null?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .

What is difference between null and null?

Null has a default value 0. it can be used as bool,integer, pointer. But C# null is used when we are not pointing to some object.

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.

IS null a string or object?

“A null String is Java is literally equal to a reserved word “null”. It means the String that does not point to any physical address.” In Java programming language, a “null” String is used to refer to nothing. It also indicates that the String variable is not actually tied to any memory location.


2 Answers

Here's the source code of String.valueOf: -

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

As you can see, for a null value it returns "null" string.

So,

String stringValue = null;
String valueOf = String.valueOf(stringValue);

gives "null" string to the valueOf.

Similarly, if you do: -

System.out.println(null + "Rohit");

You will get: -

"nullRohit"

EDIT

Another Example:

Integer nulInteger = null;
String valueOf = String.valueOf(nulInteger) // "null"

But in this case.

Integer integer = 10;
String valueOf = String.valueOf(integer) // "10"
like image 98
Rohit Jain Avatar answered Nov 11 '22 18:11

Rohit Jain


Actually, you can have a look at the implementation of the method: valueOf(). You will know what happened then.

In JDK 1.5, its code is like this:

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

From the code, you can see that if the object is null it will return a not null string with "null" value in it, which means the valueOf object is not null.

like image 31
Lichader Avatar answered Nov 11 '22 18:11

Lichader