When “” == s is false but “”.equals( s ) is true

前端 未结 10 1471
深忆病人
深忆病人 2020-11-30 19:46

EDIT Thanks for the prompt responses. Please see what the real question is. I have made it bold this time.

I do understand the difference between ==

10条回答
  •  再見小時候
    2020-11-30 20:26

    Why not use:

    if (value != null && value.length == 0) {
        // do stuff (above could be "== null ||"
    }
    

    You should use equals() because == for objects compares references, i.e., are they the same object. Whilst at compile time Java finds identical strings and makes them share the same reference (Strings are immutable), at runtime it is easy to create empty strings that have different references, where == fails for your typical intention of equals().

提交回复
热议问题