Does == check for full equality in Booleans? - Java

左心房为你撑大大i 提交于 2019-11-30 11:09:06

Does == check for full equality in Booleans? - Java

It depends on whether you're talking about Booleans (the object wrapper, note the capital B) or booleans (the primitive, note the lower case b). If you're talking about Booleans (the object wrapper), as with all objects, == checks for identity, not equivalence. If you're talking about booleans (primitives), it checks for equivalence.

So:

Boolean a, b;
a = new Boolean(false);
b = new Boolean(false);
System.out.println("a == b? " + (a == b)); // "a == b? false", because they're not the same instance

But

boolean c, d;
c = false;
d = false;
System.out.println("c == d? " + (c == d)); // "c == d? true", because they're primitives with the same value

Regarding strings:

I've heard that if I compare 2 strings with == then I will only get true back if the strings are identical and they both refer to the same object/instance...

It's not really an "and": == will only check whether the two String variables refer to the same String instance. Of course, one String instance can only have one set of contents, so if both variables point to the same instance, naturally the contents are the same... :-) The key point is that == will report false for different String instances even if they have the same characters in the same order. That's why we use equals on them, not ==. Strings can get a bit confusing because of interning, which is specific to strings (there's no equivalent for Boolean, although when you use Boolean.valueOf(boolean), you'll get a cached object). Also note that Java doesn't have primitive strings like it does primitive boolean, int, etc.

If you have an Object use equals, when not you can run in things like this. (VM cache for autoboxing primitives)

    public static void main(String[] args){
       Boolean a = true;
       Boolean b = true;
       System.out.println(a == b);
       a = new Boolean(true);
       b = new Boolean(true);
       System.out.println(a == b);
   }

the output is TRUE and FALSE

It depends if you are talking about value types like: int, boolean, long or about reference types: Integer, Boolean, Long. value types could be compared with ==, reference types must be compared with equals.

When using ( == ) with booleans,

  1. If one of the operands is a Boolean wrapper,then it is first unboxed into a boolean primitive and the two are compared.

  2. If both are Boolean wrappers,created with 'new' keyword, then their references are compared just like in the case of other objects. new Boolean("true") == new Boolean("true") is false

  3. If both are Boolean wrappers,created without 'new' keyword,

    Boolean a = false;
    Boolean b = Boolean.FALSE;
    // (a==b) return true
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!