1

I was going through an exercise in Head First Java. It has the following code :

static {
System.out.println("Super constructor block");
}

i dont get the static modifier that is before the curly braces. What is it called? I know static variables etc. I tried searching online but couldn't get an answer. Thanks.

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
VistaAlta
  • 11
  • 1

3 Answers3

5

It is called a static initialization block. See https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html:

A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword.

It executes once the class is loaded by the JVM.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
M A
  • 71,713
  • 13
  • 134
  • 174
1

This is a static block not static method.

  • static blocks are different than static methods.

  • static blocks need not be called and are automatically executed. static blocks insure that they are only called once, When the class gets loaded.

  • static blocks can be written anywhere in the class, before execution compiler will combine all static blocks and execute at once on class load.

  • You can only initialize/access static variables/methods in a static block. Which means you cannot access non-static variables inside a static block, same as with a static method.

  • As static methods can be called more than once unlike blocks, which makes methods reusable, which is downside of blocks.

  • Static blocks are normally used to initialise static variables or do other calculations which are needed before a class instance is created or any static field is accessed..

For more information, refer to these links:

JavaCode.in

Oracle Docs

Asif Mujteba
  • 4,596
  • 2
  • 22
  • 38
1

This is called "static block". It is executed only once: the first time you make an object of that class or the first time you access a static member of that class (even if you never make an object of that class). See this link

Mohammed
  • 43
  • 7