This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
whenever there is assignment like this you can see it like as follows:
array[index] = (index = 3)
so when this line is executed array[index] will be evaluated with original value of index then right side(index = 3) will be evaluated and the expression will become:
array = 3.
hope you understand or you need more detailed explaination?
Yes. it is related to operator precedence.... but that is not the only thing that has an effect here. You also need to understand the associativity and the order of evaluation for this.
For the precedence, the array dereference is higher than the assignment. Not that we have a choice here, if the assignment had higher precedence, the expression will generate a syntax error here.
For the associativity, it only applies to the assignments for this expression. And in this case, it just means that the second assignment has higher precedence than the first assignment.
And for the Order of Evaluation, that is defined by the specification, this is probably the main cause that effects what you are seeing. For the most part, Evaluation Order goes left to right, with side effects being applied as the expression is evaluated.
Bert Bates wrote:interesting discussion, but this sort of thing isn't on the exam.
Indeed, but Bert, is the information in your (and Kathy Sierras) book (SCJP 6) enough to pass the exam. I mean how "deep" and tricky questions are there? You mentioned that this array/index-thing isn't on the exam. But how about, lets say, overloading with widening and var-args. I understand this pretty clearly, as it is stated in the book. But then again, it can get very complicated..
In this case we got compiler error, call to callMe is ambiguous. I've played with this thing quite a lot and I think I've learned things that aren't really clearly mentioned in the book, as those are very detailed and obscure cases..
It's probably nice to know these obscure cases like the back of your hand. That way one can predict which piece of code can cause errors/mysterious behaviour, and more easily see bugs in the code. However, is this "extra" information needed to pass the exam? Is the book enough?
Hi, Nidhi Sar, That's not related to order of execution. That is related to associativity in Java. When two operators with the same precedence the expression is evaluated according to its associativity.
For Ex, x = y = z = 17; is treated as x = (y = (z = 17)), since = operator has right to left associativity.
Order of Evaluation : In Java, left operand is always evaluated before the right operand. It also applies to function arguments.