Difference between null and empty (“”) Java String

前端 未结 22 1501
再見小時候
再見小時候 2020-11-22 17:10

What is the difference between null and the \"\" (empty string)?

I have written some simple code:

String a = \"\";
String b         


        
相关标签:
22条回答
  • 2020-11-22 17:47

    Amazing answers, but I'd like to give from a different perspective.

    String a = "StackOverflow";
    String a1 = "StackOverflow" + "";
    String a2 = "StackOverflow" + null;
    
    System.out.println(a == a1); // true
    System.out.println(a == a2); // false
    
    

    So this can tell us "" and null point to the different object references.

    0 讨论(0)
  • 2020-11-22 17:48

    String is an Object and can be null

    null means that the String Object was not instantiated

    "" is an actual value of the instantiated Object String like "aaa"

    Here is a link that might clarify that point http://download.oracle.com/javase/tutorial/java/concepts/object.html

    0 讨论(0)
  • 2020-11-22 17:50

    "" is an actual string, albeit an empty one.

    null, however, means that the String variable points to nothing.

    a==b returns false because "" and null do not occupy the same space in memory--in other words, their variables don't point to the same objects.

    a.equals(b) returns false because "" does not equal null, obviously.

    The difference is though that since "" is an actual string, you can still invoke methods or functions on it like

    a.length()

    a.substring(0, 1)

    and so on.

    If the String equals null, like b, Java would throw a NullPointerException if you tried invoking, say:

    b.length()


    If the difference you are wondering about is == versus equals, it's this:

    == compares references, like if I went

    String a = new String("");
    String b = new String("");
    System.out.println(a==b);
    

    That would output false because I allocated two different objects, and a and b point to different objects.

    However, a.equals(b) in this case would return true, because equals for Strings will return true if and only if the argument String is not null and represents the same sequence of characters.

    Be warned, though, that Java does have a special case for Strings.

    String a = "abc";
    String b = "abc";
    System.out.println(a==b);
    

    You would think that the output would be false, since it should allocate two different Strings. Actually, Java will intern literal Strings (ones that are initialized like a and b in our example). So be careful, because that can give some false positives on how == works.

    0 讨论(0)
  • 2020-11-22 17:50

    You may also understand the difference between null and an empty string this way:

    Original image by R. Sato (@raysato)

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