Is there any reason for "Boolean.TRUE.equals(x)" in Java?

user1508893 picture user1508893 · Oct 8, 2012 · Viewed 17.7k times · Source

I've come across this code in one of the projects I'm working on

(This is in Java)

if (Boolean.TRUE.equals(foo.isBar()))

Foo#isBar() is defined as boolean isBar(), so it can't return null

Is there really any reason why it should be written that way? I myself would just write

if (foo.isBar())

, but perhaps I'm missing something subtle.

Thanks

Answer

Yogendra Singh picture Yogendra Singh · Oct 8, 2012

I hope foo.isBar() returns a boolean. In that case you can always write if (foo.isBar()). If you foo.isBar() returns Boolean then it can be either Boolean.TRUE, Boolean.FALSE or NULL. In that case if (Boolean.TRUE.equals(foo.isBar())) makes sure the if block is executed in one scenario(TRUE) and omitted in remaining 2.

Over and above if (foo.isBar()) will fail, when foo.isBar() returns Boolean NULL.