This week's book giveaways are in the Refactoring and Agile forums.We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# related to operators

Harvinder Singh
Ranch Hand
Posts: 90
//11:25 AM 8/15/03
//Question: how is the following expression evaluated?
class M {
static int m(int i) {
System.out.print(i + ", "); return i;
}
public static void main(String s[ ]) {
m(m(1) + m(2) % m(3) * m(4));
}
}
//output is 1,2,3,4,9
/*reason
Java evaluates expressions from left to right. The first operator encountered is the addition operator. First, the left operand is evaluated as 1. The value of the right operand will be the result of the expression m(2) % m(3) * m(4). //why not 2 ?
When Java encounters the remainder operator, "%", it first evaluates the left hand operand, 2, and then the right, 3. The result is 2.//ok
The next operator is the multiplication operator. The left operand is the result of the previous operation, 2. The right operand is 4. The result is 8. Java then adds the left operand, 1, of the addition operator to the value of the right operand, 8. The result is 9. �
*/

Jose Botella
Ranch Hand
Posts: 2120

The value of the right operand will be the result of the expression m(2) % m(3) * m(4). //why not 2

Because % has higher precedence than + is carried out first. Then the result is 1 + 2 * m(4) . But * has a higher precedence than + , thus all ends up to something similar to 1 + (2 * 4)
We can check out what the compiler produces with a similar example:

We got the previous output using javap -c Test .
First i, j and k are evaluted (pushed into the operand stack) in that order. Then irem performs the modulus on j and k. The result is multiplied by imul with m. The result is added by iadd to i, that was at the bottom of the stack.
I would say that for an expression like A op1 B op2 C op3 D the A and B operands are evaluated first (*). Now the if the operator op1 takes precedence over op2 ,or both have the same precedence, such operation is performed on A and B; otherwise C is evaluated and the precedence of op2 is compared against op3. Repeat the process untill you find the first operator that has a higher or equal precedence than the one to its right, and a higher precedence or equal to the one to its left. That operation is performed.
(*)Some operators (&&, || )will prevent subsequent evaluations.
[ August 17, 2003: Message edited by: Jose Botella ]
[ August 17, 2003: Message edited by: Jose Botella ]