Operator precedence with comparison and logical operators – Computer Sir Ki Class

Code Learning #JAVA#3740

## 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

 class OpPrecCompCond { public static void main(String[] args) { int a=10,b=12,c=14; boolean d= a-c%b >= 8 && a*2 == b*2-4; System.out.println(d); } } .linedwrap { border: 1px solid #c0c0c0; padding-top: 5px; padding-bottom: 5px; border-radius: 4px; background-color:#F8F8F8; } .linedtextarea { padding: 0px; margin: 0px; background-color:#F8F8F8; } .linedtextarea textarea, .linedwrap .codelines .lineno { font-size: 12pt; font-family: monospace; line-height: normal !important; } .linedtextarea textarea { padding-right:0.3em; padding-top:0.3em; border: 0; } .linedwrap .lines { margin-top: 0px; width: 20px; float: left; overflow: hidden; border-right: 1px solid #c0c0c0; margin-right: 10px; } .linedwrap .codelines { padding-top: 5px; } .linedwrap .codelines .lineno { color:#AAAAAA; padding-right: 2px; padding-top: 0.0em; text-align: right; white-space: nowrap; } .linedwrap .codelines .lineselect { color: red; }

## Run Output

``true``

## 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

## 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|

×