What is the difference between i++ & ++i in a for loop? [duplicate]
I've just started learning Java and now I'm into for loop statements. I don't understand how ++i
and i++
works in a for-loop.
How do they work in mathematics operations like addition and subtraction?
They both increment the number. ++i
is equivalent to i = i + 1
.
i++
and ++i
are very similar but not exactly the same. Both increment the number, but ++i
increments the number before the current expression is evaluted, whereas i++
increments the number after the expression is evaluated.
int i = 3;
int a = i++; // a = 3, i = 4
int b = ++a; // b = 4, a = 4
Here's a sample class:
public class Increment
{
public static void main(String [] args)
{
for (int i = 0; i < args.length; ++i)
{
System.out.println(args[i]);
}
}
}
If I disassemble this class using javap.exe I get this:
Compiled from "Increment.java"
public class Increment extends java.lang.Object{
public Increment();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: aload_0
4: arraylength
5: if_icmpge 23
8: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
11: aload_0
12: iload_1
13: aaload
14: invokevirtual #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
17: iinc 1, 1
20: goto 2
23: return
}
If I change the loop so it uses i++ and disassemble again I get this:
Compiled from "Increment.java"
public class Increment extends java.lang.Object{
public Increment();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: aload_0
4: arraylength
5: if_icmpge 23
8: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
11: aload_0
12: iload_1
13: aaload
14: invokevirtual #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
17: iinc 1, 1
20: goto 2
23: return
}
When I compare the two, TextPad tells me that the two are identical.
What this says is that from the point of view of the generated byte code there's no difference in a loop. In other contexts there is a difference between ++i and i++, but not for loops.