code: com.java.basics.App01
public class App01 {
public static void main(String[] args) {
System.out.println("Hello World");
}
}compile: javac App01.java
run: java App01
output: Hello World
Java has 2 types of blocks.
- static blocks
(executed without object creation during class load time only) - non-static(instance) blocks.
(executed every time an object created)
code: com.java.basics.App02
- A block
{}prefixed with the keywordstatic. - Always executes whenever the class is loaded.
- Execution of static block does not dependent on the object creation.
- Static blocks execute in order of declaration.
public class App02 {
static {
System.out.println("static block 1");
}
static {
System.out.println("static block 2");
}
public static void main(String[] args) {
}
}- When we run above program the class gets loaded and as a result the static blocks executed in order.
output:
static block 1
static block 2
code: com.java.basics.App03
- Static blocks always execute before the execution of main method.
- The signature of main method is `public static void main(String[] args)
public class App03 {
static {
System.out.println("static block 1");
}
static {
System.out.println("static block 2");
}
public static void main(String[] args) {
System.out.println("from main method");
}
}output:
static block 1
static block 2
from main method