File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
Register / Login
Win a copy of
The Mikado Method
this week in the
Agile and other Processes
forum!
JavaRanch
»
Java Forums
»
Java
»
Beginning Java
Author
Order of Evaluation for pre and post increment operators
Mohnish Khiani
Ranch Hand
Joined: May 17, 2010
Posts: 65
posted
May 20, 2011 05:30:33
0
Whats the order of evaluation?
int i=0; int x=++i + i++ + ++i; System.out.println(x+" "+i);
Output :
5 3
What is the right output :
1+2+2=5
(or)
1+1+3=5
vibhor sharma
Greenhorn
Joined: Dec 10, 2010
Posts: 19
I like...
posted
May 20, 2011 06:42:30
0
Initially value of i=0;
now , int x=++i
i=0 initial
i=1 final
int x= ++i + i++
i=0 initial i=1 (initial)
i=1 final i=2(final)
int x= ++i + i++ + ++i
i=0 initial i=1 (initial) i=3(initial)
i=1 final i=1 (final; but i=2 will go) i=3 (final;i 's value)
1+1+3=5 (x's value)
....hope that helps
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9950
6
I like...
posted
May 20, 2011 06:53:00
0
Mohnish Khiani wrote:
What is the right output :
1+2+2=5
(or)
1+1+3=5
Wouldn't it have been easier to run the code yourself and find out?
Never ascribe to malice that which can be adequately explained by stupidity.
Mohnish Khiani
Ranch Hand
Joined: May 17, 2010
Posts: 65
posted
May 20, 2011 06:59:27
0
i have executed the code and know the output is 5,but i wanted to know how?
That means evaluation is from left to right no matter pre or post operators?
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
I like...
posted
May 20, 2011 07:16:18
0
Correct. That code is equivalent to this:
int i=0; int x; ++i; // i == 1 x = i; // the x = ++i has now been handled; x == 1, i == 1 x += i; // x == 2, i == 1 i++; // the x = ++i + i++ has now been handled; x == 2, i == 2 ++i; // x == 2, i == 3 x += i; // the x = ++i + i++ + ++i has now been handled; x == 5, i == 3 System.out.println(x+" "+i);
But this also shows how dangerous it can be to use pre and post increment operators inside other statements. It's very easy to loose track of what's going on.
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions
How To Answer Questions
I agree. Here's the link:
http://zeroturnaround.com/jrebel
- it saves me about five hours per week
subject: Order of Evaluation for pre and post increment operators
Similar Threads
Operators
assigment order and post increment
operator precedence
post and pre increment opeartor
simple operator precedence question
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter