Anonymous Person
Anonymous Person

Reputation: 219

for-loops in java

If I have the following code, what will the integer "i" be equal to after it executes? Does a loop increment after a break statement?

int i = 0;
for(int foo = 0; foo < 10; foo++,i++){
    break;
}

Upvotes: 1

Views: 2985

Answers (4)

dahvyd
dahvyd

Reputation: 491

After a for loop finishes one iteration it executes the incrementor code (in your case foo++,i++). Since your loop breaks before it finishes one iteration neither foo nor i increments.

Upvotes: 5

Charlie Martin
Charlie Martin

Reputation: 112356

You can actually look this up in the standard. A for loop with a break, by definition, is like a while, goto, as so:

for( init; test; incr){
   break;
}

is

init
while(test){
   // do things
   goto end
   incr
}
end:

So, since the break is always executed, it never hts the increment part, and neither foo nor i will be incremented.

Upvotes: 4

ObscureRobot
ObscureRobot

Reputation: 7336

It prints 0, which is exactly what you should expect it to print. The post increment clause is executed after the code block, but we are breaking in the middle of the code block. So the post increment is never executed.

Upvotes: 0

AHungerArtist
AHungerArtist

Reputation: 9579

Why don't you put a println and see...

I'm going to say it ends up with what you started (i.e., zero -- the increment happens after the code in inside the for executes -- since you break out of it, it never gets to increment).

Upvotes: 3

Related Questions