• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

post++ Operator: Doudt

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The following program prints 0, i thought it will print 1.
class Test {
public static void main(String []args) {
int x=0;
x=x++;
System.out.println(x);
}
}
But the following program prints as expected...
class Test {
public static void main(String []args) {
int x=0;
x++;
System.out.println(x);
}
}
Could some body explain in detail what is happening in detail.
Advance Thanks...
 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Hi,
The following program is prints 0 that's right.
Your being getting confused is also right...Its happens with every body in the starting
now see......
in your first prog.
class Test {
public static void main(String []args) {
int x=0;
x=x++; //Read like this x=x=(x+1) Here the operator is
postfix...thats why first it will assign the original valur of x(In your case x =0)to the
left side of x...and then it will increment the x by
Understand like this y = x = x+1;It will give x = 0 to y and then x itself will become 1; try to imagine y will be leading with value 0 and x trailing with 1;, in your case both x .. so two "x" are moving. so when ever you ask for value of x it will always print x =0; If you put for loop... in the next iteration first x will become 1 and trailing x will become 2....
x=x+1
.
.
.
.
x= x =0;///
System.out.println(x);
}
}
But in the following program ............here no y so only x will be carrying the value of 1;;; same as above. ..
class Test {
public static void main(String []args) {
int x=0;
x++;// The meaning is x = x+1...
System.out.println(x);
}
}

I am not sure about my explaining ability. But I always talk in the layman language....Hope it will solve your purpose
Amit
 
This tiny ad is guaranteed to be gluten free.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic