Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java static scoping

Tags:

java

I have the following piece of code that is taken from a mock exam for Sun Certified Java Programmer:

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

The test asks you for the result of this line:

System.out.println(x + y + ++x);

The answer is 3, but I don't completely understand why it is 3. I can arrive at that answer if I completely ignore:

      static 
      { 
            int x = 5; 
      }

My question is, what is the meaning of the above code snippet? Why does it not change the value of the variable 'x'?

like image 818
czchlong Avatar asked Apr 30 '12 17:04

czchlong


1 Answers

that's a static initialization block. but that doesn't really matter in this context since it's modifying the value of a variable local to it.

like image 132
user1329572 Avatar answered Nov 09 '22 16:11

user1329572