Java | static blocks

|
| By Webner

Static Blocks: Static block is used to initialize the static data members. It is executed before main method and constructor at the time of classloading. A class can have any number of static initialization blocks and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

Syntax:

static {
//  initialization  of  static data member here
}

Example of static block:

public class Static_Block {
static {
System.out.println("Static block is invoked.");
}
public static void main(String[] arg) {
System.out.println("\n Inside the Main.");
}
}

Output:
Static block is invoked.
Inside the Main.

Can we execute a program without main() method?

Yes, with the help of static block (not supported after jdk 1.7).

For Example:

public class Without_Main {
static {
System.out.println("static block  is invoked");
System.exit(0); //without exit() java compiler returns warning message
    }
}

Note: The above program runs up to jdk7 not in higher versions. In Jdk 8 and above, output will be:

Output:

Error: Main method not found in class.

Can you create new objects and call other static and non-static functions in a static block?

Yes, it is possible to call static functions but not the nonstatic functions in static block. If you want to call non-static method then first create a new object in the static block.

Leave a Reply

Your email address will not be published. Required fields are marked *