Reputation: 2952
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
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
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