aspose file tools*
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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Operators and Assignments" Watch "Operators and Assignments" New topic
Author

Operators and Assignments

Dilip Nedungadi
Greenhorn

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...
//LangSpecs.java
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
Dilip,
u will get the answer from the link below.
http://www.javaranch.com/ubb/Forum24/HTML/003185.html
You will get more additional information if u keep digging the old discussions by searching.
Smitha Krishna
Greenhorn

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
Greenhorn

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

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.
Basically,
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
Sheriff

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
http://www.javaranch.com/ubb/Forum24/HTML/001303.html
http://www.javaranch.com/ubb/Forum24/HTML/001715.html
Hope that helps,
Ajith


Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
 
jQuery in Action, 2nd edition
 
subject: Operators and Assignments