Search code examples
javaboolean-expression

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


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


Solution

  • Since isBar returns a primitive boolean, there is no semantic difference. Additionally, the second way is more concise, more clear, and more efficient, since the result won't have to be autboxed for the call and then have the original boolean extracted again. Given all that, there is no reason to use the first method, and several to use the second, so use the second. I give a great deal of leeway to fellow coders, but I would sit down and have a chat with anyone who added something like that to professional code.