In Java, operators have different levels of precedence, which determines the order in which they are evaluated in an expression. Here's a general overview of operator precedence in Java, listed from highest to lowest precedence:
1. **Postfix operators:**
- `expr++` (Post-increment)
- `expr--` (Post-decrement)
2. **Unary operators:**
- `++expr` (Pre-increment)
- `--expr` (Pre-decrement)
- `+expr` (Unary plus)
- `-expr` (Unary minus)
- `!expr` (Logical NOT)
- `~expr` (Bitwise NOT)
- `(type) expr` (Type cast)
3. **Multiplicative operators:**
- `*` (Multiplication)
- `/` (Division)
- `%` (Modulus)
4. **Additive operators:**
- `+` (Addition)
- `-` (Subtraction)
5. **Shift operators:**
- `<<` (Left shift)
- `>>` (Right shift with sign extension)
- `>>>` (Right shift with zero extension)
6. **Relational operators:**
- `<` (Less than)
- `>` (Greater than)
- `<=` (Less than or equal to)
- `>=` (Greater than or equal to)
- `instanceof` (Type comparison)
7. **Equality operators:**
- `==` (Equal to)
- `!=` (Not equal to)
8. **Bitwise AND:**
- `&`
9. **Bitwise XOR:**
- `^`
10. **Bitwise OR:**
- `|`
11. **Logical AND:**
- `&&`
12. **Logical OR:**
- `||`
13. **Conditional (Ternary) operator:**
- `? :`
14. **Assignment operators:**
- `=`
- `+=`
- `-=`
- `*=`
- `/=`
- `%=`
- `&=`
- `^=`
- `|=`
- `<<=`
- `>>=`
- `>>>=`
Operators with higher precedence are evaluated before those with lower precedence. Parentheses `( )` can be used to override the default precedence and explicitly specify the order of evaluation. For example, expressions inside parentheses are always evaluated first.
Understanding operator precedence is important for writing correct and predictable expressions in Java.
No comments:
Post a Comment