user1765876
user1765876

Reputation:

post increment with addition in Java

I have following code in java

int x=5;
System.out.println(x++ + ++x);

The output is 12.

I thought it should be 11.

We have three operators here:

In which order does the above print statement compile?

If I write int x=5; and then ++x, does x==6 or x==5 as I haven't written x=++x. Does the new value get stored in x?

Looking for a way to remember operator precedence in Java,or .NET, just like we have DMAS. Is their any analogy for this too?

Upvotes: 4

Views: 1403

Answers (6)

user3091530
user3091530

Reputation: 630

post increment

During Expression evaluation only pre incremnted value is used.(Post increment operator is used just after completion of expression evaluation) This may help you

   =x++ + ++x
   =x++ + 6
   =6 + 6
   =12

Upvotes: 1

Squizer
Squizer

Reputation: 651

Evaluation/increments will occur before the + operator, one after the other

Your println is, step by step:
(x++ + ++x) where x=5
(5++ + ++x) where x=5
(5 + ++x) where x=6
(5 + x) where x=7
(5 + 7)=12

You have 2 increments of x, from 5 to 7, before summing x thus explaining the total of 12.

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34146

In the line

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

first x is 5, so after x++, x will be 6, but the expression will be evaluated before the increment, so you will have:

5 + ++x

at this moment x is 6, so ++x will first increment x to 7 and then evaluate the expression. At the end you will have:

5 + 7

which is 12.

Upvotes: 1

Karura91
Karura91

Reputation: 623

The point is that:

x++ increment x AFTER the assignment in the expression. ++ x increment x BEFORE the assignment in the expression.

So, in your example you actually do 5 + 7. 5 Because the increment is done after the evaluation, so x become 6. 7 because the increment is done before the evaluation, so x become 7.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234695

In C and C++ this kind of thing is undefined behaviour (since, in those languages, the + does not sequence the two expressions).

But in Java, it is defined. The evaluation order is from left to right.

It's quite simple: the first expression is x++ which has the value of 5 but increases x to 6.

The second expression is ++x which increases x from 6 to 7 and has the value of 7.

5 + 7 = 12: Done.

Needless to say, this kind of code is not recommended. And a port to C / C++ would be distastrous.

Upvotes: 2

AbhinavRanjan
AbhinavRanjan

Reputation: 1646

x++ is equal to 5 but x has become 6. ++x means 6 is incremented by 1 that is ++x is 7. So 5 + 7 = 12 is the correct answer.

Upvotes: 5

Related Questions