CHAPTER 4 ■ OPERATORS
Table 4-2. Unary operators
Operator Name Description
++expr Prefix increment Adds 1 to the value of the expression that follows
--expr Prefix decrement Subtracts 1 from the value of the expression that follows
+expr Unary plus Indicates a positive number (usually redundant)
-expr Unary minus Negates an expression (including literals)
~ Bitwise complement Performs a bit-by-bit reversal of an integer value
! Logical complement Reverses true and false
Let's consider a code example that exercises each of the unary operators (see Listing 4-3):
Listing 4-3. Unary operators
byte a = 0;
++a; // unary prefix increment operator - now a has a value of 1
--a; // unary prefix decrement operator - back to 0
byte b = +1; // unary plus operator (unnecessary)
byte c = -1; // unary minus operator to create a negative number
System.out.println(~b); // bitwise complement operator - prints -2
System.out.println(~c); // bitwise complement operator - prints 0
boolean myCatScratchesTheCouch = false;
System.out.println(!myCatScratchesTheCouch); // logical complement operator - prints true
Understanding the Bitwise Complement Operator
Java (and all programming languages) store values in one or more bytes, and each byte consists of 32
bits. When we talk about bytes in this context, we mean the units computers use for memory. That's not
the same as Java's data type called “Byte” (which has a minimum value of -128 and a maximum value of
of 127). The JVM stores a value of one as the following binary string: 00000000000000000000000000000001
(a 32-bit binary value that consists of 31 zeroes and a single one). When you use the bitwise complement
operator on it, the JVM turns all the zeroes into ones and all the ones into zeroes, resulting in
11111111111111111111111111111110 , which evaluates to -2. Similarly, -1 in binary is
11111111111111111111111111111111. Because that's all ones, the bitwise complement operator turns it to
all zeroes, so its value is 0.
I won't blame you if you think that's all meaningless trivia, but the bitwise complement operator
does have real-world uses. For example, in graphics programming, the color white is generally
represented by all the bits being 1. Applying the bitwise complement operator sets all the bits to 0, which
generally indicates the color black. The same principle applies to other colors (which have various bits
set to 0 or 1). In this fashion, a graphics program can quickly create a negative of an image without any
mathematical processing.