Sergei Voitovich
Sergei Voitovich

Reputation: 2952

Instantiating Boolean object in Java: Boolean.TRUE and Boolean.FALSE vs primitives

I want to figure out whether

Boolean var = true;

is any better than

Boolean var = Boolean.True;

?

What is an ideological way? Which one is better comparing performance?

After all why there're instantiated Boolean objects if we have two primitives to use?

Upvotes: 1

Views: 907

Answers (2)

Aakash Patel
Aakash Patel

Reputation: 557

Go for Boolean.TRUE;

The reason

boolean boolVar = Boolean.TRUE;

works is because of autounboxing, a Java 5 feature that allows a wrapper object to be converted to its primitive equivalent automatically when needed. The opposite, autoboxing, is also possible:

Boolean boolVar = true;

Boolean.TRUE is a reference to an object of the class Boolean, on the other hand, true is value of the primitive boolean type. Boolean class is often called "wrapper classes", and are used when you need an object instead of a primitive type.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201437

Your two snippets perform identically, because the Java compiler will autobox primitives to their wrapper types (which means the code is effectively identical). The primitive type boolean would typically be expected to have slightly better performance, if you did boolean var = true; (but it probably isn't measurable).

Upvotes: 1

Related Questions