Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Beginning Java and the fly likes Please help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Please help " Watch "Please help " New topic

Please help

prerna boja
Ranch Hand

Joined: Aug 19, 2004
Posts: 67

public class 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;

For the above program When I solve on the paper I am gettting the output as 24 but the IDE shows as the output is 3.
Please help me to solve the pb.
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
I can tell you what is happening, but I'm not sure on the specifics of why.

First x is initialized by the system to 0.

Then x-- makes x = -1
then myMethod is called as y = 0 + 0 and x gets post incremented to 1
then you have System.out.println(1 + 0 + 2)

the static x=5 block isn't involved
Joel McNary

Joined: Aug 20, 2001
Posts: 1824

Steven's almost correct -- except it's not that the static block isn't invoked, it's that its declaring its own version of x, one that has nothing to do with the Static.x variable.

(Oh, and y = -1 + 1, not 0 + 0...)

Change the static block to read

and you will get a result of 23, arrived as such:

x = 5;
decrement x to 4
y = 4 + 6 (10) (x = 4, post-increment x to 5, pre-increment x to 6, add 4 and 6 together to get 10, and x is set at 6).
print 6 + 10 + 7 (23)

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
Technically I didn't say that the static block wasn't invoked, I said it wasn't involved, but I did miss the fact that it creates it's own version.

Must pay better attention to things like that.
I agree. Here's the link:
subject: Please help
It's not a secret anymore!