1

I am practicing the java post and pre increment operators where I have a confusion to understand the output of the below program. How it have generated the output as "8" ?

public class Test{

public static void main(String [] args){
    int x=0;
    x=++x + x++ + x++ + ++x;
    System.out.println(x);
   }    
}

I have tried some more sample programs where I am able to track the outputs

public class Test{
 public static void main(String [] args){
    int x=0;
    x=++x + ++x + ++x + x++;
    //  1 + 2 + 3 + 3 =>9
    System.out.println(x);
  } 
}
Gaurav Pathak
  • 2,576
  • 1
  • 10
  • 20
  • Possible duplicate: https://stackoverflow.com/questions/28829957/pre-increment-and-post-increment-behavior-in-java – assylias Nov 06 '17 at 17:44

2 Answers2

2

This would be arguably the same as the following:

public static void main(String[] args) {
    int x=0;
    int t1 = ++x;
    System.out.println(t1);//t1 = 1 and x = 1
    int t2 = x++;
    System.out.println(t2);//t2 = 1 and x = 2
    int t3 = x++;
    System.out.println(t3);//t3 = 2 and x = 3
    int t4 = ++x;
    System.out.println(t4);//t4 = 4 and x = 4

    x= t1 + t2 + t3 + t4;//x = 1 + 1 + 2 + 4
    System.out.println(x);//8
}
Rodolfo Forte
  • 51
  • 1
  • 6
1

This might help to understand pre and post operator behavior.

 public class Test{

    public static void main(String [] args){
        int x=0;
        x =   ++x   +  x++   +      x++  +     ++ x;
      //0 = (+1+0)  + (1)    + (+1 +1)   + (+1 +1 +2);
      //0  = 1      + 1      +  2      +  4
         System.out.println(x); // prints 8.
       }    
    }
Ranjit
  • 146
  • 1
  • 9