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.