This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Operators and Assignments

 
Dilip Nedungadi
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 45
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please ignore the explanation in my previous mail. Should have given more thought before posting.
 
Velmurugan
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5782
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic