Programming and Problem Solving with Java

(やまだぃちぅ) #1
9.3 Additional Java Operators | 451

int1 = 14;
int2 = ++int1;
// At this point, int1 == 15 and int2 == 15
int1 = 14;
int2 = int1++;
// At this point int1 == 15 and int2 == 14


Some people make a game of seeing how much they can accomplish in the fewest key-
strokes possible by using side effects in the middle of larger expressions. Professional soft-
ware development, however, requires writing code that other programmers can read and
understand. Use of side effects reduces readability.
By far, the most common use of ++and --is to perform the incrementation or decre-
mentation as a separate expression statement:


count++;


Here, the value of the expression is not used, but we get the desired side effect of incre-
menting count.


Bitwise Operators


You use the bitwise operators listed in Table 9.1 (<<,>>,>>>,&,|, and so forth) to manipulate
individual bits within a memory cell. This book does not explore the use of these operators;
the topic of bit-level operations is most often covered in a course on computer organization
and assembly language programming. However, we will draw your attention to the fact that
three of the bitwise operators have a second meaning in Java: The &,|and ^operators can
also be used with booleanoperands to perform logical AND, OR, and EXCLUSIVE OR opera-
tions without short-circuit evaluation.
Recall from Chapter 4 that when the first operand of &&is false, the second operand
need not be evaluated because the result must be false. When used in combination with
booleanoperands, the &operator causes the second operand to be evaluated regardless of the
value of the first operand. Similar rules apply to the |and ^operators.
Here is an example that illustrates the difference between these logical operators:


// This code works OK when i is 0 because m/i isn't evaluated
if (i != 0 && m/i >= 4)
k = 20;


Now consider what happens if we use & in place of &&:

// This code fails when i is 0 because of division by zero
if (i != 0 & m/i >= 4)
k = 20;


In rare cases, full evaluation is useful. We recommend, however, that you always use the re-
lational operators &&and ||in your logical expressions.

Free download pdf