简体   繁体   English

String.valueOf(String Object)的null和“null”有什么区别

[英]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? 然后输出是“在其他地方” ,为什么会发生这种情况?

Here's the source code of String.valueOf : - 这是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. 如您所见,对于null值,它返回"null"字符串。

So, 所以,

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

gives "null" string to the valueOf . "null"字符串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"

Actually, you can have a look at the implementation of the method: valueOf(). 实际上,您可以查看方法的实现:valueOf()。 You will know what happened then. 你会知道那时发生了什么。

In JDK 1.5, its code is like this: 在JDK 1.5中,其代码如下:

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. 从代码中,您可以看到如果对象为null,它将返回一个非空字符串,其中包含“null”值,这意味着valueOf对象不为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM