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!

# precedence

Thomas Thomas
Greenhorn
Posts: 28
hi
public class Test{
static int var1=5;
public static int increment(int var1){
Test.var1=var1+Test.var1;
return Test.var1;
}
public static void main(String[] args){
int d=var1+(increment(2)+var1);// =19
System.out.println(d);
}
}

Brian Joseph
Ranch Hand
Posts: 160
This is a good thread. Basically, you need to evaluate the expression left to right.
Operator Precedence
A example like above could be:

d = 1 + 1(d=2) + 2; //4
If you are evaluating the expression and there is a side effect, that side effect can affect the evaluation of the expression.
[ June 24, 2003: Message edited by: Brian Joseph ]

Dave Johnson
Ranch Hand
Posts: 111
So just to be sure am I right in thinking that the line: int d=var1+(increment(2)+var1); in mathematical terms is as follows: d=5+7+7?

Jose Botella
Ranch Hand
Posts: 2120
Welcome to the Ranch Thomas.
Because you did not state your question I am only guessing: var1+(increment(2)+var1) should print 21, instead of 19 as it does? The reasoning is given that the parentheses executes first the first var1 should be 7 when evaluated?
In java the expressions are evaluted from left to right. The value of the first var1 (5) is stored (in the operand stack) and then the rest of the expression is executed. Thus the problem was the tendency to think that a parentheses is executed before anything to its left. This is not true when evaluating expressions in Java.
It is possible to check this out using javap -c Test:

The bytecode at line 0 stores the value of var1 in the operand stack before the invokation of increment(2) in line 4. The last integer addition (iadd) at line 11 adds this value previously stored, and the result of increment(2) + var1

Anupam Sinha
Ranch Hand
Posts: 1090
Hi Dave
You are correct.