• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Break/Incrementation question

 
David Kennedy
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just have a question about this code:

public class Test{
public static void main(String[] args) {
int counter = 0;
outer: for(int i=0;i < 4; ++i)
middle: for(int j=0;j < 4; ++j)
inner: for(int k=0;k < 4; ++k) {
System.out.println("Hello - " + ++counter);
if((k % 4) ==0)
break outer;
}
}
}

The answer is meant to be Hello - 1 due to 0 mod 4 being 0 and thus the inner loop is only executed once but I would of thought since k is pre-incremented in the declaration of the for statement that k would never be 0 and be greater than 0 due to this pre-incrementation and thus wouldnt break to outer?

Does the incrementation happen only after one iteration of the for loop or something?

Any tips to help understand would be appreciated.

Dave
[ July 31, 2006: Message edited by: David Kennedy ]
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, the statements that are part of the for loop declaration



are only executed after the body of the loop.
 
David Kennedy
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cheers for the reply

That solves that for me.


Thanks
[ July 31, 2006: Message edited by: David Kennedy ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic