• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

A question about the precedence

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
I think I'll just lie down here for a second. And ponder this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic