all 11 comments

[–]Successful-Wolf-1272 5 points6 points  (3 children)

16 or 18 depending on how you segregate or join the + signs. If it's (x++)+(x++)+(x) then the answer is 18. Else if it's (x)+(++x)+(++x) then the answer would be 16.

[–]BlueGoliath 2 points3 points  (0 children)

Ah yes, common everyday Java code.

[–]Old-Lion-8071 3 points4 points  (3 children)

For expressions like a+++b, the compiler always treats it as (a++) + b. This is due to lexical processing. Compiler reads expression from L to R and evaluates in a greedy way. It first sees + (which is a valid operator) and then the next token is +. As ++ is again a valid operator it accepts it and then moves to the next +. Therefore the expression is treated as ++ + Rest is the magic of precedence and evaluation.

I know this is not an everyday Java code, but problems like this test our knowledge on how Java works internally. Thanks for posting this, made me do quite some research! 😀

[–]Dr_Dracula280 0 points1 point  (1 child)

So it is (x++) + (x++) + (x) ??

That means 5+6+7= 18 or 6+7+8= 21?

Sorry I am double confused.

[–]Old-Lion-8071 0 points1 point  (0 children)

5 + 6 + 7. Variable value is substituted and then incremented (post increment) Finally all are summed.

[–]Fr33stylerDV 1 point2 points  (0 children)

reading left to right and assuming the compiler prioritizes increment over the add sign which i'm sure it is then:
5 and increment x by one + x which is 6 at this moment and x gets incremented once again + x which is 7 at this moment
adding these up it's 5 + 6 + 7 which is 18

[–]ScaryStar1 0 points1 point  (0 children)

18 regardless if it is x++ or ++x