Java 1.5 Tiger A Developers Notebook [Electronic resources]

David Flanagan, Brett McLaughlin

نسخه متنی -صفحه : 131/ 52
نمايش فراداده

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:

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.

4.4.2 What about...

...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.

You can't depend on this result; it's merely used as an illustration. Some JVMs may choose to try and optimize this code, and create one instance for both Integer objects, and in that case, the == operator would return a true result.

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.