aspose file tools*
The moose likes Beginning Java and the fly likes FOR condition. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "FOR condition." Watch "FOR condition." New topic
Author

FOR condition.

WeiJie Lim
Ranch Hand

Joined: Sep 05, 2012
Posts: 85


Why does the output look this way :
1
2
3
4
5
6
7
8
9
10
The final value of i is 11

Shouldn't the final value be 10 ?
Kemal Sokolovic
Bartender

Joined: Jun 19, 2010
Posts: 825
    
    5

After the value 10 is printed, i is increased once more. Since the new value, 11, doesn't satisfy the condition in for loop, the loop ends and in the next statement you get that value 11.


The quieter you are, the more you are able to hear.
siva chaitanya
Ranch Hand

Joined: Jul 05, 2011
Posts: 59
Final value of i is 11 only because after the execution of System.out.println(i);//10
'i' value will be incremented which is 11 eventually.
WeiJie Lim
Ranch Hand

Joined: Sep 05, 2012
Posts: 85
Kemal Sokolovic wrote:After the value 10 is printed, i is increased once more. Since the new value, 11, doesn't satisfy the condition in for loop, the loop ends and in the next statement you get that value 11.


Very clear answer. Thanks ^^
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14146
    
  18

Let's look at what exactly this line means:

Note that there are three parts in the for-statement.

1. The first one is executed at the start to initialize i: i = 1
2. The second one is the condition for the loop. This is checked at the beginning of each iteration of the loop. The loop will repeat as long as the condition is true.
3. The third one is executed at the end of each iteration.

So, what happens when you run this?

i = 1
check i <= 10: true, so run the body of the loop
i++: i becomes 2
check i <= 10: true, so run the body of the loop
i++: i becomes 3
...
check i <= 10: true, so run the body of the loop
i++: i becomes 9
check i <= 10: true, so run the body of the loop
i++: i becomes 10
check i <= 10: true, so run the body of the loop
i++: i becomes 11
check i <= 10: false, so stop, we're done

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: FOR condition.