Difference between null and empty (“”) Java String

前端 未结 22 1688
再見小時候
再見小時候 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:40

    When you write

    String a = "";

    It means there is a variable 'a' of type string which points to a object reference in string pool which has a value "". As variable a is holding a valid string object reference, all the methods of string can be applied here.

    Whereas when you write

    String b = null;

    It means that there is a variable b of type string which points to an unknown reference. And any operation on unknown reference will result in an NullPointerException.

    Now, let us evaluate the below expressions.

    System.out.println(a == b); // false. because a and b both points to different object reference
    
    System.out.println(a.equals(b)); // false, because the values at object reference pointed by a and b do not match.
    
    System.out.println(b.equals(a)); // NullPointerException, because b is pointing to unknown reference and no operation is allowed
    

提交回复
热议问题