'I am stuck at a simple problem here ,and got a error in a statement in java--> ((a++)++)++; [duplicate]

public class Test1 {
    public static void main(String[]args) {
        int a=1;
        ((a++)++)++;  //in this line i got a error as variable expected
        System.out.println(a);

    }
}

This is getting an error please let me know that why error occurs and (()) are allowed or not.



Solution 1:[1]

There are two main things you should be aware of in order to properly understand this issue.

  • Java evaluates expressions from left to right and in the order in which they appear.
  • The Postfix increment operator only increments the variable(in our case 'a') after the variable is used or returned.

And, once again, I emphasize that this is only a variable, not a constant or anything else.

This is pseudocode for the postfix increment operator:

int x = 5;
int temp = x;
x += 1;
return temp;

Then let's see what happens when we compile this code in the order specified.

int a=1;
((a++)++)++;

we know that it evaluates to:

((a=a+1)++)++;

Since a=1 it becomes,

((1++)++)++;

Then it evaluates to:

((2)++)++;

So since from the second post increment it is not a variable but a constant.It will give this compiler error.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark Rotteveel