Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

precedence

 
Thomas Thomas
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dave
You are correct.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic