Operators
An operator
The unary operators support either prefix or postfix notation. Prefix notation means that the operator appears before its operand: operator op //prefix notation Postfix notation means that the operator appears after its operand: op operator //postfix notation
All the binary operators use
op1 operator op2 //infix notation The ternary operator is also infix; each component of the operator appears between operands: op1 ? op2 : op3 //infix notation
In addition to performing the operation, an operator returns a value. The return value and its type depend on the operator and the type of its operands. For example, the arithmetic operators, which perform such basic arithmetic operations as addition and subtraction, return
We divide the operators into these categories:
Arithmetic OperatorsThe Java programming language supports various arithmetic operators for all floating-point and integer numbers. These operators are + (addition), - (subtraction), * (multiplication), / (division), and % (modulo). Table 5 summarizes the binary arithmetic operations in the Java programming language. Table 5. Binary Arithmetic Operators
public class ArithmeticDemo {
public static void main(String[] args) {
//a few numbers
int i = 37;
int j = 42;
double x = 27.475;
double y = 7.22;
System.out.println("Variable values...");
System.out.println(" i = " + i);
System.out.println(" j = " + j);
System.out.println(" x = " + x);
System.out.println(" y = " + y);
//adding numbers
System.out.println("Adding...");
System.out.println(" i + j = " + (
i + j
));
System.out.println(" x + y = " + (
x + y
));
//subtracting numbers
System.out.println("Subtracting...");
System.out.println(" i - j = " + (
i - j
));
System.out.println(" x - y = " + (
x - y
));
//multiplying numbers
System.out.println("Multiplying...");
System.out.println(" i * j = " + (
i * j
));
System.out.println(" x * y = " + (
x * y
));
//dividing numbers
System.out.println("Dividing...");
System.out.println(" i / j = " + (
i / j
));
System.out.println(" x / y = " + (
x / y
));
//computing the remainder resulting from dividing numbers
System.out.println("Computing the remainder...");
System.out.println(" i % j = " + (
i % j
));
System.out.println(" x % y = " + (
x % y
));
//mixing types
System.out.println("Mixing types...");
System.out.println(" j + y = " + (
j + y
));
System.out.println(" i * x = " + (
i * x
));
}
}
The output from this program is:
Variable values...
i = 37
j = 42
x = 27.475
y = 7.22
Adding...
i + j = 79
x + y = 34.695
Subtracting...
i - j = -5
x - y = 20.255
Multiplying...
i * j = 1554
x * y = 198.37
Dividing...
i / j = 0
x / y = 3.8054
Computing the remainder...
i % j = 37
x % y = 5.815
Mixing types...
j + y = 49.22
i * x = 1016.58
Note that when an integer and a floating-point number are used as operands to a single arithmetic operation, the result is floating point. The integer is implicitly converted to a floating-point number before the operation takes place. Table 6 summarizes the data type returned by the arithmetic operators, based on the data type of the operands. The necessary conversions take place before the operation is performed. Table 6. Data Types Returned by Arithmetic Operators
In addition to the binary forms of + and - , each of these operators has unary versions that perform the following operations, as shown in Table 7. Table 7. Unary Arithmetic Operators
Two shortcut arithmetic operators are
++
, which increments its operand by 1, and
--
, which decrements its operand by 1. Either
++
or
--
can appear before
(prefix)
or after
(postfix)
its operand. The prefix version,
++op
/
--op
,
public class SortDemo {
public static void main(String[] args) {
int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,
2000, 8, 622, 127 };
for (int i = arrayOfInts.length;
--i >= 0
; ) {
for (int j = 0; j < i;
j++
) {
if (arrayOfInts[j] > arrayOfInts[j+1]) {
int temp = arrayOfInts[j];
arrayOfInts[j] = arrayOfInts[j+1];
arrayOfInts[j+1] = temp;
}
}
}
for (int i = 0; i < arrayOfInts.length;
i++
) {
System.out.print(arrayOfInts[i] + " ");
}
System.out.println();
}
}
This program puts ten integer values into an array -a fixed-length structure that can hold multiple values of the same type -then sorts them. The boldface line of code declares an array referred to by arrayOfInts , creates the array, and puts ten integer values into it. The program uses arrayOfInts.length to get the number of elements in the array. Individual elements are accessed with this notation: arrayOfInts[ index ] , where index is an integer indicating the position of the element within the array. Note that indices begin at 0. You'll get more details and examples for arrays in the section Arrays (page 165).
The output from this program is a list of numbers sorted from
3 8 12 32 87 127 589 622 1076 2000
Let's look at how the
SortDemo
program uses
--
to help control the outer of its two nested sorting
for (int i = arrayOfInts.length;
--i >= 0
; ) {
...
}
The for statement is a looping construct, which you'll meet later in this chapter. What's important here is the code set in boldface, which continues the for loop as long as the value returned by --i is greater than or equal to 0. Using the prefix version of -- means that the last iteration of this loop occurs when i is equal to 0. If we change the code to use the postfix version of -- , the last iteration of this loop occurs when i is equal to -1, which is incorrect for this program because i is used as an array index and -1 is not a valid array index. The other two loops in the program use the postfix version of ++ . In both cases, the version used doesn't really matter, because the value returned by the operator isn't used for anything. When the return value of one of these shortcut operations isn't used for anything, convention prefers the postfix version. The shortcut increment/decrement operators are summarized in Table 8. Table 8. Shortcut Increment and Decrement Operators
Relational and Conditional Operators
A relational operator
Table 9. Relational Operators
public class RelationalDemo {
public static void main(String[] args) {
//a few numbers
int i = 37;
int j = 42;
int k = 42;
System.out.println("Variable values...");
System.out.println(" i = " + i);
System.out.println(" j = " + j);
System.out.println(" k = " + k);
//greater than
System.out.println("Greater than...");
System.out.println(" i > j is " + (i > j)); //false
System.out.println(" j > i is " + (j > i)); //true
System.out.println(" k > j is " + (k > j)); //false
//greater than or equal to
System.out.println("Greater than or equal to...");
System.out.println(" i >= j is " + (i >= j)); //false
System.out.println(" j >= i is " + (j >= i)); //true
System.out.println(" k >= j is " + (k >= j)); //true
//less than
System.out.println("Less than...");
System.out.println(" i < j is " + (i < j)); //true
System.out.println(" j < i is " + (j < i)); //false
System.out.println(" k < j is " + (k < j)); //false
//less than or equal to
System.out.println("Less than or equal to...");
System.out.println(" i <= j is " + (i <= j)); //true
System.out.println(" j <= i is " + (j <= i)); //false
System.out.println(" k <= j is " + (k <= j)); //true
//equal to
System.out.println("Equal to...");
System.out.println(" i == j is " + (i == j)); //false
System.out.println(" k == j is " + (k == j)); //true
//not equal to
System.out.println("Not equal to...");
System.out.println(" i != j is " + (i != j)); //true
System.out.println(" k != j is " + (k != j)); //false
}
}
Here's the output from this program:
Variable values...
i = 37
j = 42
k = 42
Greater than...
i > j is false
j > i is true
k > j is false
Greater than or equal to...
i >= j is false
j >= i is true
k >= j is true
Less than...
i < j is true
j < i is false
k < j is false
Less than or equal to...
i <= j is true
j <= i is false
k <= j is true
Equal to...
i == j is false
k == j is true
Not equal to...
i != j is true
k != j is false
Relational operators often are used with conditional operators to construct more complex decision-making expressions. The Java programming language supports six conditional operators -five binary and one unary -shown in Table 10 (page 84). One such operator is && , which performs the conditional AND operation. You can use two different relational operators along with && to determine whether both relationships are true . The following line of code uses this technique to determine whether an array index is between two boundaries. It determines whether the index is both greater than or equal to 0 and less than NUM_ENTRIES , which is a previously defined constant value. Table 10. Conditional Operators
<=
index && index < NUM_ENTRIES
Note that in some instances, the second operand to a conditional operator may not be evaluated. Consider this code segment: (numChars < LIMIT) && (...) The && operator will return true only if both operands are true . So, if numChars is greater than or equal to LIMIT , the left-hand operand for && is false , and the return value of && can be determined without evaluating the right-hand operand. In such a case, the interpreter will not evaluate the right-hand operand. This has important implications if the right-hand operand has side effects, such as reading from a stream, updating a value, or making a calculation.
When both operands are boolean, the operator
&
performs the same operation as
&&
. However,
&
always evaluates both of its operands and returns
true
if both are
true
. Likewise, when the operands are boolean,
performs the same operation as is similar to
. The
operator always evaluates both of its operands and returns
true
if at least one of its operands is
true
. When their operands are numbers,
&
and
perform bitwise manipulations. The
Shift and Bitwise OperatorsA shift operator performs bit manipulation on data by shifting the bits of its first operand right or left. Table 11 summarizes the shift operators available in the Java programming language. Table 11. Shift Operators
Each operator shifts the bits of the left-hand operand over by the number of
13 >> 1; The binary representation of the number 13 is 1101. The result of the shift operation is 1101 shifted to the right by one position -110, or 6 in decimal. The right-hand bits are filled with 0s as needed. Table 12 shows the four operators the Java programming language provides to perform bitwise functions on their operands. Table 12. Bitwise Operators
When its operands are numbers, the & operation performs the bitwise AND function on each parallel pair of bits in each operand. The AND function sets the resulting bit to 1 if the corresponding bit in both operands is 1, as shown in Table 13. Table 13. Bitwise AND ( op1 & op2 )
Suppose that you were to AND the values 13 and 12, like this: 13 & 12 . The result of this operation is 12 because the binary representation of 12 is 1100, and the binary representation of 13 is 1101. 1101 // 13 & 1100 // 12 - - - - - - 1100 // 12
If both operand bits are 1, the
AND
function sets the resulting bit to 1;
When both of its operands are numbers, the operator performs the inclusive or operation, and ^ performs the exclusive or ( XOR ) operation. Inclusive or means that if either of the two bits is 1, the result is 1. Table 14 shows the results of an inclusive or operation. Table 14. Bitwise Inclusive Or ( op1 op2 )
Table 15. Bitwise Exclusive Or ( op1 ^ op2 )
Exclusive or means that if the two operand bits are different, the result is 1; otherwise, the result is 0. Table 15 shows the results of an exclusive or operation. And finally, the complement operator ( ~ ) inverts the value of each bit of the operand: If the operand bit is 1, the result is 0; if the operand bit is 0, the result is 1. For example, ~ 1011 (11) is 0100 (4)
Among other things, bitwise manipulations are useful for managing sets of boolean flags. Suppose, for example, that your program had several boolean flags that indicated the state of various
First, set up constants that
static final int VISIBLE = 1; static final int DRAGGABLE = 2; static final int SELECTABLE = 4; static final int EDITABLE = 8; int flags = 0; To set the visible flag when something became visible, you would use this statement: flags = flags VISIBLE; To test for visibility, you could then write:
if ((flags & VISIBLE) == VISIBLE) {
...
}
public class BitwiseDemo {
static final int VISIBLE = 1;
static final int DRAGGABLE = 2;
static final int SELECTABLE = 4;
static final int EDITABLE = 8;
public static void main(String[] args) {
int flags = 0;
flags = flags VISIBLE;
flags = flags DRAGGABLE;
if ((flags & VISIBLE) == VISIBLE) {
if ((flags & DRAGGABLE) == DRAGGABLE) {
System.out.println("Flags are Visible and Draggable.");
}
}
flags = flags EDITABLE;
if ((flags & EDITABLE) == EDITABLE) {
System.out.println("Flags are now also Editable.");
}
}
}
Here's the output from this program: Flags are Visible and Draggable. Flags are now also Editable. Assignment Operators
You use the basic assignment operator,
=
, to assign one value to another. The
MaxVariablesDemo
program uses
=
to initialize all its local
// integers byte largestByte = Byte.MAX_VALUE; short largestShort = Short.MAX_VALUE; int largestInteger = Integer.MAX_VALUE; long largestLong = Long.MAX_VALUE; // real numbers float largestFloat = Float.MAX_VALUE; double largestDouble = Double.MAX_VALUE; // other primitive types char aChar = 'S'; boolean aBoolean = true; The Java programming language also provides several shortcut assignment operators that allow you to perform an arithmetic, shift, or bitwise operation and an assignment operation all with one operator. Suppose that you wanted to add a number to a variable and assign the result back into the variable, like this: i = i + 2; You can shorten this statement by using the shortcut operator +=, like this: i += 2; The two previous lines of code are equivalent. Table 16 lists the shortcut assignment operators and their lengthy equivalents. Table 16. Shortcut Assignment Operators
Other Operators
The Java programming language also supports the operators in Table 17. These operators are covered in other
Table 17. Other Operators
Summary of OperatorsTable 18 lists all the operators supported by the Java programming language. Table 18. All the Operators
Questions and Exercise: OperatorsQuestions
Exercises
AnswersYou can find answers to these Questions and Exercises online: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/QandE/answers_operators.html |