0
public class Testtt {
    public static void main(String [] args)
    {

        int x = 1;

        System.out.println(x++ + ++x + ++x);

    }

}

Result is 8 

how it prints 8 .. can any one please explain it ? o.O sorry to ask dumb question but i didnt get how the pre - post increment works

KindZadZa
  • 37
  • 5

4 Answers4

4

x++ returns 1, value of x is now 2
++x now returns 3, value of x is now 3
++x now returns 4, value of x is now 4
The returned values (1, 3 and 4) all add up to 8.

Terrible Tadpole
  • 607
  • 6
  • 20
2
System.out.println(x++ + ++x + ++x);

1.) x++ => x = 1, increement later

2.) ++x => x =3, increement from step 1 , increement again for ++x

3.) ++x => x=4, increement again for ++x

finally - 1 + 3 + 4
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
1

x++ increments after x value is used and ++x increments before x value is used I try to explain it using an example:

int x = 1;
System.out.println(x++); // prints 1 but its value will be 2 after print
x = 1;
System.out.println(++x); // prints 2 but its value will be 2 after print
System.out.println(x++ + ++x + ++x); // 1 + 3 + 4 = 8
balint.steinbach
  • 278
  • 3
  • 16
0

++x is called preincrement x++ is called postincrement

Example:

int x = 1, y = 1;

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

System.out.println(y++); // outputs 1
System.out.println(y); // outputs 2

I can explain x++ + ++x + ++x by 1 + 3 + 4 = 8

codeaholicguy
  • 1,671
  • 1
  • 11
  • 18