0 votes
1 view
in Java by (4.1k points)

Java boolean allows values of true and false while Boolean allows true, false, and null. I have started to convert my booleans to Booleans. This can cause crashes in tests such as

Boolean set = null;

...

if (set) ...

while the test

if (set != null && set) ...

seems contrived and error-prone.

When, if ever, is it useful to use Booleans with null values? If never, then what are the main advantages of the wrapped object?

1 Answer

0 votes
by (46.1k points)

Use boolean rather than Boolean every time you can. This will avoid many NullPointerExceptions and make your code more robust.

Boolean is useful, for example

  • to store booleans in a collection (List, Map, etc.)
  • to represent a nullable boolean (coming from a nullable boolean column in a database, for example). The null value might mean "we don't know if it's true or false" in this context.
  • each time a method needs an Object as argument, and you need to pass a boolean value. For example, when using reflection or methods like MessageFormat.format().

Related questions

0 votes
1 answer
asked Oct 28, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Aug 6, 2019 in Java by Anvi (10.2k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...