Operators

Operators lists the operators of the Java language, along with their precedence, operand types, and associativity.

Java Operators
Prec. Operator Operand Type(s) Assoc. Operation Performed
++ arithmetic R pre-or-post increment (unary)
-- arithmetic R pre-or-post decrement (unary)
+, - arithmetic R unary plus, unary minus
~ integral R bitwise complement (unary)
! boolean R logical complement (unary)
(type) any R cast
*, /, % arithmetic L multiplication, division, remainder
+, - arithmetic L addition, subtraction
+ string L string concatenation
<< integral L left shift
>> integral L right shift with sign extension
>>> integral L right shift with zero extension
<, <= arithmetic L less than, less than or equal
>, >= arithmetic L greater than, greater than or equal
instanceof object, type L type comparison
== primitive L equal (have identical values)
!= primitive L not equal (have different values)
== object L equal (refer to same object)
!= object L not equal (refer to different objects)
& integral L bitwise AND
& boolean L boolean AND
^ integral L bitwise XOR
^ boolean L boolean XOR
| integral L bitwise OR
| boolean L boolean OR
&& boolean L conditional AND
|| boolean L conditional OR
?: boolean, any, any R conditional (ternary) operator
= variable, any R assignment
*=, /=, %=, +=, -=, <<=, >>=, >>>=, &=, ^=, |= variable, any R assignment with operation

Operator precedence controls the order in which operations are performed. Consider the following example:

w = x + y * z; 

The multiplication operator * has a higher precedence than the addition operator +, so the multiplication is performed before the addition. Furthermore, the assignment operator = has the lowest precedence of any operator, so the assignment is done after all the operations on the right-hand side are performed. Operators with the same precedence (like addition and subtraction) are performed in order according to their associativity (usually left-to-right). Operator precedence can be overridden with the explicit use of parentheses. For example:

w = (x + y) * z; 

The associativity of an operator specifies the order that operations of the same precedence are performed in. In Table 13.3 a value of L specifies left-to-right associativity, and a value of R specifies right-to-left associativity. Left-to-right associativity means that operations are performed left-to-right. For example:

w = x + y + z; 

is the same as:

w = ((x + y) + z); 

because the addition operator has left-to-right associativity. On the other hand, the following expressions:

x = ~-~y; q = a?b:c?d:e?f:g; 

are equivalent to:

x = ~(-(~y)); q = a?b:(c?d:(e?f:g)); 

because the unary operators and the ternary conditional ?: operator have right-to-left associativity.

Java operators are basically identical to C operators, except for these differences: