Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is boolean interned in Java?

Tags:

java

jls

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.

like image 212
uvsmtid Avatar asked Jun 19 '16 08:06

uvsmtid


2 Answers

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.

like image 133
assylias Avatar answered Oct 15 '22 14:10

assylias


Based on the source code, the boolean is parsed as:

public static final Boolean FALSE = new Boolean(false);
public static final Boolean TRUE = new Boolean(true);

public static Boolean valueOf(String s) {
    return toBoolean(s) ? TRUE : FALSE;
}

Where TRUE and FALSE are static (immutable) objects. So yes, parsed booleans are interned.

However, I agree with @JBNizet's comment that one should not derive code contracts from the source code: as long as a feature is not documented, the developers of Java can change their mind. You better use Boolean.equals to check whether two objects are equivalent.

like image 33
Willem Van Onsem Avatar answered Oct 15 '22 13:10

Willem Van Onsem