• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

increment

 
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Those cherries would go best on cherry cheesecake. Don't put those cherries on this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic