Page 1 of 1
Precedence of increment ooperators
Posted: Fri Sep 22, 2017 2:59 am
by Lefteris
Consider the code
int x=3;
int y=++x * 5 / x-- + --x;
System.out.println(x+" "+y);
Is it true that post-increment takes precedence over pre-increment? If yes y should evaluate to 3. However, it evaluates to 7. Why?
Re: Precedence of increment ooperators
Posted: Fri Sep 22, 2017 3:36 am
by admin
Please post the source of the code.
Re: Precedence of increment ooperators
Posted: Fri Sep 22, 2017 4:15 am
by Lefteris
Since the extension java is not allowed I copied-pasted the code
public class IncOpPrecedence {
public static void main(String args[]) {
int x = 3;
int y = ++x * 5 / x-- + --x;
System.out.println(x+" "+y);
}
}
Re: Precedence of increment ooperators
Posted: Fri Sep 22, 2017 4:25 am
by admin
By source, I meant the website or the book from where you got it.
In any case, no, post-increment does not have higher precedence than pre-increment. But precedence is not the only thing that governs the evaluation of an expression. Expression evaluation is governed by precedence as well as associativity. This article explains it nicely -
http://cs-fundamentals.com/java-program ... tivity.php
HTH,
Paul.
Re: Precedence of increment ooperators
Posted: Fri Sep 22, 2017 4:37 am
by Lefteris
Thank you for your reply.
The source is OCA: Oracle® Certified Associate Java®SE 8 Programmer by Jeanne Boyarsky and Scott Selikoff, Page 52, Table 2.1.