File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes using i=i++ Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "using i=i++ " Watch "using i=i++ " New topic

using i=i++

Ken Kallaur

Joined: Jun 28, 2010
Posts: 3
While going through some mock exams I came across the following question in Naveen's test

according to the test the answer is 2, but when I run this in MyEclipse the answer comes back as 0.

if I change the i=i++ to i++ the answer comes out as 2.

I guess my question is does i= in front of the i++ affect the outcome or not?

My thought is that the first time through the loop on the line i=i++ i would be = 0 but the next line i would be incremented to 1 and then similar for the second time through i should be equal to 2

Ken Kallaur
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
Yes it matters. Think carefully about when "i" is incremented and/or
assigned in the loop. Putting ++ before or after "i" is very different.

Jim ... ...

(P.S. And welcome to JavaRanch. You will learn a lot here.)

Sahil Kapoor
Ranch Hand

Joined: Sep 12, 2009
Posts: 316

For the above code you would get 2 0.


Explanation :-

++j or j++ it essentially means


Now which j is assigned to left (if any of assignment operator) is the issue.

Now, suppose we have
x= ++j then j(new) would be used.

if we have x=j++ then j(old) would be used.

Important is , j would be incremented first irrespective of x=++i or x=i++;

Ex1 := x=i++;

This translates to
i(new) = i(old) +1;

Ex2:- x=++i

This essentially translates to
i(new) = i(old)+1

Now just replace x with i , use the above sequence , you would get the above mentioned answers.

Thanks !!!

SCJP 6.0 96%

(Connecting the Dots ....)
Ken Kallaur

Joined: Jun 28, 2010
Posts: 3
Thanks guys for the quick replies

I think I'm getting it now.

I had it in my head that

i=i++ would still increment

I understand that
x=i++ equals the old value of i

but my thinking was
i=old value of i now increment i

The thing that throws me off is that where
i does increment
Henry Wong

Joined: Sep 28, 2004
Posts: 20538

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
I agree. Here's the link:
subject: using i=i++
It's not a secret anymore!