explain this inspection

I have the following code in my project:

Boolean foo = new Boolean(a_string);

It is flagged by IDEA and can be simplified to:

Boolean foo = Boolean.valueOf(a_string);

But why is that better?

3 comments
Comment actions Permalink

Hello Kevin,

I have the following code in my project:

Boolean foo = new Boolean(a_string);

It is flagged by IDEA and can be simplified to:

Boolean foo = Boolean.valueOf(a_string);

But why is that better?


This avoids creating a new Boolean object and instead reuses one of the singleton
TRUE or FALSE instances.

--
Dmitry Jemerov
Development Lead
JetBrains, Inc.
http://www.jetbrains.com/
"Develop with Pleasure!"


0
Comment actions Permalink

That makes sense. Thanks!

0
Comment actions Permalink

Kevin Hale Boyes wrote:

I have the following code in my project:

Boolean foo = new Boolean(a_string);

It is flagged by IDEA and can be simplified to:

Boolean foo = Boolean.valueOf(a_string);

But why is that better?


In Java libraries there are many classes which instances (the
objects, created from them) are IMMUTABLE. Means, once created, nothing
inside the object can be changed. Such are java.lang.String,
java.lang.Integer, java.lang.Boolean etc.
Every object of class java.lang.Boolean can have only two meanings:
Boolean.TRUE or Boolean.FALSE. Once created, the value (internally
stored in a boolean field named "value") can never ever be changed. And
when the VM loads (generally speaking) there are two static Boolean
objects, each of which represents one of the possible boolean values
(namely, Boolean.TRUE = true and Boolean.FALSE = false), so there is
usually no need to create another instance of class Boolean. Since it
will be either logically equal to Boolean.FALSE or to equal to
Boolean.TRUE. That is why "new Boolean(...)" is rarely needed ...

Hope this was helpful ;)
Greetings,
George

0

Please sign in to leave a comment.