File APIs for Java Developers Manipulate DOC, XLS, PPT, PDF and many others from your application. http://aspose.com/file-tools
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login

# expression evaluation

mounika paruchuri
Greenhorn

Joined: Feb 12, 2002
Posts: 26
Consider the following expression:
i--%5>0
the question is
a : What is the result of the expression, assuming that the value of i is initially 10?
b : Modify the expression so that it has the same result but is easier for programmers to read.
when I evaluate the expression using precedence... I get true....
10--%5>0 //1
9%5>0 //2 as unary is higher in precedence than % and >
4>0 //3 as % has higher precedence
finally true...
but the answer is given as :
Answer: false,(i-- % 5) > 0
can somebody explain why it is 'false'......
Angela Margot
Ranch Hand

Joined: Feb 07, 2002
Posts: 80
The location of the unary operator determines when that operation takes place. If an operator is --x then it occurs before any other operation. If it is x-- then it occurs after the other operations.
So, if it were --i%5>0 then the result would be true because the unary operation would take place before the % - thus if i=10, --i%5>0 -> 9%5>0 -> 4>0 is true
But because it is i--%5>0 the i%5 takes place before the i-- . In this case if i=10, i--%5>0 -> 10%5>0 -> 0>0 is false and then i=9.
Help any?

Angela Margot <img src="smile.gif" border="0"> <br />Sr. Software Engineer<br />SCJP2 SCWCD MCSD MCP
Brian Lugo
Ranch Hand

Joined: Nov 10, 2000
Posts: 165
Monika,
Here is link to understanding post fix operators:
http://www.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=014701
Hope this helps,
Brian
mounika paruchuri
Greenhorn

Joined: Feb 12, 2002
Posts: 26
thanks Leilani for the great explanation and brian for the link....it did help.
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
arrrg. This is a good example of why tests are hard! I KNOW how postincrement/predecrement work, but that little fact got lost in my brain somewhere and when I first looked at this question, I used 9 for the left-hand side operator, giving 4 for the answer, making the statement true.
But of course this is wrong, because I should have used 10. I know this, yet it slipped my mind.
That's why it's critical to go slow, take your time, and concentrate on the details of each question so you don't make silly mistakes like I just did!
[ February 20, 2002: Message edited by: Rob Ross ]

Rob
SCJP 1.4

I agree. Here's the link: http://aspose.com/file-tools

subject: expression evaluation