• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

i=i++ and s=i++

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
anybody explain me why output like that?
1.class Test{
public static void main(String args[])
{
int i=0;
i=i++;
System.out.println(i);//0
i=i++;
System.out.println(i);//0
i=i++;
System.out.println(i);//0
}
}

2.class Test{
public static void main(String args[])
{
int i=0,s;
s=i++;
System.out.println(i);//1
s=i++;
System.out.println(i);//2
s=i++;
System.out.println(i);//3
}
}
 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
This is something to do with operator precedence.
First to be eveluated is ++ and last to be evaluated is =
the assignment operator.
let us take the case of
i = i++;
since = has least precedence the RHS ( Right Hand Side ) expression is to be evaluated first.
which is i++; here first it returns the val if i ( i == 0 ) first and then increments i to i+1 i.e i =1 ;
and finally when it is evaluating '=' operator it assigns zero to i; so i finally becomes zero ( i == 0 )
Now this set of statements are repeated thrice in the code
and each time i is set to zero and hence it prints zero three times
coming to the case of s = i ++;
proceding similarly after first statement s = 0 and i =1
here i is not reset to zero as it is assigned to a different variable.
continuing similarly the after the second s = i++;
s = 1 and i = 2;
after third s = 2 and i = 3;
HTH
Sasidhar


[This message has been edited by sasi dhulipala (edited January 04, 2001).]
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
there are 2 things
1. ++ operator has precedence over = operator
2. i++ returns i and increases the value of i by 1
therefore i=i++ would set the value of i on the left hand side to i not i+1
and s=i++ would set s=i and i to i+1.
K Singh
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic