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
• Liutauras Vilda
• Tim Cooke
• Jeanne Boyarsky
• Paul Clapham
Sheriffs:
• Devaka Cooray
• Ron McLeod
• paul wheaton
Saloon Keepers:
• Tim Moores
• Piet Souris
• Tim Holloway
• Stephan van Hulst
• Carey Brown
Bartenders:
• Al Hobbs
• Frits Walraven
• Scott Selikoff

# incrementor question

Greenhorn
Posts: 26
• Number of slices to send:
Optional 'thank-you' note:
public class Static
{
static
{
int x = 5;
}

static int x,y;
public static void main(String args[])
{
x--; myMethod();
System.out.println(x + y + ++x);
}

public static void myMethod()
{
y = x++ + ++x;
}
}

My question is why does "y" in myMethod evaluate to 0.

Happy Studying

Greenhorn
Posts: 25
• Number of slices to send:
Optional 'thank-you' note:
Lets Evaluate

static
{
int x = 5;
} this is block variable so wont matter.

static int x,y; here x = 0, y=0
x-- x is still 0 post operator --- @1
myMethod()
y = x++ + ++x;

here x++( would make x = -1 as the post o/p @1 would get result)
++x ( this would cause the previous x++ to give value (-1 + 1) 0 and then
-1 + 1 + 1= 1)

so y = -1 + 1 = 0

Hope this helps

Annette Sovereign
Greenhorn
Posts: 26
• Number of slices to send:
Optional 'thank-you' note:
here x++( would make x = -1 as the post o/p @1 would get result)

Hi there,

Thanks for responding.

I'm sorry I'm not sure I understand what the statement means. How x++ would make x become equal to -1 is a mystery to me. I was able to evaluate the expression to 0, but I'm not sure my reasoning is correct.

If someone can break it down, that would be great.

I'm trying to work out when the post increment operator on x is applied.

Happy Studying

Author
Posts: 84
• Number of slices to send:
Optional 'thank-you' note:
When myMethod is entered, the value of x is -1.

The order of evaluation on the y = x++ + ++x statement is as follows:

x++ - Pre-evaluation, x=-1. This expression will evaluate to -1, then set x=0.
++x - Pre-evaluation, x=0. x will be set to 1 with the pre-increment operator. The expression will then evaluate to 1.

So we have: y = -1 + 1, and thus y = 0. Hope that makes sense?

 You guys wanna see my fabulous new place? Or do you wanna look at this tiny ad? the value of filler advertising in 2021 https://coderanch.com/t/730886/filler-advertising