File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "A question about the precedence" Watch "A question about the precedence" New topic

A question about the precedence

yang ming

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.println(" j="+j);
int i=0;
int j = m(++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?

Ming Yang
Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865
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="" target="_blank" rel="nofollow">Try my mock exam.</a>
I agree. Here's the link:
subject: A question about the precedence
It's not a secret anymore!