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 Break/Incrementation question 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 "Break/Incrementation question" Watch "Break/Incrementation question" New topic

Break/Incrementation question

David Kennedy
Ranch Hand

Joined: Jan 22, 2006
Posts: 33
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.

[ July 31, 2006: Message edited by: David Kennedy ]

"There are only 10 types of people in the world: Those who understand binary, and those who don't"
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
Yes, the statements that are part of the for loop declaration

are only executed after the body of the loop.
David Kennedy
Ranch Hand

Joined: Jan 22, 2006
Posts: 33
Cheers for the reply

That solves that for me.

[ July 31, 2006: Message edited by: David Kennedy ]
I agree. Here's the link:
subject: Break/Incrementation question
It's not a secret anymore!