Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Infinite loop..WHY?

 
Cathy Song
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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++".
 
Cathy Song
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Thomas.
 
K Ville
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Mika Leino
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
K Ville
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, sir. You explained it well. Now, I understand
 
Cathy Song
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Cathy.. it really helped..
 
Harwinder Bhatia
Ranch Hand
Posts: 150
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow ... it was a really interesting & informative thread !
Thanks Cathy & Durga.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic