I tried to solve it manually as follows. Since operator precedence is checked from LEFT to RIGHT of an expression, Multiplication(*) will happen first, followed by DIVIDE (/), followed by ADD(+) and finally SUBTRACT (-)

Here are the steps.
3+4-5*2/7
3+4-10/7
3+4-1.4
7-1.4
5.6

However, when I try to run the same in Java, I get the answer as 6.0

Can anyone explain, how operator precedence works?

Without seeing your program I cannot be positive what is going on here, but I suspect it you are not using float or double variables and you are ending up with a rounded answer.

Also just a tip, which I'm sure you are aware of, adding parenthesis to complex math code makes code significantly more readable and more difficult to make mistakes.

Bobby Smallman wrote:Without seeing your program I cannot be positive what is going on here, but I suspect it you are not using float or double variables and you are ending up with a rounded answer.

Also just a tip, which I'm sure you are aware of, adding parenthesis to complex math code makes code significantly more readable and more difficult to make mistakes.

It's quite obvious that if using constants here, JVM takes pure int-arithmetic. That's why 5*2/7 is 1.

Operators are checked from left to right BUT with checking precedence!

First it's 5*2 => 10. Then 10/7 => 1 (because it's int!). Then 3 + 4 - 1 => 6.

If / was over * it would be 3 + 4 + (5*(2/7)) => 3 + 4 + (5*0) => 7

Prasad Shindikar
Ranch Hand

Joined: Feb 18, 2007
Posts: 114

posted

0

I seemed to have forgotten the basic rule that when we use two integers for an arithmetic operation, the result is always an INT!

Thanks!

However, I am unable to understand

Operators are checked from left to right BUT with checking precedence!

What do you mean by checking precedence?

Christian Dillinger
Ranch Hand

Joined: Jul 20, 2009
Posts: 191

posted

0

The are operators having a higher "value" than others, that precendence. So the JVM takes that statement "3+4-5*2/7" and tries to calculate... It divides the statement into smaller parts. And where does it divide if it has more than one possibility? It takes the operators with the lower "value".

So it should look like this:
3+(4-5*2/7)

Next step: resolve the part inside braces.

=> 3 + ( 4 + (5*2/7))

and so on.

May be this is a bad example because the "error" was just because of int-arithmetic.

Take 3*4/2+1/4*5.

Lowest "value" is +. So you get (3*4/2) + (1/4*5). Now you only have ops that have the same "value". They are checked from left to right. => (3*4)/2 and (1/4)*5.