Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...