It's not a secret anymore!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes A question about the precedence Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "A question about the precedence" Watch "A question about the precedence" New topic
Author

A question about the precedence

yang ming
Greenhorn

Joined: Nov 06, 2002
Posts: 17
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


Ming Yang
Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865
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.


Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: A question about the precedence
 
Similar Threads
doubt in explanation dam mock question
A Dan Mock Exam Question (Dec 4)
Operator Precedence
associativity
postfix operator