Don't write code whose intention isn't obvious when you read it. You can get all sorts of results you don't expect!
And please use the code button; it makes your posting easier to read.
Go and find a precedence chart (there is one here) and you see that the ++ postfix operator has the highest precedence of all. The + operator has a rather lower precedence, and the assignment operators including *= have the lowest precedence of all. So you can now work out which operation is carried out first, which is carried out second and which third. You should easily work out how you get 15. Remember 15 = 3 * 5.
When you add the round brackets () you are changing the precedence of the operators, so you can work out which operation is done first. That is more difficult to understand; I would have thought you would get 9. I shall let you explain how you get 15 and 12; remember what the difference between i++ and ++i is.
Thank you, Rob. I worried and worried about that last night, wondering why it wasn't 9, then just after going to be I realised that the *=2 bit is executed first and the whole thing evaluates to 6+6, as you explained. Relieved that it follows the usual rules of arithmetic and the i++ operator, I was able to sleep!
Joined: Oct 26, 2008
hello rob prime,
Whereas System.out.println((i *= 2) + i++) can be broken up as follows:
because the compiler assigns the value of i as follows:
i = 6 (after i*=2)
i = 6(after i++)
i=7(effect of i++)
so this code will have output as follows:
i is : 7
This is what i get , any suggestions are welcome.
Joined: Oct 13, 2005
I told you last night: remember the difference between i++ and ++i.
If you start with i as 6, then both i++ and ++i change i to 7. But you do not have i in that statement; you have i++. The value of i++ is the old value of i, so i is 7, but i++ is still 6.