views:

1643

answers:

8

Is there a difference between ++x and x++ in java?

+31  A: 

++x is called preincrement while x++ is called postincrement.

int x = 5, y = 5;

System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6

System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6
Emil H
Good explanation
Rahul Garg
+5  A: 

Yes,

int x=5;
System.out.println(++x);

will print 6 and

int x=5;
System.out.println(x++);

will print 5.

Johannes Weiß
Why is this only +1 and the same answer , posted at the same instant is +5?
Tom
Because we're turning into slashdot... slowly... surely...
skaffman
@Tom, I was just considering how to cast my votes, so here's my interpretation: one small reason to prefer Emil H's answer is that his example code is /slightly/ more informative.
Jonik
Jonik. True, also includes keywords 'preincrement' and 'postincrement'.
Tom
+7  A: 

yes

++x increments the value of x and then returns x
x++ returns the value of x and then increments

example:

x=0;
a=++x;
b=x++;

after the code is run both a and b will be 1 but x will be 2.

Victor
+1 Lots of examples, this is an _explanation_ with examples :)
Jeremy Smyth
Yeah, I also ended up upvoting this one because of the clear prose explanation at the start. (Hmm, didn't know you can do cursive in comments nowadays... *cool*)
Jonik
+1  A: 

Yes, using ++X, X+1 will be used in the expression. Using X++, X will be used in the expression and X will only be increased after the expression has been evaluated.

So if X = 9, using ++X, the value 10 will be used, else, the value 9.

nojevive
+1  A: 

If it's like many other languages you may want to have a simple try:

i = 0;
if (0 == i++) // if true, increment happened after equality check
if (2 == ++i) // if true, increment happened before equality check

If the above doesn't happen like that, they may be equivalent

flq
+2  A: 

Yes.

public class IncrementTest extends TestCase {

    public void testPreIncrement() throws Exception {
     int i = 0;
     int j = i++;
     assertEquals(0, j);
     assertEquals(1, i);
    }

    public void testPostIncrement() throws Exception {
     int i = 0;
     int j = ++i;
     assertEquals(1, j);
     assertEquals(1, i);
    }
}
Carl Manaster
+1  A: 

Yes, the value returned is the value after and before the incrementation, respectively.

class Foo {
    public static void main(String args[]) {
        int x = 1;
        int a = x++;
        System.out.println("a is now " + a);
        x = 1;
        a = ++x;
        System.out.println("a is now " + a);
    }
}

$ java Foo
a is now 1
a is now 2
Lars Haugseth
+5  A: 

These are known as postfix and prefix operators. Both will add 1 to the variable but there is a difference in the result of the statement.

int x = 0;
int y = 0;
y = ++x;            // result: y=1, x=1

int x = 0;
int y = 0;
y = x++;            // result: y=0, x=1

See here http://www.janeg.ca/scjp/oper/prefix.html

Pablojim