Boolean.TRUE == myBoolean vs. Boolean.TRUE.equals(myBoolean)
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).
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.
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