Operator Precedence in Java

 

✅ Operator Precedence in Java

Operator precedence determines the order in which operators are evaluated in expressions. Operators with higher precedence are evaluated before operators with lower precedence. If operators have the same precedence, their associativity (left-to-right or right-to-left) determines the order.


🔹 Table of Java Operator Precedence and Associativity

Precedence LevelOperatorsDescriptionAssociativity
1 (Highest)()Parentheses (grouping)Left to right
[], ., obj.method(), a[i], x.yArray/member access, method callLeft to right
2++, --, + (unary), - (unary), ~, !Unary operatorsRight to left
3*, /, %MultiplicativeLeft to right
4+, -AdditiveLeft to right
5<<, >>, >>>Bitwise shiftLeft to right
6<, <=, >, >=, instanceofRelationalLeft to right
7==, !=EqualityLeft to right
8&Bitwise ANDLeft to right
9^Bitwise XORLeft to right
10``Bitwise OR
11&&Logical ANDLeft to right
12``
13? :Ternary conditionalRight to left
14=, +=, -=, *=, /=, %=Assignment and compound assignmentRight to left
&=, `=, ^=, <<=, >>=, >>>=`
15 (Lowest)->, ::Lambda expressions, method reference

🔹 Example Illustrating Precedence


int a = 10, b = 5, c = 2; int result = a + b * c; // result = 10 + (5 * 2) = 20

👉 Multiplication (*) has higher precedence than addition (+), so it's done first.


🔹 Using Parentheses for Clarity

To override precedence and make expressions easier to read, use parentheses:


int result = (a + b) * c; // Now result = (10 + 5) * 2 = 30

🔹 Logical Precedence Example


boolean res = true || false && false; // AND has higher precedence → evaluated as: true || (false && false) → true

Comments

Popular posts from this blog

Object Oriented Programming PBCST 304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Object Oriented Programming PBCST 304 Course Details and Syllabus

Type casting in Java