An operator performs a function on one, two, or three operands. An operator that requires one operand is called a unary operator. For example, ++ is a unary operator that increments the value of its operand by 1. An operator that requires two operands is a binary operator. For example, = is a binary operator that assigns the value from its righthand operand to its lefthand operand. And finally, a ternary operator is one that requires three operands. The Java programming language has one ternary operator, ?:, which is a shorthand ifelse statement.
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 infix notation, which means that the operator appears between its operands:
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 numbersthe result of the arithmetic operation. The data type returned by an arithmetic operator depends on the type of its operands: If you add two integers, you get an integer back. An operation is said to evaluate to its result.
We divide the operators into these categories:
Arithmetic Operators
The Java programming language supports various arithmetic operators for all floatingpoint and integer numbers. These operators are + (addition),  (subtraction), * (multiplication), / (division), and % (modulo). Table 5 summarizes the binary arithmetic operations in the Java programming language.
Operator 
Use 
Description 

+ 
op1 + op2 
Adds op1 and op2; also used to concatenate strings 
 
op1  op2 
Subtracts op2 from op1 
* 
op1 * op2 
Multiplies op1 by op2 
/ 
op1 / op2 
Divides op1 by op2 
% 
op1 % op2 
Computes the remainder of dividing op1 by op2 
Here's an example program, ArithmeticDemo, [1] that defines two integers and two doubleprecision floatingpoint numbers and uses the five arithmetic operators to perform different arithmetic operations. This program also uses + to concatenate strings. The arithmetic operations are shown in boldface:

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 floatingpoint number are used as operands to a single arithmetic operation, the result is floating point. The integer is implicitly converted to a floatingpoint 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.
Data Type of Result 
Data Type of Operands 

long 
Neither operand is a float or a double (integer arithmetic); at least one operand is a long. 
int 
Neither operand is a float or a double (integer arithmetic); neither operand is a long. 
double 
At least one operand is a double. 
float 
At least one operand is a float; neither operand is a double. 
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.
Operator 
Use 
Description 

+ 
+op 
Promotes op to int if it's a byte, short, or char 
 
op 
Arithmetically negates op 
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, evaluates to the value of the operand after the increment/decrement operation. The postfix version, op++/op, evaluates to the value of the operand before the increment/decrement operation.
The following program, called SortDemo, [1] uses ++ twice and  once.

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 arraya fixedlength structure that can hold multiple values of the same typethen 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 lowest to highest:
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 loops. Here's the statement that controls the outer loop:
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.
Operator 
Use 
Description 

++ 
op++ 
Increments op by 1; evaluates to the value of op before it was incremented 
++ 
++op 
Increments op by 1; evaluates to the value of op after it was incremented 
 
op 
Decrements op by 1; evaluates to the value of op before it was decremented 
 
op 
Decrements op by 1; evaluates to the value of op after it was decremented 
Relational and Conditional Operators
A relational operator compares two values and determines the relationship between them. For example, != returns true if its two operands are unequal. Table 9 summarizes the relational operators.
Operator 
Use 
Description 

> 
op1 > op2 
Returns true if op1 is greater than op2 
>= 
op1 >= op2 
Returns true if op1 is greater than or equal to op2 
< 
op1 < op2 
Returns true if op1 is less than op2 
<= 
op1 <= op2 
Returns true if op1 is less than or equal to op2 
== 
op1 == op2 
Returns true if op1 and op2 are equal 
!= 
op1 != op2 
Returns true if op1 and op2 are not equal 
Following is an example, RelationalDemo, [1] that defines three integer numbers and uses the relational operators to compare them:

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 decisionmaking expressions. The Java programming language supports six conditional operatorsfive binary and one unaryshown 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.
Operator 
Use 
Description 

&& 
op1 && op2 
Returns true if op1 and op2 are both true; conditionally evaluates op2 
 
op1  op2 
Returns true if either op1 or op2 is true; conditionally evaluates op2 
! 
!op 
Returns true if op is false 
& 
op1 & op2 
Returns true if op1 and op2 are both boolean and both true; always evaluates op1 and op2 If both operands are numbers, performs bitwise AND operation 
 
op1  op2 
Returns true if both op1 and op2 are boolean, and either op1 or op2 is true; always evaluates op1 and op2 If both operands are numbers, performs bitwise inclusive OR operation 
^ 
op1 ^ op2 
Returns true if op1 and op2 are different, that is, if one or the other of the operands, but not both, is true 
0 <= 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 lefthand operand for && is false, and the return value of && can be determined without evaluating the righthand operand. In such a case, the interpreter will not evaluate the righthand operand. This has important implications if the righthand 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 next section, Shift and Bitwise Operators (page 85), has more information.
Shift and Bitwise Operators
A 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.
Operator 
Use 
Description 

<< 
op1 << op2 
Shift bits of op1 left by distance op2; fills with zero bits on the righthand side 
>> 
op1 >> op2 
Shift bits of op1 right by distance op2; fills with highest (sign) bit on the lefthand side 
>>> 
op1 >>> op2 
Shift bits of op1 right by distance op2; fills with zero bits on the lefthand side 
Each operator shifts the bits of the lefthand operand over by the number of positions indicated by the righthand operand. The shift occurs in the direction indicated by the operator itself. For example, the following statement shifts the bits of the integer 13 to the right by one position:
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 position110, or 6 in decimal. The righthand 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.
Operator 
Use 
Description 

& 
op1 & op2 
Bitwise AND, if both operands are numbers Conditional AND, if both operands are boolean 
 
op1  op2 
Bitwise inclusive OR, if both operands are numbers Conditional OR, if both operands are boolean 
^ 
op1 ^ op2 
Bitwise exclusive OR (XOR) 
~ 
~op2 
Bitwise complement 
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.
Bit in op1 
Corresponding Bit in op2 
Result 

0 
0 
0 
0 
1 
0 
1 
0 
0 
1 
1 
1 
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; otherwise, the resulting bit is 0. So, when you line up the two operands and perform the AND function, you can see that the two highorder bits (the two bits farthest to the left of each number) of each operand are 1. Thus, the resulting bit in the result is also 1. The loworder bits evaluate to 0 because either one or both bits in the operands are 0.
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.
Bit in op1 
Corresponding Bit in op2 
Result 

0 
0 
0 
0 
1 
1 
1 
0 
1 
1 
1 
1 
Bit in op1 
Corresponding Bit in op2 
Result 

0 
0 
0 
0 
1 
1 
1 
0 
1 
1 
1 
0 
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 components in your program: is it visible, is it draggable, and so on. Rather than define a separate boolean variable to hold each flag, you could define a single variable, flags, for all of them. Each bit within flags would represent the current state of one of the flags. You would then use bit manipulations to set and to get each flag.
First, set up constants that indicate the various flags for your program. These flags should each be a different power of 2 to ensure that each bit is used by only one flag. Define a variable, flags, whose bits would be set according to the current state of each flag. The following code sample initializes flags to 0, which means that all flags are false (none of the bits are set):
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) { ... }
Here's the complete program, BitwiseDemo, [1] that includes this code:

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 variables:
// 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.
Operator 
Use 
Equivalent to 


Arithmetic Shortcuts 
+= 
op1 += op2 
op1 = op1 + op2 
= 
op1 = op2 
op1 = op1  op2 

*= 
op1 *= op2 
op1 = op1 * op2 

/= 
op1 /= op2 
op1 = op1 / op2 

%= 
op1 %= op2 
op1 = op1 % op2 

Bitwise Shortcuts 
&= 
op1 &= op2 
op1 = op1 & op2 
= 
op1 = op2 
op1 = op1  op2 

^= 
op1 ^= op2 
op1 = op1 ^ op2 

Shift Shortcuts 
<<= 
op1 <<= op2 
op1 = op1 << op2 
>>= 
op1 >>= op2 
op1 = op1 >> op2 

>>>= 
op1 >>>= op2 
op1 = op1 >>> op2 
Other Operators
The Java programming language also supports the operators in Table 17. These operators are covered in other parts of this book.
Operator 
Description 

?: 
Shortcut ifelse statement The ifelse Statements (page 102) 
[] 
Used to declare arrays, to create arrays, and to access array elements Creating and Using Arrays (page 165) 
. 
Used to form qualified names Using Objects (page 126) 
(params ) 
Delimits a commaseparated list of parameters Defining Methods (page 182) 
(type ) 
Casts (converts) a value to the specified type 
new 
Creates a new object or array Creating Objects (page 122) and Creating and Using Arrays (page 165) 
instanceof 
Determines whether its first operand is an instance of its second operand 
Summary of Operators
Table 18 lists all the operators supported by the Java programming language.
Operator 
Use 
Description 

+ 
op1 + op2 
Adds op1 and op2; also used to concatenate strings 
+ 
+op 
Promotes op to int if it's a byte, short, or char 
 
op1  op2 
Subtracts op2 from op1 
 
op 
Arithmetically negates op 
* 
op1 * op2 
Multiplies op1 by op2 
/ 
op1 / op2 
Divides op1 by op2 
% 
op1 % op2 
Computes the remainder of dividing op1 by op2 
++ 
op++ 
Increments op by 1; evaluates to the value of op before it was incremented 
++ 
++op 
Increments op by 1; evaluates to the value of op after it was incremented 
 
op 
Decrements op by 1; evaluates to the value of op before it was decremented 
 
op 
Decrements op by 1; evaluates to the value of op after it was decremented 
> 
op1 > op2 
Returns true if op1 is greater than op2 
>= 
op1 >= op2 
Returns true if op1 is greater than or equal to op2 
< 
op1 < op2 
Returns true if op1 is less than op2 
<= 
op1 <= op2 
Returns true if op1 is less than or equal to op2 
== 
op1 == op2 
Returns true if op1 and op2 are equal 
!= 
op1 != op2 
Returns true if op1 and op2 are not equal 
&& 
op1 && op2 
Returns true if op1 and op2 are both true; conditionally evaluates op2 
 
op1  op2 
Returns true if either op1 or op2 is true; conditionally evaluates op2 
! 
!op 
Returns true if op is false 
& 
op1 & op2 
Returns true if op1 and op2 are both boolean and both true; always evaluates op1 and op2 
 
op1  op2 
Returns true if both op1 and op2 are boolean, and either op1 or op2 is true; always evaluates op1 and op2 
^ 
op1 ^ op2 
Returns true if op1 and op2 are different, that is, if one, but not both, of the operands is true 
>> 
op1 >> op2 
Shift bits of op1 right by distance op2; fills with zero bits on the righthand side 
<< 
op1 
Shift bits of op1 left by distance op2; fills with the highest (sign) bit on the lefthand side 
>>> 
op1 >>> op2 
Shift bits of op1 right by distance op2; fills with zero bits on the lefthand side 
& 
op1 & op2 
Bitwise AND, if both operands are numbers Logical AND, if both operands are boolean 
 
op1  op2 
Bitwise OR, if both operands are numbers Logical OR, if both operands are boolean 
^ 
op1 ^ op2 
Bitwise XOR 
~ 
~op2 
Bitwise complement 
= 
op1 = op2 
Assigns the value of op2 to op1 
+= 
op1 += op2 
Equivalent to op1 = op1 + op2 
= 
op1 = op2 
Equivalent to op1 = op1  op2 
*= 
op1 *= op2 
Equivalent to op1 = op1 * op2 
/= 
op1 /= op2 
Equivalent to op1 = op1 / op2 
%= 
op1 %= op2 
Equivalent to op1 = op1 % op2 
&= 
op1 &= op2 
Equivalent to op1 = op1 & op2 
= 
op1 = op2 
Equivalent to op1 = op1  op2 
^= 
op1 ^= op2 
Equivalent to op1 = op1 ^ op2 
<<= 
op1 <<= op2 
Equivalent to op1 = op1 << op2 
>>= 
op1 >>= op2 
Equivalent to op1 = op1 >> op2 
>>>= 
op1 >>>= op2 
Equivalent to op1 = op1 >>> op2 
?: 
op1 ? op2 : op3 
If op1 is true, returns op2; otherwise, returns op3 
[] 
Used to declare arrays, to create arrays, and to access array elements. Creating and Using Arrays (page 165) 

. 
Used to form long names. Using Objects (page 126) 

(params ) 
Delimits a commaseparated list of parameters. Defining Methods (page 182) 

(type ) 
Casts (converts) a value to the specified type. 

new 
Creates a new object or array. Creating Objects (page 122) and Creating and Using Arrays (page 165) 

instanceof 
op1 instanceof op2 
Returns true if op1 is an instance of op2 
Questions and Exercise: Operators
Questions
1: 
Consider the following code snippet: arrayOfInts[j] > arrayOfInts[j+1] What operators does the code contain? 
2: 
Consider the following code snippet: int i = 10; int n = i++%5;

3: 

Exercises
1: 
Write a program that tests whether a floatingpoint number is zero. (Hint: You shouldn't generally use the equality operator == with floatingpoint numbers, as floatingpoint numbers by nature are difficult to match exactly. Instead, test whether the number is close to zero.) 
2: 
Write a program that calculates the number of U.S. dollars equivalent to a given number of French francs. Assume an exchange rate of 6.85062 francs per dollar. If you want to control the format of the numbers your program displays, you can use the DecimalFormat class, which is discussed in the section Formatting Numbers with Custom Formats (page 156). 
3: 
Write a program that uses the bits in a single integer to represent the true/false data shown in Figure 44. Figure 44. Bits in a single integer represent the true and false data. Include in the program a variable named status, and have the program print the meaning of status. For example, if status is 1 (only bit 0 is set), the program should print something like this: Ready to receive requests

Answers
You can find answers to these Questions and Exercises online:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/QandE/answers_operators.html
Getting Started
ObjectOriented Programming Concepts
Language Basics
Object Basics and Simple Data Objects
Classes and Inheritance
Interfaces and Packages
Handling Errors Using Exceptions
Threads: Doing Two or More Tasks at Once
I/O: Reading and Writing
User Interfaces That Swing
Appendix A. Common Problems and Their Solutions
Appendix B. InternetReady Applets
Appendix C. Collections
Appendix D. Deprecated Thread Methods
Appendix E. Reference