Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A question about the precedence

 
yang ming
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question cames from Dan Mock Exam but I changed to this
Question 30
class M {
static int m(int i) {
System.out.print(i + ", ");
return i;
}
public static void main(String s[]) {
int i=0;
int j = ++i + m(++i);
System.out.print("i="+i);
System.out.println(" j="+j);
//
int i=0;
int j = m(++i)+ ++i;
System.out.print("i="+i);
System.out.println(" j="+j);
}
}
The output will be
2, i=2 j=3
1, i=2 j=3
My question is why these two outputs are same. According to the Precedence rules, the Postfix operators is higer than prefix unary operators,so I think everytime java should call function first, then do "++i". That means the two outputs are same. But actually the results are different.
Any ideas?
Thanks
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yang,
Thank you for using my exams.
The operator questions involving increment and decrement operators are difficult. It is a little easier to learn about the evaluation of expressions by focusing on expressions that don't have side effects.
Java evaluates expressions from left to right. The left operand of an operator is always evaluated before the right operand.
The expressions that are the arguments of method calls are always evaluated before the method is processed.
I see that you are working through the comprehensive exams and you are having trouble with questions involving the evaluation of expressions. This would be a great time to go to the Single Topic Exam page and work on the operator exams in section 5. Start with the Operator exams A and B. After you understand everything on those pages, then try the Side Effects exams in the same section. Those contain the questions with the increment and decrement operators.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic