• Post Reply Bookmark Topic Watch Topic
  • New Topic

variables

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hai,
i want why hte output is different in java for the below code
---
int a=2;
a=a++;
System.out.println(a);
---
the output is 2
why
&how the code is executed(i want some algorithem)

 
George Brown
Ranch Hand
Posts: 919
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is to do with the precedence. If you try using the pre-increment operator instead:
<pre>
int a = 2 ;
a = ++a ;
System.out.println( a ) ;
</pre>
the output is 3, as you would expect. I remember that in various C++ reference books there was a certain amount of 'good practice' advice where the recommendation was to use the pre-increment operator wherever possible, to avoid confusion. I'll try to explain:
In your code, if you had written:
<pre>
int a = 2;
a++;
System.out.println( a );
</pre>
That would have worked. However, by using the line:
<pre>a = a++ ;</pre>
you are prone to precedence issues.
I admit that this can be confusing. If you wanted to avoid using the unary operators, you could skip the ambiguity by writing:
<pre>a = a + 1 ;</pre>
I hope that helps.
[This message has been edited by George Brown (edited September 28, 2000).]
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank u very much
srinivasan.e
 
scott irwin
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int a = 0;
a = a++;
The post uniary operator ++ is above the = operator in precedence. So first evaluate the right side (a is 0). That's your value to be assigned to the left when we are done. Now apply the post ++ operator (a becomes 1). Now perform the = assignment from the evaluated statement (a = 0). So, 'a' was increamented but on assignment (done last) it is set back to the evaluated value of 0.
 
What are you doing? You are supposed to be reading this tiny ad!
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!