Home > Software design >  Does JVM specifically caches Boolean.(TRUE|FALSE)?
Does JVM specifically caches Boolean.(TRUE|FALSE)?

Time:06-04

Given Boolean value,

Boolean b = getSome();

Is following expression

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

equal(equivalent) to

return Boolean.TRUE.equal(b);

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

CodePudding user response:

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.

  • Related