Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does JVM specifically caches Boolean.(TRUE|FALSE)?

Given Boolean value,

Boolean b = getSome();

Is following expression

return Boolean.TRUE == b; // possibly false even b.booleanValue() is true?

equal(equivalent) to

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

return Boolean.TRUE.equal(b);

Does the JLS specify regarding any constant preservation of Boolean.(TRUE|FALSE)?

>Solution :

The JLS says that there may be caching behavior for values produced by boxing. However, it does not mandate it. (It is an implementation detail, as far as the JLS is concerned.)

See JLS 5.1.7

Furthermore, if you create a Boolean using new, it is guaranteed
that you will get a new object.

See JLS 15.9.4:

"The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created."

So for example:

Boolean falze = new Boolean(false);
if (Boolean.FALSE == falze) {
    System.out.println("falze is not FALSE");
}

will print the message.


Does the JLS specify regarding any constant preservation of Boolean.(TRUE|FALSE)?

The JLS does not mention those constants.

However, the javadoc for java.lang.Boolean does mention that they are constants, and Boolean is an immutable type.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading