Skip to content

Instantly share code, notes, and snippets.

@alexmullins
Last active September 23, 2015 04:12
Show Gist options
  • Save alexmullins/1c2788361e886e7f3fee to your computer and use it in GitHub Desktop.
Save alexmullins/1c2788361e886e7f3fee to your computer and use it in GitHub Desktop.
Example shows the difference between ++d and d++ operators.
package test;
public class Test {
// Example showing the difference between pre-increment (++i) and post-increment (i++) operators.
public static void main(String[] args) {
int d = 0;
// d++ is post-increment op
int e = d++; // What is the value of d and e after this line executes? It is d == 1 and e == 0
if (e == 0) {
System.out.println("d++ will first return the current value of d (which is 0) and assign it to e, then it will increment d to 1.");
}
// reset
d = 0;
// ++d is pre-increment op
int f = ++d; // What is the value of d and f after this line executes? It is d == 1 and f == 1
if (f == 1) {
System.out.println("++d will first increment d to 1 and then assign that value to variable f.");
}
// Conclusion: Best way to remember the difference between ++d and d++ is this:
// 1. Ask yourself where is ++ in relation to d (BEFORE or AFTER).
// 2. The answer to that fills in the blank to the following statement:
// "The incrementing happens ______ the surrounding expression evaluates.
// Simulate the pre-increment and post-increment operators with Java functions and classes
IntegerWrapper w1 = new IntegerWrapper(0);
int a = postInc(w1); // read: w1++. after this line executes: a == 0 and w1 == 1
System.out.println("a == "+a+" and w1 == "+w1.i);
// reset
w1.i = 0;
int b = preInc(w1); // read: ++w1. after this line executes: b == 1 and w1 == 1
System.out.println("b == "+b+" and w1 == "+w1.i);
}
// Java implementation of ++i
private static int preInc(IntegerWrapper iw) {
iw.i = iw.i + 1;
return iw.i;
}
// Java implementation of i++
private static int postInc(IntegerWrapper iw) {
int temp = iw.i;
iw.i = iw.i + 1;
return temp;
}
}
class IntegerWrapper {
public int i;
public IntegerWrapper(int i) {
this.i = i;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment