# Thread: For loop using i++ and ++i

1. Member
Join Date
Nov 2011
Posts
56
Rep Power
0

## For loop using i++ and ++i

Okay, this has been bothering me for the longest time possible.

I'm not exactly a new to java, and I understand the post and pre increment, but this for loop thing has been bothering me like forever.

Java Code:
public class Testing {

public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
int k = i;
System.out.println(k);
}
}
}
Okay, so i++ returns the value before it is incremented, right?

So basically,

1) I declare i = 0. i(0) is < 2, so I enter the for loop.
2) k = i(0)
3) I print out 0.
4) i++;

Shouldn't i still be a 0? Since it returns the value before it is incremented? Wow, I can't believe I'm so bothered by this, but I'll be grateful if anyone could enlighten me.

2. ## Re: For loop using i++ and ++i

You aren't using the value returned by the ++ operator at all. Try something more like this:

Java Code:
int i = 0;
while(i < 10){
System.out.println("i before i++ is: " + i);
System.out.println(i++);
System.out.println("i after i++, before ++i is: " + i);
System.out.println(++i);
System.out.println("i after ++i is: " + i);

}

3. Member
Join Date
Nov 2011
Posts
56
Rep Power
0

## Re: For loop using i++ and ++i

Oh, I see. That explains it. Because I thought that when you are comparing i<2, you were using the return value of i++; Thanks for your code. I'll read it up later. :)

4. ## Re: For loop using i++ and ++i

Originally Posted by rhexis
Oh, I see. That explains it. Because I thought that when you are comparing i<2, you were using the return value of i++; Thanks for your code. I'll read it up later. :)
No. The increment expression is invoked after each iteration of the loop. Please read this: The for Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•