Precedence of increment ooperators

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
Lefteris
Posts: 4
Joined: Wed Sep 13, 2017 2:48 am
Contact:

Precedence of increment ooperators

Post 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?

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Precedence of increment ooperators

Post by admin »

Please post the source of the code.
If you like our products and services, please help us by posting your review here.

Lefteris
Posts: 4
Joined: Wed Sep 13, 2017 2:48 am
Contact:

Re: Precedence of increment ooperators

Post 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);
}
}

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Precedence of increment ooperators

Post 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.
If you like our products and services, please help us by posting your review here.

Lefteris
Posts: 4
Joined: Wed Sep 13, 2017 2:48 am
Contact:

Re: Precedence of increment ooperators

Post 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.

Post Reply

Who is online

Users browsing this forum: No registered users and 52 guests