Java static block
Overview
A Java static block is a code block executed when the class is loaded into the main memory. A code block is a group of statements treated as a single unit. The JVM invokes this code only once when the class loader loads the class into the memory.
static block Syntax
The general syntax of the static block is as follows:
static {
// static code block statements
}
We can also call the block a static initializer block. The main purpose of the is to initialize the key static variables of the class. It is important to note that the block doesn’t accept any parameters and doesn’t return any values to the JVM.
The static block can only access the static fields of the class. It cannot access or refer to the non-static fields of the class.
Example
An example to illustrate the concept of the static {} block is shown below:
/* * Program to demo Java static block * Java Tutorials - www.TestingDocs.com */ public class StaticBlockDemo { static { System.out.println("In Static Block."); } public static void main(String[] args) { System.out.println("In Main method."); } }
We can notice that the static block is executed before the main method execution.
The static block can invoke other static methods. For example, the below example invokes a static method of the class.
/* * Program to demo Java static block * Java Tutorials - www.TestingDocs.com */ public class StaticBlockDemo { static { try { System.out.println("In Static Block."); delayMain(); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { System.out.println("In Main method."); } public static void delayMain() throws InterruptedException { Thread.sleep(1000*120);// 2 minutes delay } }
The main difference between static block and ordinary method is that the methods have return types and return values and control to the caller. Methods may or may not accept parameters. The programmer can invoke methods many times in the program code.
—
Java Tutorial
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :