Search code examples
javaoperatorspost-incrementpre-incrementunary-operator

Post and Pre Increment Operator OCJA-1.8


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);
  } 
}

Solution

  • 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
    }