Chapter 2- Associativity of Operators in Java



Associativity

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

/ *      L to R

+ -      L to R

++, =      R to L



Quick Quiz: How will you write the following expression in Java?

Code As Described in the Video :

package com.company;
public class cwh_09_ch2_op_pre {
public static void main(String[] args) {
// Precedence & Associativity

//int a = 6*5-34/2;
/*
Highest precedence goes to * and /. They are then evaluated on the basis
of left to right associativity
=30-34/2
=30-17
=13
*/
//int b = 60/5-34*2;
/*
= 12-34*2
=12-68
=-56
*/

//System.out.println(a);
//System.out.println(b);

// Quick Quiz
int x =6;
int y = 1;
// int k = x * y/2;

int b = 0;
int c = 0;
int a = 10;
int k = b*b - (4*a*c)/(2*a);
System.out.println(k);

}
}


Solutions :

1. 
package com.company;     //question have to be x *y/2 ; question is incorrect

public class precedanceAndAssociativity {
public static void main(String[] args) {
int x=6;
int y=1;
int k=x-y*2;
System.out.println(k);
}
}

/*
4
*/


2. 

package com.company;

public class precedanceAndAssociativity {
public static void main(String[] args) {
int a=2;
int b=3;
int c=4;
int k=(b*b-4*a*c)/(2*a);
System.out.println(k);
}
}

/*
-5
*/

3. 
package com.company;

public class precedanceAndAssociativity {
public static void main(String[] args) {
int v=5;
int u=6;
int k=v*v-u*u;
System.out.println(k);
}
}

/*
-11
*/

4. 
package com.company;

public class precedanceAndAssociativity {
public static void main(String[] args) {
int a=2;
int b=3;
int d=4;
int k=a*b-d;
System.out.println(k);
}
}

/*
2
*/
Aryadeep

Welcome to CodeWithARYA. It's My Personal Reference Website. Where You Can Get Amazing Codes. Have a Look.

Post a Comment

Previous Post Next Post