Operator Precedence in Java
What is Operator Precedence in Java ?
Here, in this page we will discuss about the operator Precedence in Java. Java provides quite a variety of operators which come in handy to the programmer for the manipulation of variables.
Operator Precedence is defined by how two operators are bind together and how they will be evaluated. Operator with more precedence will be evaluated first in an expression.
Java Operator Precedence
The operators in java are as follows:
- Arithmetic Operators
- Relational Operators
- Bit-wise Operators
- Logical Operators
- Assignment Operators
- Miscellaneous Operators
For example x = 10 – 4 * 2, here the value of x will be 2 not 12 as * (Multiplication) has more precedence over -, so it will be evaluated first which gives 8, then 8 will be subtracted from 10 which gives our final answer 2.
Precedence And Associativity in Java :
Precedence | Operator | Type | Associativity |
---|---|---|---|
15 | () [] · | Parentheses Array subscript Member selection | Left to Right |
14 | ++ — | Unary post-increment Unary post-decrement | Left to Right |
13 | ++ — + – ! ~ ( type ) | Unary pre-increment Unary pre-decrement Unary plus Unary minus Unary logical negation Unary bitwise complement Unary type cast | Right to left |
12 | * / % | Multiplication Division Modulus | Left to right |
11 | + – | Addition Subtraction | Left to right |
10 | << >> >>> | Bitwise left shift Bitwise right shift with sign extension Bitwise right shift with zero extension | Left to right |
9 | < <= > >= instanceof | Relational less than Relational less than or equal Relational greater than Relational greater than or equal Type comparison (objects only) | Left to right |
8 | == != | Relational is equal to Relational is not equal to | Left to right |
7 | & | Bitwise AND | Left to right |
6 | ^ | Bitwise exclusive OR | Left to right |
5 | | | Bitwise inclusive OR | Left to right |
4 | && | Logical AND | Left to right |
3 | || | Logical OR | Left to right |
2 | ? : | Ternary conditional | Right to left |
1 | = += -= *= /= %= | Assignment Addition assignment Subtraction assignment Multiplication assignment Division assignment Modulus assignment | Right to left |
Example :
import java.util.*; public class Main{ public static void main(String[] args){ // Initializing the variables int a = 10; int b = 20; int c = 30; int d = 60; int e; //10 + 600 e = a + b * c; System.out.println(e); //30 * 30 e = (a + b) * c; System.out.println(e); //30 * 2 e = (a + b) * (d / c); System.out.println(e); } }
Output: 610 900 60
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment