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'?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With