Operator precedence with comparison and logical operators
Understanding operator precedence with comparison(relational) and logical(conditional) operators.
Learning Objectives
- Operator precedence with the use of comparison and logical operators.
Source Code
|
Run Output
Code Understanding
int a=10,b=12,c=14; //Three integer variables initialised for further computation
boolean d= a-c%b >= 8 && a*2 == b*2-4;
We shall analyse this computation with step by step approach
STEP 1: 10-14%12 >= 8 && 10*2 == 12*2-4;
Values are put in the expression
STEP 2: 10-2 >= 8 && 20 == 24-4;
Arithmetic computation step is done to bring it to minimum level.
STEP 3: 8 >= 8 && 20 == 20;
Level up to only comparison and logical steps are brought
STEP 4: true && true;
Comparison level is done first
STEP 5: true;
Logical level is applied next
System.out.println(d);
Final output is printed
Notes
- Whenever comparison and logical operators are involved the final expression will always be a boolean expression which will evaluate to either true or false.
- The operator precedence table can be seen at this link.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Common Errors
- Student often try to do make these evaluations in one go and errors are quite likely. The stepwise approach is always better.
Suggested Filename(s): OpPrecCompCond.java
sunmitra| Created: 5-Mar-2018 | Updated: 5-Mar-2018|