• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

SCJP Mock Question : static

 
Mainak Goswami
Ranch Hand
Posts: 52
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Please find below the code:
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;
}

}
Output is 3.
Can anyone please explain me the flow and why the output is 3?
Actually according to me the static variables x and Y are initialized to 0.After that when the static block runs the value of x is modified to 5.
As per the flow goes the answer should be 15.
Thanks in advance.
 
Gaurav Bhatia
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The static block is declaring a new local variable (scope : within static block) and initializing it to 5.
The static variable 'x' is still 0 (after static block execution).

So, using that value of x if you calculate the result will be printed as 3.

Hope this clarifies.
 
Umesh Patil
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

This is my first reply on this site, Sorry if i have done some mistake. please check the code.


public class Static {
static{
int x=5;// Define in static block But we are not setting value to static class member.
}
static int x,y;// Initial values x=0 y=0
public static void main(String args[]){
x--;// x=-1 now
myMethod();// Here x=1 and y=0
System.out.println(x+y+ ++x);// 1+0+(2) == 4
}
public static void myMethod(){
y=x++ + ++x;////y= -1 + 1 = 0

}
}
 
Mainak Goswami
Ranch Hand
Posts: 52
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Many thanks to Gaurav and Umesh. My doubt is clear now.
 
O. Ziggy
Ranch Hand
Posts: 430
Android Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Umesh Patil:
Hi ,

This is my first reply on this site, Sorry if i have done some mistake. please check the code.


public class Static {
static{
int x=5;// Define in static block But we are not setting value to static class member.
}
static int x,y;// Initial values x=0 y=0
public static void main(String args[]){
x--;// x=-1 now
myMethod();// Here x=1 and y=0
System.out.println(x+y+ ++x);// 1+0+(2) == 4
}
public static void myMethod(){
y=x++ + ++x;////y= -1 + 1 = 0

}
}


Dont you mean 3 as the answer?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic