• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please help

 
prerna boja
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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;
}
}

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
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic