Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is avoiding Boolean instantiation a good idea?

PMD is warning me to avoid Boolean instantiation (for efficiency reasons). I have something like this

Boolean variable = new Boolean(somestringIGotRepresentingABoolean);

And I'm supposed to use this

Boolean variable = Boolean.valueOf(somestringIGotRepresentingABoolean);

Why is that better?

like image 444
dertoni Avatar asked Jul 17 '14 07:07

dertoni


People also ask

What happens when Boolean is false?

FALSE is an object, so they're not really comparable. If you assign false to a Boolean variable, like this: Boolean b = false; Java's auto boxing occurs to convert the primitive into an object, so the false value is lost and you end up with Boolean.

What is the point of Boolean?

In computer science, the Boolean (sometimes shortened to Bool) is a data type that has one of two possible values (usually denoted true and false) which is intended to represent the two truth values of logic and Boolean algebra.

Do you need to initialize Boolean in Java?

Java boolean keyword is used to declare a variable as a boolean type which represents only one of two possible values i.e. either true or false . In java, by default boolean variables are initialized with false.

How do you instantiate a Boolean?

Boolean variables are variables that can have only two possible values: true, and false. To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false.


1 Answers

The reason is that new Boolean always returns a new instance. Since Boolean instances are immutable it does not make sense to have more than 2 instances. One for false and one for true.

Try this and you will see

Boolean boolean1 = new Boolean("true");
Boolean boolean2 = new Boolean("true");
Boolean boolean3 = new Boolean("true");

System.out.println(System.identityHashCode(boolean1));
System.out.println(System.identityHashCode(boolean2));
System.out.println(System.identityHashCode(boolean3));

Boolean valueOf1 = Boolean.valueOf("true");
Boolean valueOf2 = Boolean.valueOf("true");

System.out.println(System.identityHashCode(valueOf1));
System.out.println(System.identityHashCode(valueOf2));
like image 120
René Link Avatar answered Sep 18 '22 12:09

René Link