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

boolean, equals-operator, java

Solution

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

It depends on whether you're talking about `Boolean`s (the object wrapper, note the capital `B`) or `boolean`s (the primitive, note the lower case `b`). If you're talking about `Boolean`s (the object wrapper), as with all objects, `==` checks for identity, not equivalence. If you're talking about `boolean`s (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 `intern`ing, 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.

Problem

So I've heard that if I compare 2 strings with == then I will only get true back if they both refer to the same object/instance. That's strings. What about Booleans?

Original source