This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes precedence Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "precedence" Watch "precedence" New topic
Author

precedence

Thomas Thomas
Greenhorn

Joined: Jun 17, 2003
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

Joined: May 16, 2003
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

Joined: May 25, 2003
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

Joined: Jul 03, 2001
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


SCJP2. Please Indent your code using UBB Code
Anupam Sinha
Ranch Hand

Joined: Apr 13, 2003
Posts: 1088
Hi Dave
You are correct.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: precedence
 
Similar Threads
Can we have return statement in try block ?
Member Variable
Certification cx 310-035
passing reference problem.......I think :confused:
final variable