THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

Shift operators can be used only on integer types. In the rare circumstance when you actually need to
manipulate the bits in a floating-point value, you can use the conversion methods on the classes Float and
Double, as discussed in "The Floating-Point Wrapper Classes" on page 191.


Exercise 9.2: Write a method that determines the number of 1 bits in a passed-in int, by using just the bit
manipulation operators (that is, don't use Integer.bitCount). Compare your solution with published
algorithms for doing thissee the related reading for "General Programming Techniques" on page 758 for one
source.


9.2.6. The Conditional Operator ?:


The conditional operator provides a single expression that yields one of two values based on a boolean
expression. The statement


value = (userSetIt? usersValue : defaultValue);


is equivalent to


if (userSetIt)
value = usersValue;
else
value = defaultValue;


The primary difference between the if statement and the ?: operator is that the latter has a value and so can
be used as part of an expression. The conditional operator results in a more compact expression, but
programmers disagree about whether it is clearer. We use whichever seems clearer at the time. When to use
parentheses around a conditional operator expression is a matter of personal style, and practice varies widely.
Parentheses are not required by the language.


The conditional operator expression has a type that is determined by the types of the second and third
expressions (usersValue and defaultValue in the above example). If the types of these expressions
are the same then that is the type of the overall expression. Otherwise, the rules get somewhat complicated:


If one expression is a primitive type and the other can be unboxed to become a compatible primitive
type, then the unboxing occurs and the expressions are reconsidered.


If both expressions are numeric primitive types then the resulting type is also a numeric primitive
type, obtained by numeric promotion if needed. For example, in

double scale = (halveIt? 0.5 : 1);

the two expressions are of type double (0.5) and type int ( 1 ). An int is assignable to a
double, so the 1 is promoted to 1.0 and the type of the conditional operator is double.


If one expression is an int constant, and the other is byte, short, or char, and the int value can
fit in the smaller type, then the resulting type is that smaller type.


If one of the expressions is a primitive type and the other is a reference type that can't be unboxed to
get a compatible value, or both expressions are primitive but incompatible, then the primitive type is
boxed so that we have two reference types.


Given two reference types that are different, the type of the expression is the first common parent
type. For example, if both expressions were unrelated class types that implemented Cloneable then

Free download pdf