Comparing a string with the empty string (Java)

前端 未结 8 676
失恋的感觉
失恋的感觉 2020-12-02 11:17

I have a question about comparing a string with the empty string in Java. Is there a difference, if I compare a string with the empty string with == or eq

8条回答
  •  一向
    一向 (楼主)
    2020-12-02 12:09

    Short answer

    s1 == ""         // No!
    s1.equals("")    // Ok
    s1.isEmpty()     // Ok: fast (from Java 1.6) 
    "".equals(s1)    // Ok: null safe
    

    I would assure s1 is not null and use isEmpty().

    Note: empty string "" is not a special String, but counts as any other "value".

    A little longer answer

    References to String objects depend on the way they are created:

    String objects created using the operator new always refer to separate objects, even if they store the same sequence of characters so:

    String s1 = new String("");
    String s2 = new String("");
    s1 == s2 // false
    

    String objects created using the operator = followed by a value enclosed whitin double quotes (= "value") are stored in a pool of String objects: before creating a new object in the pool, an object with the same value is searched in the pool and referenced if found.

    String s1 = ""; // "" added to the pool
    String s2 = ""; // found "" in the pool, s2 will reference the same object of s1
    s1 == s2        // true
    

    The same is true for strings created enclosing a value whitin double quotes ("value"), so:

    String s1 = "";  
    s1 == "";        //true
    

    String equals method checks for both, that's why it is safe to write:

    s1.equals("");
    

    This expression may throw a NullPointerException if s1 == null, so, if you don't check for null before, it is safer to write:

    "".equals(s1);
    

    Please read also How do I compare strings in Java?

    Hope it may help not so experienced users, who may find other answers a bit too complicated. :)

提交回复
热议问题