static block in java

Java Programming Language Class, Object and Methods in java (Article) Class, Object and Methods in java (Program)

1065

Program:

 class StaticBlock{

  static{
	  System.out.println("i am inside of static block ");
	  }

  public static void main(String args[]){
   System.out.println("Hello in main");
  }
}

Output:

i am inside of static block
Hello in main
Press any key to continue . . .

Explanation:

Why Use Static Blocks?

Static blocks are useful for initializing static variables or performing setup tasks that are required once per class loading. For example, you might use a static block to establish a database connection or to load a configuration file.

In this specific example, the static block is used simply to demonstrate that it executes before the main method.

Explanation

  1. Class Definition:

    • class StaticBlock defines a class named StaticBlock.
  2. Static Block:

    • The static block is a block of code that gets executed when the class is first loaded into the JVM (Java Virtual Machine). It runs only once, before the main method or any other methods in the class.
    • static { System.out.println("I am inside of static block"); } is the static block in this class. It contains a single statement that prints a message to the console.
  3. Main Method:

    • public static void main(String args[]) { System.out.println("Hello in main"); } is the main method, which serves as the entry point of the program. It prints "Hello in main" to the console.

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.