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

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