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 Operator precedence and postfix operators Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Operator precedence and postfix operators" Watch "Operator precedence and postfix operators" New topic

Operator precedence and postfix operators

Ben Pracht

Joined: Jan 13, 2005
Posts: 4
In a table precedence in C++, I've seen the prefix and postfix operators shown in separate places. In the seemingly rare times when someone actually lists a precedence table in Java, they don't make that distinction. So I did a test:

public class ATest
static int i=1;
static int j=2;
public static void main(String args[])
int k=i+(j=i++); // Line in question

The line in question wouldn't compile when I left out the parenthesis, but with them it showed i=2 j=1 and k=2. Can I then assume it

1. Set j=1
2. Set k=i+j which is k=1+1 which is 2
3. Set i=i+1 which is i=2

Does this mean that it does the postfix operations after all the other assignments are done?

Anand Ko
Ranch Hand

Joined: Dec 03, 2003
Posts: 79
There is distinction in Java also for prefix and postfix.
Order of Precedence : postfix then prefix.

k = i + (j=i++) //

i++ //value of i is used and then incremented

Anand<br />SCJP 1.4, SCWCD 1.4, SCEA 5.0(1/3)
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
The rule is that operators are evaluated from left to right.

In the expression above

The expression i is evaluated to 1 first, then the whole parenthesis is evaluated, that would be (j=i++). So j is assigned the value 1 and after that it increments i to value 2. But the left most i had already been evaluated before. So k will evaluate to 2, and i would have already been incremented.

You can see that's true if you evaluate the expression this way:

This way you will see i is incremented before evaluating the right most operand.
Andris Jekabsons
Ranch Hand

Joined: Jan 20, 2004
Posts: 82
Originally posted by Ben Pracht:
The line in question wouldn't compile when I left out the parenthesis,

int k = i + j = i++; // the same as: // int k = ( i + j ) = i++;
is a multiple assignment statement that is assigning values for each variable from right to left in the form of:
a = b = c;
Then c has to evaluate to a value and is assigned to b, which has to be a variable (we cannot assign a value to another value), then the new value of the variable b is assigned to the variable a. In this example, however, ( i + j ) returns a value, not variable. A compiler notices that and won't compile.
I agree. Here's the link:
subject: Operator precedence and postfix operators
It's not a secret anymore!