Static Block - rahul00773/JavaConcepts GitHub Wiki

Static Blocks will be executed at the time of class loading. Hence At the time of class loading if we want to perform any activity we have to define that inside a static block.

Example 1. :

At the time of java class loading, the corresponding native library should be loaded. Hence we have to define this activity inside the static block.

class Test{

static{

System.loadLibrary(“Native Library path”);

} }

Example2:

After loading every database driver class. We have to register class with driver manager But inside the database driver class, there is a static block to perform this activity. And we are not responsible to register explicitly.

class DBDriver{

static{ “Register this driver with driver manager” } }

Note: In a class, we can declare any number of static blocks but all these static blocks will be executed from top to bottom.

Q1. Without writing the main method is it possible to print some statements to the console. Ans: By using static block

class Test{

static{

System.out.println(“Hello I can print..”); System.exit(0); }

}

Q2.; Without writing the main method and the static block is it possible to print Some Statements to the console. Ans: Yes. Of course, there are multiple ways.

class Test{

static int x = m1();

public static int m1(){

System.out.println(“Hello I can print”); System.exit(0); return 10;

}

}

class Test{ static int x = new Test(); { System.out.println(“Hello I can print”); System.exit(0); }

}

class Test{ static int x = new Test(); Test() { System.out.println(“Hello I can print”); System.exit(0);

} }

Note: From 1.7 version onwards the main method is mandatory to start program execution. Hence from 1.7 version onwards without writing the main method, it is impossible to print some statements to the console