Java Static

I have the following code snippet taken from a mock exam for a 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 do not quite understand why this is 3. I can come up with this answer if I completely ignore it:

      static 
      { 
            int x = 5; 
      }

My question is: what is the meaning of the above code snippet? Why does this not change the value of the variable "x"?

+5
source share
5 answers

what is a static initialization block. but in this context it does not really matter, since it changes the value of a variable local to it.

+4
source

int x = 5;executed, but xhere is a local variable, not a member static int x.

+5
source

, , , { }. - ,

+1

It changes the value of a local variable with a name x, but not a static member field called x, that is, it is 0.

+1
source
Value

x is set to 5, but only in the context of a static block

static 
      { 
            int x = 5; 
      }

The variable x declared in static int x,y;has a class-level scope and depends on the rest of the code that references it.

0
source

All Articles