Two Laptop Bag
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Operators and Assignments 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 "Operators and Assignments" Watch "Operators and Assignments" New topic

Operators and Assignments

Dilip Nedungadi

Joined: Jun 23, 2000
Posts: 3
Please see the code below. The code runs and displays 0 as output, even though the Print command is called after the line x = x++; have executed completely. I was expecting 1 as output. Please help...
public class LangSpecs
public static void main(String[] args)
int x = 0;
x = x++;
System.out.println("Value of x is : " +x);
Anbooo Sanygao
Ranch Hand

Joined: Oct 04, 2000
Posts: 45
u will get the answer from the link below.
You will get more additional information if u keep digging the old discussions by searching.
Smitha Krishna

Joined: Oct 06, 2000
Posts: 4
Guess it is because the ++ operator has precedence over the assignment operator.
The operation in the code would be performed in the following
sequence :
Increments op by 1; evaluates to the value of op before it was incremented
So, if the assignment is made to the same variable the change is overridden. But, if the assignment y = x++ would work as expected by you.

Smitha Krishna

Joined: Oct 06, 2000
Posts: 4
Please ignore the explanation in my previous mail. Should have given more thought before posting.

Joined: Oct 11, 2000
Posts: 5
Change the postfix operator to prefix operator and try it. That will give you a clue about what's going on.
1. Operands are evaluated from left to right, and the operations are performed in the order of precedence and associativity.
2. ++ operator is one of the operators which are very high in the precedence level. = is one of the lowest.
Hope this helps.
Ajith Kallambella

Joined: Mar 17, 2000
Posts: 5782
This is a favourite topic in the SCJP forum. Though you may not get such questions in the exam, it is fun to figureout what's happening here
Look at the two of our old discussions
Hope that helps,

Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
I agree. Here's the link:
subject: Operators and Assignments
It's not a secret anymore!