4.4 Boolean Versus boolean
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.
4.4.1 How do I do that?
Any time you have an expression that uses !, ||, or &&, any Boolean values
are unboxed to boolean primitive values, and evaluated accordingly:
In this case, the result of the expression, a boolean, is boxed into the
Boolean case1 = true;
Boolean case2 = true;
boolean case3 = false;
Boolean result = (case1 || case2) && case3;
result variable.NOTEFor 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.
4.4.2 What about...
...direct object comparison? Object comparison works as it always has:
The result of running this code, at least in my JVM, is the text "Not
Integer i1 = 256;
Integer i2 = 256;
if (i1 == i2) System.out.println("Equal!");
else System.out.println("Not equal!");
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.
|
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:
Here, you would get the text "Equal!" Remember that int values from -127
Integer i1 = 100;
Integer i2 = 100;
if (i1 == i2) System.out.println("Equal!");
else System.out.println("Not equal!");
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.