Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 926
user1508893 Avatar asked Oct 08 '12 03:10

user1508893


People also ask

Why is Boolean true equal?

Java Boolean equals() method The equals() method of Java Boolean class returns a Boolean value. It returns true if the argument is not null and is a Boolean object that represents the same Boolean value as this object, else it returns false.

Is Boolean true in Java?

The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true" . Example: Boolean.

What is the difference between Boolean true and true?

Boolean. TRUE is a reference to an object of the class Boolean, while true is just a value of the primitive boolean type. Classes like Boolean are often called "wrapper classes", and are used when you need an object instead of a primitive type (for example, if you're storing it in a data structure).

Is it true or true in Java?

To display Boolean type, firstly take two variables and declare them as boolean. val1 = true; Now, use if statement to check and display the Boolean true value.


Video Answer


1 Answers

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.

like image 189
Yogendra Singh Avatar answered Sep 20 '22 12:09

Yogendra Singh