Home / Programs / Associativity and precedence in operators example in java
Programming Example

Associativity and precedence in operators example in java

👁 4,527 Views
💻 Practical Program
📘 Step by Step Learning
Associativity and precedence in operators example in java

Program Code

/*
 * Here we will see the effect of precedence in operators life
 */
public class OperatorAssociativityExample {

 public static void main(String args[]) {
 int i = 40;
 int j = 80;
 int k = 40;

 int l = i / k * 2 + j;
 /*
 * In above calculation we are not using any bracket. And there are two
 * operator of same precedence(divion and multiplication) so which
 * operator(/ or *) will be evaluated first is decided by association.
 * Associativity of * & / is left to right. So divison will be evaluated
 * first then multiplication.
 *
 * So the output will be 82.
 */

 System.out.println("value of L :" + l);

 int m = i / (k * 2) + j;
 /*
 * In above calculation brackets are used so associativity will not come
 * in picture and multiply(*) will be evaluated first and then
 * divison()/. So output will be 80
 */

 System.out.println("Value of M:" + m);
 }

}

Output

value of L :82
Value of M:80
Press any key to continue . . .

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.