Skip to content
Related Articles

Related Articles

Class Loading and Static Blocks Execution Using Static Modifier in Java
  • Difficulty Level : Expert
  • Last Updated : 04 Dec, 2020

Static is a keyword which when attached to the method, variable, Block makes it Class method, class variable, and class Block. You can call a static variable/method using ClassName. JVM executes the static block at “CLASS LOADING TIME”

Execution Order:

There is an order in which static block/method/variable gets initialized. 

  1. Static Block
  2. Static Variable
  3. Static Method

Static Blocks are called even before the main method which is nothing but a static method i.e. execution point of every class. 

Note:



Sometimes, it is asked in interviews, to print “HELLO” without printing it inside main method or calling any method from main. Answer is to use Static block as they get initialized before main so you can use them to print anything without having any dependency on main Method in java.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Class Loading and Static Blocks
// Execution Using Static Modifier in Java
  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        // Created 3 Threads
        MyThread myThread1 = new MyThread();
        myThread1.start();
  
        MyThread myThread2 = new MyThread();
        myThread2.start();
  
        MyThread myThread3 = new MyThread();
        myThread3.start();
    }
}
  
class MyThread extends Thread {
    
    // Static Variable count is maintained across
    // all threads as it is only created once
    static int count = 0;
    
    // Non Static Variable count is maintained seprately
    // for seprate thread As non-static variables are
    // created for every thread
    int notStatic = 0;
    public void run()
    {
        count++;
        notStatic++;
        System.out.println("Thread = " + count);
        System.out.println("Non Static Variable Value="
                           + notStatic);
    }
}

chevron_right


Output

Thread = 3
Thread = 2
Non Static Variable Value=1
Thread = 1
Non Static Variable Value=1
Non Static Variable Value=1

Static Variable

You can use Static Variables to save memory or in an operation where you want all threads to maintain one variable instead of having a different variable for every thread.

Static Method

Used when methods are more relevant to class than an instance of a class. Math Class in java is a great example in Java. It has all the static Methods which you can call using a class name like max, min, pow as these functions do not require different objects to have different values. You can pass parameters and get answer using className.methodName() .

Static Block

Used when you want to initialize any data before the execution control goes to other methods like the main method.

Rules:

  1. Static Methods can only call other static methods i.e. you can not call a non-static method from a static method like the main method.
  2. Static block can use the only static variable directly

Singleton Design Pattern is the Most Widely used design pattern where only one instance of the class is created and returned for every instance request of class. The static keyword is used to make object creation only once as static occupy memory only once and hence synchronization is maintained for every call. 

Below is the example which clearly displays the order of execution. Static Block is called first even it is written after the main method. It proves Static Blocks are the first thing to get called even before the main method.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Class Loading and Static Blocks
// Execution Using Static Modifier in Java
  
import java.io.*;
  
class GFG {
  
    // Static Variable
    public static void main(String[] args)
    {
        System.out.println("Static Variable=" + count);
        System.out.println("Static Method");
    }
  
    // Static Variable
    static int count = 3;
  
    // Called even before Main Method
    static { System.out.println("Static Block"); }
}

chevron_right


Output

Static Block
Static Variable=3
Static Method

Real-Life Example: To append output to the same log file, one logger object is created, and using logger.info() data can be appended in order of insertion.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :