Meaningless Drivel is fun!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes variables 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 "variables" Watch "variables" New topic


Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
i want why hte output is different in java for the below code
int a=2;
the output is 2
&how the code is executed(i want some algorithem)

George Brown
Ranch Hand

Joined: Sep 26, 2000
Posts: 919
This is to do with the precedence. If you try using the pre-increment operator instead:
int a = 2 ;
a = ++a ;
System.out.println( a ) ;
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:
int a = 2;
System.out.println( a );
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).]
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
thank u very much
scott irwin
Ranch Hand

Joined: Aug 07, 2000
Posts: 87
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.
I agree. Here's the link:
subject: variables
It's not a secret anymore!