Java Empty Block Area

I am wondering what the purpose of using an empty block is. For instance,

    static{
        int x = 5;
    }

    public static void main (String [] args){

          int i = 10;

          {
               int j = 0 ;
               System.out.println(x);  // compiler error : can't find x ?? why ??
               System.out.println(i);  // this is fine
          }
          System.out.println(j); //compiler error :  can't find j

    }

Can someone explain

  • In what situation do we want to use an empty block.
  • Are all the variables inside this empty block still going on stack?
  • Why was he unable to access static variable x?
+5
source share
3 answers
  • The block that you show in your message is not an empty block, it is a static initializer. It is used to provide non-trivial initialization for the static variables of your class.
  • The local variables that you use during initialization go on the stack, with the exception of objects that you allocate from the heap
  • x, . x .

x , :

private static int x;
static {
    x = 5;
}

:

private static int x = 5;

, , :

private static List<List<String>> x = new ArrayList<List<String>>();
static {
    for (int i = 0 ; i != 10 ; i++) {
        x.add(new ArrayList<String>(20));
    }
}
+3
  • ; .
  • , .
  • x , ​​ ( ), .
+3

, .

static final Map<K, V> MY_MAP = ...;

static {
  MY_MAP.put(...);
  ...
}

?

, , , . @veer, , VM.


main x?

, static.

+2

All Articles