Search code examples
javajls

Is boolean interned in Java?


The following code for Integer uses object interning:

Integer.valueOf("1")

It is not clear from API documentation whether this code for Boolean also uses interned object:

Boolean.valueOf("true")

Obviously, it may. But does it have to?

UPDATE

I agree that source code can explain what actually happens (BTW, thanks for the answers). To make the question less trivial, is there any part of Java API spec or JSL which tells what MUST happen?

It was natural to ask the question against the code like this:

String str = "true";
if (Boolean.valueOf(str) == Boolean.TRUE) { ... }

The outcome depends on whether "object interning" is guaranteed or not. It's better to avoid this code altogether and use true instead of Boolean.TRUE (rather than looking up details in any specs or sources), but it is a valid reason to ask the question.

NOTE: In fact, I didn't see guarantees of object interning for Integer in any googled specs. So, it may all be just an implementation detail nobody should rely on.


Solution

  • The JLS guarantees that:

    Integer i = 1;
    Boolean b = true;
    

    will use interning (at least between -128 and 127 for Integers, and for true and false for Booleans).

    The relevant javadocs also guarantee that:

    Integer i = Integer.valueOf(1);
    Boolean b = Boolean.valueOf(true);
    

    will return interned objects.

    However there is no such explicit guarantees for valueOf(String): although it is the case in the specific implementation you are using, it may not be the case with a different JVM or in future releases. In fact an implementation that would return new Boolean(Boolean.parseBoolean(input)) would be valid.