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

# primitive value

Ranch Hand
Posts: 486
• Number of slices to send:
Optional 'thank-you' note:

Line 1 print statement is printing 1 only. but I am getting the answer 2.obviously, inside the method m1 ,we can get class variable value 1.after executing x=x++ ,in the stack one new x variable is created with 2 value.How come it is giving 1 value after the execution of x++.

author
Posts: 23949
142
• Number of slices to send:
Optional 'thank-you' note:
http://faq.javaranch.com/view?PostIncrementOperatorAndAssignment

Ranch Hand
Posts: 2412
• Number of slices to send:
Optional 'thank-you' note:
In x = x++, the increment is discarded because the assignment happens after the increment.

Ranch Hand
Posts: 41
• Number of slices to send:
Optional 'thank-you' note:
The first value of x is 1.

x=x++;

What we are doing here.....value of x is 1 and we are assigning this 1 value to x and after that we are increasing the value of old x to 2 and discarding that value (not assigning to any variable), So the value of x will be 1 only. If you will do like...

x=++x; // then value of x will be 2.

Greenhorn
Posts: 26
• Number of slices to send:
Optional 'thank-you' note:
Hi I changed the code as below and now it prints 2. Can some one explain me how postincrement is working in this case?

Ranch Hand
Posts: 109
• Number of slices to send:
Optional 'thank-you' note:

Keith Lynn

In x = x++, the increment is discarded because the assignment happens after the increment.

Keith, I think it is the assignment that happens before incrementing x value.

Greenhorn
Posts: 8
• Number of slices to send:
Optional 'thank-you' note:

System.out.println(x + "," + y); // now output will be 2,3

But i am getting the output as 1,3 not 2,3

 Consider Paul's rocket mass heater.