Java Operators – Complete Guide with Types, Examples, and Usage
Learn all types of Java operators including arithmetic, relational, logical, bitwise, assignment, and ternary operators with detailed examples and use cases.
Operators in Java – Complete Detailed Tutorial
Operators in Java are special symbols that perform operations on variables and values. Understanding operators is essential for performing mathematical calculations, comparisons, and logical operations in Java programs.
1. Types of Operators in Java
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Unary Operators
- Ternary Operator
- Shift Operators
- Instanceof Operator
2. Arithmetic Operators
- Used to perform mathematical operations.
- Symbols:
+ - * / %
| OperatorDescriptionExample | ||
| + | Addition | 5 + 3 = 8 |
| - | Subtraction | 5 - 3 = 2 |
| * | Multiplication | 5 * 3 = 15 |
| / | Division | 10 / 3 = 3 |
| % | Modulus (Remainder) | 10 % 3 = 1 |
Example:
3. Relational Operators
- Used to compare two values
- Return boolean (
trueorfalse)
| OperatorDescriptionExample | ||
| == | Equal to | 5 == 5 → true |
| != | Not equal to | 5 != 3 → true |
| > | Greater than | 5 > 3 → true |
| < | Less than | 5 < 3 → false |
| >= | Greater than or equal to | 5 >= 5 → true |
| <= | Less than or equal to | 3 <= 5 → true |
Example:
4. Logical Operators
- Used to combine multiple boolean expressions
| OperatorDescriptionExample | ||
| && | Logical AND | (x > 5 && y < 30) |
| || | Logical OR | `(x > 5 |
| ! | Logical NOT | !(x > y) |
Example:
5. Bitwise Operators
- Operate on binary bits of numbers
| OperatorDescriptionExample | ||
| & | AND | 5 & 3 → 1 |
| | | OR | 5 | 3 → 7 |
| ^ | XOR | 5 ^ 3 → 6 |
| ~ | Complement | ~5 → -6 |
| << | Left shift | 5 << 1 → 10 |
| >> | Right shift | 10 >> 1 → 5 |
| >>> | Zero-fill right shift | -5 >>> 1 → 2147483645 |
Example:
6. Assignment Operators
- Used to assign values to variables
| OperatorDescriptionExample | ||
| = | Assign | x = 5 |
| += | Add & assign | x += 5 → x = x + 5 |
| -= | Subtract & assign | x -= 3 → x = x - 3 |
| *= | Multiply & assign | x *= 2 → x = x * 2 |
| /= | Divide & assign | x /= 2 → x = x / 2 |
| %= | Modulus & assign | x %= 3 → x = x % 3 |
Example:
7. Unary Operators
- Operate on a single operand
| OperatorDescriptionExample | ||
| + | Positive | +a |
| - | Negative | -a |
| ++ | Increment | a++ / ++a |
| -- | Decrement | a-- / --a |
| ! | Logical NOT | !true → false |
Example:
8. Ternary Operator
- Short form of
if-else - Syntax:
Example:
9. instanceof Operator
- Checks object type
- Returns boolean
Example:
10. Example Program Using Multiple Operators
Output:
11. Summary
- Operators are special symbols for operations
- Categories: Arithmetic, Relational, Logical, Bitwise, Assignment, Unary, Ternary, instanceof
- Essential for calculations, comparisons, and decision-making