1

As per the order of precedence of operators, () is evaluated before unary operators like ++ or --. But let us consider the following code:-

int x = 1;
x = 2 + (x++);

If x++ is executed first, the value of x should have been updated to 2, and hence the value of x should have been 4. However, on executing the code, the value of x is 3. Does this mean that the expression was evaluated without considering the () around x++, or am I missing something?

2
  • x++ is post increment operation. The value of x++ expression is x. Then x is incremented. So, your code becomes x = 2 + 1 = 3. Commented Oct 13, 2023 at 17:07
  • From the Java Language Specification: “The value of the postfix increment expression is the value of the variable before the new value is stored.” (emphasis is from the spec, not added by me)
    – VGR
    Commented Oct 13, 2023 at 17:08

2 Answers 2

2

Let me try to explain this.

If you enclose the (x++). It is still evaluated, but its value is used before the increment (++) operation.

The order of your code goes like this:

  1. (x++) is evaluated first. At this point x is still 1 and (x++) returns the original value of x (1) AND THEN increments x to 2.

  2. After the x++ in parentheses is evaluated, the expression becomes x = 2 + 1, as the:

    Post-increment operator x++ returns the current value of x and then increments x. Therefore, in the expression x++ returns the current value of x, (which is 1) and then increments x to 2.

    So at the end of this step the expression x = 2 + 1 is 3.

  3. At the end the result of the addition (3) is assigned to x. So the x is now 3.

For your code to return 4, you should use "++x" (pre-increment operator) This operator increments x first then returns the updated value of x. if you use the ++x in an expression, x is incremented before its value is used.

Hopefully I explained it well. :D

1

"... As per the order of precedence of operators, () is evaluated before unary operators like ++ or --. ..."

The expression will be evaluated from left to right.
The Java® Language Specification – Chapter 15. Expressions

"... Does this mean that the expression was evaluated without considering the () around x++, or am I missing something?"

The parentheses are not denoting when the unary operator is evaluated.

I suggest reviewing the following Java tutorial.
Operators (The Java™ Tutorials > Learning the Java Language > Language Basics)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.