CodeNewbie Community 🌱

Cover image for Associativity and Precedence of Operators explained in simple way
Prathmesh
Prathmesh

Posted on

Associativity and Precedence of Operators explained in simple way

Precedence meaning - the right that somebody/something has to come before somebody/something else because he/she/it is more important. definition comes when you google it.

Precedence in Java means the operators are applied and evaluated based on precedence. for example (+,-) has less procedure compared to (*,!). hence * & / are calculated first.

In case if you want to change this order, you can use parenthesis.

In Java the original common BODMAS Rule doesn't work instead precedence and associativity works. when precedence of is same like * and / then associativity works.

B – Brackets
O – Order of powers or roots,
D – Division
M – Multiplication
A – Addition
S – Subtraction.

The BODMAS rule state that mathematical operations need to be solved from left to right in the order of BODMAS.

Whenever you start working on solving operators problem, first check the operators who has highest precedence value and then start solving but if you encounter operators which has same precedence value than check the associativity rule then start solving.

Source: codeharry

Associativity tells the direction of the execution of operators. It can either be left to right or vice versa.

    / * -> Left to Right

    + - -> Left to Right

    ++, = -> Right to Left
Enter fullscreen mode Exit fullscreen mode
int a = 7*5-34/2;

         /* calculation
         =35-34/2
          =35-17
       output   =18 */
Enter fullscreen mode Exit fullscreen mode

Latest comments (3)

Collapse
 
larrymartin1job profile image
Larry Martin

Clear and concise explanation! Understanding operator precedence and associativity is crucial for mastering Java. Thanks for simplifying it.
Best Roof Inspection Services in New York

Collapse
 
charlesmichaelvaughn profile image
Charles Michael Vaughn

good image, i am charles michael vaughn from states

Collapse
 
iampratley profile image
Prathmesh

Thanks, i am Prathmesh from Indus valley :)