12

Is there ever a situation where using equals(Boolean) and == would return different results when dealing with Boolean objects?

Boolean.TRUE == myBoolean;

Boolean.TRUE.equals(myBoolean);

I'm not thinking about primitive types here, just Boolean objects.

Edd
  • 8,053
  • 14
  • 45
  • 71

4 Answers4

11

How about:

System.out.println(new Boolean(true) == new Boolean(true));
System.out.println(new Boolean(true) == Boolean.TRUE);

(both print false, for the same reason as any other type of objects).

Community
  • 1
  • 1
assylias
  • 310,138
  • 72
  • 642
  • 762
2

It would be dangerous to use == because myBoolean may not have originated from one of the constants, but have been constructed as new Boolean(boolValue), in which case == would always result in false. You can use just

myBoolean.booleanValue()

with neither == nor equals involved, giving reliable results. If you must cater for null-values as well, then there's nothing better than your equals approach.

Marko Topolnik
  • 188,298
  • 27
  • 302
  • 416
2
if (Boolean.TRUE == new Boolean(true)) {
    System.out.println("==");
}

if (Boolean.TRUE.equals(myBoolean)) {
    System.out.println("equals");
}

In this case first one is false. Only second if condition is true.

It Prints:

equals

Clijsters
  • 3,598
  • 1
  • 27
  • 35
Vineet Singla
  • 1,539
  • 1
  • 18
  • 32
0

== only works for primitive types
when you compare Objects you should always use o.equls(Object ob)

Kuchi
  • 3,574
  • 3
  • 29
  • 37