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

Top comments (2)

Collapse
 
charlesmichaelvaughn profile image
Charles Michael Vaughn

good image, i am charles michael vaughn from states

Collapse
 
iampratley profile image
Prathmesh Author

Thanks, i am Prathmesh from Indus valley :)