my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Infinite loop..WHY? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Infinite loop..WHY?" Watch "Infinite loop..WHY?" New topic
Author

Infinite loop..WHY?

Cathy Song
Ranch Hand

Joined: Aug 24, 2003
Posts: 270
class test {
public static void main(String[] s) {
System.out.println("Start");
for(int i=0; i < 10; i = i++ ) {
System.out.println("Processing...");
}
System.out.println("End");
}
}
Can anyone explain what happens here?
i = i++?
Thanks,
Cathy.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
We have talked about the "i=i++" issue many times. Here is how it works.
1) Store the original value of i.
2) increment i.
3) assign i with the stored value (not the incremented value).
The order of operation is that the post-fix occurs before assignment but it is the original value that is assigned.
Try using "i++" instead of "i=i++".


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Cathy Song
Ranch Hand

Joined: Aug 24, 2003
Posts: 270
Thanks Thomas.
K Ville
Ranch Hand

Joined: Aug 16, 2003
Posts: 58
I'm sorry, sir, but I am a neophyte to Java. I still couldn't understand despite your explanation. Why is it that iteration expression 'i = i++' makes it an infinite loop?


Thinking is the talking of the soul with itself...-Plato
Mika Leino
Ranch Hand

Joined: Jan 07, 2002
Posts: 56
The problem in that iteration expression lies in the postfix incrementation. As Thomas tried to explain, in that particular iteration expression the value of i actually never changes.
In that assignment the post-fix incrementation increments only the value of i as it was before the assignment. I'll try explain a little better with some pseudo code:

can be read also like this:

I hope that latter example helps you


Mika Leino<br />SCJP, SCWCD
K Ville
Ranch Hand

Joined: Aug 16, 2003
Posts: 58
Thank you, sir. You explained it well. Now, I understand
Cathy Song
Ranch Hand

Joined: Aug 24, 2003
Posts: 270
Maha Anna has given an amazing explanation/method here:
http://www.coderanch.com/t/190825/java-programmer-SCJP/certification/Array
Thanks,
Cathy.
Durgaprasad Guduguntla
Ranch Hand

Joined: Oct 20, 2003
Posts: 99
Thanks Cathy.. it really helped..


Thanks,<br />Durgaprasad<br />SCJP1.4, SCWCD1.4, SCBCD1.3,<br />SCEA
Harwinder Bhatia
Ranch Hand

Joined: Oct 17, 2003
Posts: 150
Wow ... it was a really interesting & informative thread !
Thanks Cathy & Durga.
 
Consider Paul's rocket mass heater.
 
subject: Infinite loop..WHY?
 
Similar Threads
Array
Enhanced For Loop
Strange IF condition
Set all ComponentOrientation to rtl
auto boxing additions