Java provides a rich set of operators for manipulating program data. Most of these were taken directly from C/C++, but you must be careful because there are some significant differences to keep in mind. In this tutorial we will cover the most commonly used operators.
| Java Operators | |
|---|---|
| postfix | [] . () expr++ expr-- |
| unary | ++expr --expr +expr -expr ! ~ |
| creation/caste | new (type)expr |
| multiplicative | * / % |
| additive | + - |
| shift | << >> >>> |
| relational | < <= > >= instanceof |
| equality | == != |
| bitwise AND | & |
| bitwise exclusive OR | ^ |
| bitwise inclusive OR | | |
| logical AND | && |
| logical OR | || |
| ternary | ?: |
| assignment | = "op=" |
| Operators are listed in precedence or derwith the highest precedence at the top of the table. | |
Evaluation Order
In Java, the order of evaluation of operands in an expression is fixed. All operands are evaluated from left to right. The order of execution of the operations may be completely different. For example:
Assignment
Assignment operators set the value of a variable or expression to some new value. The simple = operator sets the lefthand operand to the value of the righthand operand. If the operands are object references, then a copy of the reference value will be assigned--not the object body. The assignment operator is evaluated from right to left, so a = b = c = 0; would assign 0 to c, then c to b then b to a.
Arithmetic
/ + - represent division, addition, and subtraction, as in standard math notation. * represents multiplication and % represents modulo. All of these are self-explanatory except the modulo operator. % is similar to division but returns the remainder of the division operation. For example, z = 5 % 2;, z would be 1. In other words, 5 / 2 is 2 with a remainder of 1.
One other note about the division operator: Make sure you always avoid division by 0 or else you will have an ArithmeticException thrown.
Comparison
The comparison operators return true or false boolean values. These are most often used in control flow statements such as if(), while(), and for() to determine if certain lines of code should be executed.
In the next Java Operators tutorial, we will cover the advanced operators including: instanceof, shift, unary, ternary, bitwise, short-circuit, and "op=".