-2

Code looks like this:

class AX {
      static int[] x = new int[0];
      static {
          x[0] = 10;
      }
}

I have never seen the use of static{} before. What is this? A method?

Tom
  • 16,842
  • 17
  • 45
  • 54
OPK
  • 4,120
  • 6
  • 36
  • 66
  • This is a static initialiser block. See http://stackoverflow.com/questions/15246343/why-would-i-use-static-initialization-block-in-java – NPE Dec 25 '14 at 19:38

1 Answers1

1

It's code that runs when the class initializes.

When the class is loaded and initialized, all the static blocks and initializers are run. This includes all the lines like this

static int[] x = new int[0];

that initialize a static field, and all the bits like this

static{
      x[0] = 10;
}

that can contain more or less arbitrary code for initializing things.

They get run in the order that they appear in the source code.

chiastic-security
  • 20,430
  • 4
  • 39
  • 67