-2

What is the difference between x++ and ++x in Java

Can anybody please tell me the difference of the above by refering the below code,

class Example{
    public static void main(String args[]){
        int x=10;
        int y;
        y=x++;  //Prints 11     10 
        System.out.println(x+"\t"+y)
    }
}

class Example{
    public static void main(String args[]){
        int x=10;
        int y;
        y=++x;  //Prints 11     11 
        System.out.println(x+"\t"+y)
    }
}
j.a.estevan
  • 3,057
  • 18
  • 32
DJ Tishan
  • 99
  • 3
  • 8
  • duplicate of http://stackoverflow.com/q/1094872/799558 – Abdusalam Ben Haj Feb 26 '13 at 15:30
  • 1
    @SotiriosDelimanolis Not necessarily, if you don't know it's called *postincrement* and *preincrement*, respectively. Easy if you know. Still a duplicate, this has been asked many times. – user Feb 26 '13 at 15:30
  • @MichaelKjörling You don't need to call it by name though. Just put i++ vs ++i in some search engine. – Sotirios Delimanolis Feb 26 '13 at 15:31
  • @MichaelKjörling Actually its very easy, check this [google search](https://www.google.co.uk/#hl=en&output=search&sclient=psy-ab&q=difference+between+x%2B%2B+and+%2B%2Bx+java&oq=difference+between+x%2B%2B+and+%2B%2Bx+java&gs_l=hp.3...766.10380.0.10500.39.20.2.17.18.0.247.2664.0j18j1.19.0.les%3B..0.0...1c.1.4.psy-ab.r_6b-1uvjYI&pbx=1&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.&bvm=bv.42965579,d.d2k&fp=2d067e3b3a7f4d22&biw=1280&bih=923) – Abdusalam Ben Haj Feb 26 '13 at 15:31

4 Answers4

3

y=x++ assigns x to y, then increments x.

y=++x increments x, and then assigns it to y.

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
2

++x is the pre-increment. i.e., The value of x is first incremented and then assigned to x.

x++ is post increment. i.e., the value of x is assigned first and then incremented.

y=x++;

is essentially same as

y =x;
x= x+1;

y=++x; is same as

y= (x+1);
PermGenError
  • 45,977
  • 8
  • 87
  • 106
0

Pre and Post increment. Increment BEFORE assignment and increment AFTER assignment respectively.

Louis Ricci
  • 20,804
  • 5
  • 48
  • 62
0

The difference is that in the first case (x++) Java first resolves the assignment issue and then increments x. In the other case (++x) Java first resolves the increment and then the assignment. In the following code you will see the difference:

@Test
public void test1() {
    int x = 1;
    int y = 1;

    y = 2 + x++;
    assertEquals(2, x);
    assertEquals(3, y);
}

@Test
public void test2() {
    int x = 1;
    int y = 1;

    y = 2 + ++x;
    assertEquals(2, x);
    assertEquals(4, y);
}

As you can see, x always will be incremented, but the difference is the order in which the expression is resolved.

Hope it would be useful!

Nahuel Barrios
  • 1,870
  • 19
  • 22