Operator precedence in java determines in which order the arithmetic operators in an expression are evaluated.
Before you start reading this article, you should have a basic knowledge about Java Operators.
Operator Precedence in Java
Now look at this java program:
int myInt = 12 - 4 * 2;
What will be the value of myInt? Will it be (12 - 4)*2, that is, 16? Or it will be 12 - (4 * 2), that is, 4?
When two operators share a common operand, 4 in this case, the operator with the highest precedence is operated first.
In Java, the precedence of * is higher than that of -. Hence, the multiplication is performed before subtraction, and the value of myInt will be 4.
The Operator Precedence Table
The table below lists the precedence of operators in Java; higher it appears in the table, the higher is its precedence.
Operators | Precedence |
---|---|
postfix increment and decrement | ++ -- |
prefix increment and decrement, and unary | ++ -- + - ~ ! |
multiplicative | * / % |
additive | + - |
shift | << >> >>> |
relational | < > <= >= instanceof |
equality | == != |
bitwise AND | & |
bitwise exclusive OR | ^ |
bitwise inclusive OR | | |
logical AND | && |
logical OR | || |
ternary | ? : |
assignment | = += -= *= /= %= &= ^= |= <<= >>= >>>= |
Example: Operator Precedence
public class Precedence
{
public static void main(String[] args)
{
int a = 10, b = 5, c = 1, result;
result = a-++c-++b;
System.out.println(result);
}
}
Output:
2
The operator precedence of prefix ++ is higher than that of - subtraction operator. Hence,
result = a-++c-++b;
is equivalent to:
result = a-(++c)-(++b);
When dealing with multiple operators and operands in a single expression, you can use parentheses like in the above example for clarity. The expression inside the parentheses is evaluated first.
If you have any doubts or questions, please let me know.