Himanshu Gupta wrote:To verify it I checked the source code of Boolean class and found astonishing results. Every time we create a Boolean Object a new Object is created. But why do we need a new Object? Lets say we can have two Objects in cache as immutable and whenever we need one a reference to them will be given just like Integer class where a cache is maintained of integers from -128 to +127.
If you use the
new operator, then a new object is created - always. This is also true for Integer objects. If you do this:
then a new Integer object will be created - this will not reuse an Integer object from the cache. The cache for Integer is only used when you use the Integer.valueOf(int) method, or in the case of autoboxing (because autoboxing uses Integer.valueOf(int) behind the scenes).
In the case of Boolean, there are only two values, which are defined as constants in the Boolean class: Boolean.TRUE and Boolean.FALSE. Use those two constants, or use Boolean.valueOf(boolean), which will return one of the two constants.