This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes increment Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "increment" Watch "increment" New topic
Author

increment

Sridhar Srinivasan
Ranch Hand

Joined: Nov 07, 2003
Posts: 117
Hi!
When I compile the following code I get the value as 1
public static void main(String[ ] args)
{

int k=0;
k += ++k;
System.out.println(k);
}
As per my understanding, bec's of operator precedence k becpomes 1 first and now k holds the value of 1 and then when we say k+=1 which is k=k+1(1+1) is 2.Why is it giving 1?Can anybody please explain.Thanks
[ May 18, 2004: Message edited by: Barry Gaunt ]

Software_guy
Jong Limb
Greenhorn

Joined: May 08, 2004
Posts: 12
k += ++k resolves to k = k + ++k. Taking the right hand side and evaluating left to right, you get k = 0 + ++(0). This resolves to k = 0 + 1; therefore k = 1.

Originally posted by Sridhar Srinivasan:
Hi!
When I compile the following code I get the value as 1
public static void main(String[ ] args)
{

int k=0;
k += ++k;
System.out.println(k);
}
As per my understanding, bec's of operator precedence k becpomes 1 first and now k holds the value of 1 and then when we say k+=1 which is k=k+1(1+1) is 2.Why is it giving 1?Can anybody please explain.Thanks
meeta verma
Greenhorn

Joined: May 15, 2004
Posts: 19
ya even i was expecting that .
Also

public static void main(String[ ] args)
{
int k=0;
k += ++k;
System.out.println(k);//1
k=0;
k=k+(++k);
System.out.println(k);//1

k=0;
k=++k +k;
System.out.println(k);//2
}
It seems as though left associativity is playing the role everywhere.
 
 
subject: increment