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

后端 未结 2 1007
被撕碎了的回忆
被撕碎了的回忆 2021-01-18 01:18

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         


        
相关标签:
2条回答
  • 2021-01-18 01:36

    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"
    
    0 讨论(0)
  • 2021-01-18 01:45

    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.

    0 讨论(0)
提交回复
热议问题