what is this? int k = 1; int i = ++k + k++ + + k ; //line 1 System.out.print(i+ " "+ k) ; finally, i is 5 and k is 3. why? and if I change line 1 to int i = ++k+k++++k; what is the result. why java allows the complicate and illogical thing to happen? that is not good.
int k = 1; int i = ++k + k++ + + k; Answere to the above will NOT be i = 5 and k = 3; The correct answere will be: i = 7 and k =3; Why? Well first you have to take into account operator precedence: Highest Precedence 1. postfix k++; 2. prefix ++k and unary +; 4. + addition 5. = (assignment) Lowest Precedence. Secondly consider that postfix first yiels its old value and then increments/decrements and prefex first increments/decrements and then yields the value and unary + is the same algebra +(does nothing infact). So in the above situation k++ will yield 1 and then make itself 2 then comes the ++k which will make itself 3 and yield three, uptill now 1 and 3 have been yielded, which equates to 4 and finally k is again added making the yield = 7 (i = 7) and k = 3. Remeber this sequence and you'll never faulter. Now as far as int i = ++k+k++++k; is concerned you'll encounter a compiler error.....Reason you need to distinguish between different operators in a statement or a expression, therefore the above should atleast be modified as below to run, and this two will produce the same result. int i = ++k+k++ + +k; Now to practice lets say that you solve the following expression for me: int i = ++k + (k++ + +k); Reply soon, chao!
[This message has been edited by Amond Adams (edited November 30, 2000).]
Thanks so much for your answer. the result is the same. But I still don't understand the "unary" Don't say I am lazy. I check the difinition from java.sun.com. I don't get it. Coz it say prompt i to int if i is char, short, and byte. I don't say increment by one.