The boolean type is a little bit of a special case for Java primitives, mostly because it has several logical operators associated with it, such as! (not), || (or), and && (and). With unboxing, these are now useful for Boolean values as well.
Any time you have an expression that uses !, ||, or &&, any Boolean values are unboxed to boolean primitive values, and evaluated accordingly:
Boolean case1 = true; Boolean case2 = true; boolean case3 = false; Boolean result = (case1 || case2) && case3;
In this case, the result of the expression, a boolean, is boxed into the result variable.
NOTE
For inquiring minds, primitives are boxed up to wrapper types in equality comparisons. For operators such as <, >=, and so forth, the wrapper types are unboxed to primitive types.
...direct object comparison? Object comparison works as it always has:
Integer i1 = 256; Integer i2 = 256; if (i1 == i2) System.out.println("Equal!"); else System.out.println("Not equal!");
The result of running this code, at least in my JVM, is the text "Not equal!" In this case, there is not an unboxing operation involved. The literal 256 is boxed into two different Integer objects (again, in my JVM), and then those objects are compared with ==. The result is false, as the two objects are different instances, with different memory addresses. Because both sides of the == expression contain objects, no unboxing occurs.
|
But, watch out! Remember (from "Converting Primitives to Wrapper Types"), that certain primitive values are unboxed into constant, immutable wrapper objects. So, the result of running the following code might be surprising to you:
Integer i1 = 100; Integer i2 = 100; if (i1 == i2) System.out.println("Equal!"); else System.out.println("Not equal!");
Here, you would get the text "Equal!" Remember that int values from -127 to 127 are in that range of immutable wrapper types, so the VM actually uses the same object instance (and therefore memory address) for both i1 and i2. As a result, == returns a true result. You have to watch out for this, as it can result in some very tricky, hard-to-find bugs.