Hi Rahul,
This is my understanding and I hope it helps you.
There are few things which one needs to remember before evaluating an expression and they are:
1. Evaluation Order: All operands are evaluated left to right irrespective of the order of execution of operations. You agree to this. Right.
2. Evaluate Left-Hand Operand First: The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.
So, applying the above rules to both examples:
a. int i=5*(2+6);// case 1
We will evaluate from left to right. So considering 5*(2+6),the left hand operand (which is 5) is evaluated. Since 5 is a constant, there is nothing to evaluate and hence we keep it as 5.
b. int y = z() * (z() + z());//case 2
We will evaluate from left to right. So considering z()*(z()+z()), the left hand operand (which is z()) is evaluated. After evaluation(x=0 and so return ++x gives 1) the result is x=1.
So, now the above equation is
int y = 1 * (z() + z())
3. Evaluate Operands before Operation: Java also guarantees that every operand of an operator (except the conditional operators &&, | |, and ?
appears to be fully evaluated before any part of the operation itself is performed.
If the binary operator is an integer division / or integer remainder % , then its execution may raise an ArithmeticException, but this exception is thrown only after both operands of the binary operator have been evaluated and only if these evaluations completed normally.
a. int i=5*(2+6);// case 1
so, int i = 5*(2+6) is = 5*(2+6) as 2 and 6 are constants and there is nothing to evaluate.
Remember, we have still not started
the operation and hence the equation still has * and () intact.
int y = 1 * (z() + z())
z() is evaluated twice and we get 2 and finally 3 from the evaluation of z(). So, the equation is now
int y = 1 * (2 + 3).
Remember, once again we have still not started the operation and hence the equation still has + and () intact.
4.Evaluation Respects Parentheses and Precedence: Java implementations must respect the order of evaluation as indicated explicitly by parentheses and implicitly by operator precedence.
So parenthesis gets the first preference before other operators in the operator precedence.
So now we have
a. int i=5*(2+6);// case 1
int i = 5 * (8)
b. int y = 1 * (2 + 3);// case 2
int y = 1 * (5)
and finally we get i = 40 and y = 5.
I hope the above explanation helps you and if you want to know more then I suggest that you read topic
Evaluation Order in the
JLS Suma
[This message has been edited by Suma Narayan (edited June 21, 2000).]