Operator precedence with brackets – Computer Sir Ki Class

Code Learning #JAVA#3738

## Operator precedence with brackets

Understanding operator precedence when brackets are used.

## Learning Objectives

• Operator precedence with the use of brackets.

## Source Code

 class OperatorPrecedenceBrackets { public static void main(String[] args) { int a=5,b=7,c=9; int d= a++ + (b%(c%a)) + (a+b+c); 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

``28``

## Code Understanding

int a=5,b=7,c=9; //Three integer variables initialised

int d= a++ + (b%(c%a)) + (a+b+c);
Above precedence problem would be solved in steps.

STEP 1: 5 + (7%(9%6)) + (6+7+9)
Post fix will be applied first. second and third instance of postfix will become 6, first instance will remain 5.

STEP 2: 5 + (7%(3)) + (22)
Internal most brackets shall be solved

STEP 3: 5 + 1 + 22
Next level of brackets shall be solved. Each bracket set will follow operator precedence of its own.

STEP 4: 28
Final computation done when it comes down to + – level

System.out.println(d);
Output 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): OperatorPrecedenceBrackets.java

sunmitra| Created: 5-Mar-2018 | Updated: 5-Mar-2018|

×