1

I saw the below code in one example, I unable to understand that what they doing and what they representing from same code

what is the meaning for below code in java

static 
{
    variable 1;
    variable 2;
    variable 3;
    variable 4;
}
Gnesh23
  • 39
  • 1
  • 8

2 Answers2

2

It's a static block.

static{
  System.out.print("Hello");
}

Property of static block: It executes before the execution of first static method.

Deepu--Java
  • 3,742
  • 3
  • 19
  • 30
1

Static blocks in Java

Unlike C++, Java supports a special block, called static block (also called static clause) which can be used for static initializations of a class. This code inside static block 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). For example, check output of following Java program. // filename: Main.java class Test { static int i; int j;

// start of static block
static {
    i = 10;
    System.out.println("static block called ");
}
// end of static block

}

class Main { public static void main(String args[]) {

    // Although we don't have an object of Test, static block is
    // called because i is being accessed in following statement.
    System.out.println(Test.i);
}

}

Output: static block called 10

Also, static blocks are executed before constructors. For example, check output of following Java program. // filename: Main.java class Test { static int i; int j; static { i = 10; System.out.println("static block called "); } Test(){ System.out.println("Constructor called"); } }

class Main { public static void main(String args[]) {

   // Although we have two objects, static block is executed only once.
   Test t1 = new Test();
   Test t2 = new Test();
}

}

Output:
static block called
Constructor called
Constructor called
Ashish Ratan
  • 2,838
  • 1
  • 24
  • 50