10

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?

3
  • null reference is different from "null" String. docs.oracle.com/javase/1.5.0/docs/api/java/lang/… Commented Nov 27, 2012 at 5:31
  • a debugger would have helped? Commented Nov 27, 2012 at 5:31
  • netbeans dont have debugger for java-string manupulation Commented Nov 27, 2012 at 5:32

2 Answers 2

14

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"
Sign up to request clarification or add additional context in comments.

6 Comments

thanks but when we compare both null and "null" then why both are not equal.
@arvin_codeHunk, null is an empty object, whereas "null" is an actual string containing the characters 'n', 'u', 'l', and 'l'.
The String here is written as null telling you that you just took the String value of null which is equal to "null". So a null will not be equal to "null" literal.
@rohit jain ok,but "As you can see, for a null value it returns "null" string" from above answer,if this null returns "null" string then off course this null and "null" both should be equal,correct me if i am wrong
@arvin_codeHunk.. Actually was searching for a valuable source for you. Well, the conversion of null to "null" string does not happens always, but only in certain pre-defined cases. Like in case of String Concatenation - As defined in JLS - String Concatenation. However, it is not defined for String Comparison.
|
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.