Table of Contents
The Java operators are based on those of C/C++, with some additions and modifications.
The Java Operators
Here are the operators in Java.
The precedence and associativity are essentially the same as in C/C++.
| Precedence | Operator | Operand Types | Associativity | Operation |
|---|---|---|---|---|
| 1 (Highest) | ++ — + – ~ ! (type) | arithmetic arithmetic arithmetic arithmetic integral boolean any | Right-to-Left | pre- or post- increment pre- or post- decrement unary plus unary minus bitwise complement (unary) logical complement (unary) cast |
| 2 | * / % | arithmetic arithmetic arithmetic | Left-to-Right | multiplication division remainder (modulus) |
| 3 | + – + | arithmetic arithmetic string | Left-to-Right | addition subtraction string concatenation |
| 4 | << >> >>> | integral integral integral | Left-to-Right | left shift right shift with sign extension right shift with zero extension |
| 5 | < <= > >= instanceof | arithmetic arithmetic arithmetic arithmetic object, type | Left-to-Right | less than less then or equal greater than greater than or equal type comparison |
| 6 | == != == != | primitive primitive object object | Left-to-Right | equal (have identical values) not equal (have different values) equal (refer to same obect) not equal (refer to different objects) |
| 7 | & & | integral boolean | Left-to-Right | bitwise AND boolean AND |
| 8 | ^ ^ | integral boolean | Left-to-Right | bitwise XOR boolean XOR |
| 9 | | | | integral boolean | Left-to-Right | bitwise OR boolean OR |
| 10 | && | boolean | Left-to-Right | conditional AND |
| 11 | || | boolean | Left-to-Right | conditional OR |
| 12 | ?: | boolean, any, any | Right-to-Left | conditional (ternary) operator |
| 13 (Lowest) | = *= /= %= += -= <<= >>= >>>= &= ^= |= | variable, any | Right-to-Left | assignment assignment with operation |
Differences from C/C++
Here are some ways in which Java operators differ from those of C and C++:
| Java | C & C++ | Comments |
|---|---|---|
| No comma operator | Support comma operator | Java’s for statement supports a useful syntax, as in C/C++ |
| No reference or dereference operators (*, -> and &) | Support reference and dereference operators. | Java has no pointers. |
| No sizeof operator | Support sizeof operator | Java doesn’t need it for portability |
| Doesn’t consider [] and . to be operators | Consider [] and . to be operators | |
| The + operator applied to Strings concatenates them. | In Java, conversion is performed automatically for primitive types, and by calling the toString() method for non-primitive types. | |
| Supports instanceof operator | C++ has typeid operator | Tests whether an object is an instance of a class or whether it implements an interface. |
| Supports >>> operator | Right-shifts with zero extension. | |
| Supports variety of &, | and ^ operators, depending on operand type. | Operators perform bitwise operations on integral values, but boolean operations on boolean values. |
