Open In App

Static Blocks in Java

Last Updated : 10 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In simpler language whenever we use a static keyword and associate it to a block then that block is referred to as a static block. Unlike C++, Java supports a special block, called a static block (also called static clause) that can be used for static initialization of a class. This code inside the static block is executed only once: the first time the class is loaded into memory. 

Calling of static block in java?

Now comes the point of how to call this static block. So in order to call any static block, there is no specified way as static block executes automatically when the class is loaded in memory. Refer to the below illustration for understanding how static block is called.

Illustration:

class GFG {

        // Constructor of this class
        GFG() {}
        
        // Method of this class
        public static void print() { }
        
        static{}

        public static void main(String[] args) {

                // Calling of method inside main()
                GFG geeks = new GFG();

                // Calling of constructor inside main()
                new GFG();

                // Calling of static block
                // Nothing to do here as it is called
                // automatically as class is loaded in memory

        }
}

Note: From the above illustration we can perceive that static blocks are automatically called as soon as class is loaded in memory and there is nothing to do as we have to in case of calling methods and constructors inside main(). 

Can we print something on the console without creating main() method?

It is very important question from the interview’s perceptive point. The answer is yes we can print if we are using JDK version 1.6 or previous and if after that  it will throw an. error. 

Example 1-A:  Running on JDK version 1.6 of Previous

Java




// Java Program Running on JDK version 1.6 of Previous
 
// Main class
class GFG {
   
    // Static block
    static
    {
        // Print statement
        System.out.print(
            "Static block can be printed without main method");
    }
}


Output:

Static block can be printed without main method

Example 1-B: Running on JDK version 1.6 and Later

Java




// Java Program Running on JDK version 1.6 and Later
 
// Main class
class GFG {
   
    // Static block
    static
    {
        // Print statement
        System.out.print(
            "Static block can be printed without main method");
    }
}


Output: 

Execution of Static Block

Example 1:

Java




// Java Program to Illustrate How Static block is Called
 
// Class 1
// Helper class
class Test {
 
    // Case 1: Static variable
    static int i;
    // Case 2: non-static variables
    int j;
 
    // Case 3: Static block
    // Start of static block
    static
    {
        i = 10;
        System.out.println("static block called ");
    }
    // End of static block
}
 
// Class 2
// Main class
class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Although we don't have an object of Test, static
        // block is called because i is being accessed in
        // following statement.
        System.out.println(Test.i);
    }
}


Output

static block called 
10

Remember: Static blocks can also be executed before constructors.

Example 2:

Java




// Java Program to Illustrate Execution of Static Block
// Before Constructors
 
// Class 1
// Helper class
class Test {
 
    // Case 1: Static variable
    static int i;
    // Case 2: Non-static variable
    int j;
 
    // Case 3: Static blocks
    static
    {
        i = 10;
        System.out.println("static block called ");
    }
 
    // Constructor calling
    Test() { System.out.println("Constructor called"); }
}
 
// Class 2
// Main class
class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Although we have two objects, static block is
        // executed only once.
        Test t1 = new Test();
        Test t2 = new Test();
    }
}


Output

static block called 
Constructor called
Constructor called

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.

Note: We use Initializer Block in Java if we want to execute a fragment of code for every object which is seen widely in enterprising industries in development. 



Previous Article
Next Article

Similar Reads

Class Loading and Static Blocks Execution Using Static Modifier in Java
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. Static BlockStatic Vari
3 min read
What is Class Loading and Static Blocks in Java?
Class Loading is the process of storing the class-specific information in the memory. Class-specific information means, information about the class members, i.e., variables and methods. It is just like that before firing a bullet, first, we need to load the bullet into the pistol. Similarly, to use a class first we need to load it by a class loader
3 min read
Illustrate Class Loading and Static Blocks in Java Inheritance
Class loading means reading .class file and store corresponding binary data in Method Area. For each .class file, JVM will store corresponding information in Method Area. Now incorporating inheritance in class loading. In java inheritance, JVM will first load and initialize the parent class and then it loads and initialize the child class. Example
3 min read
Understanding "static" in "public static void main" in Java
Following points explain what is "static" in the main() method: main() method: The main() method, in Java, is the entry point for the JVM(Java Virtual Machine) into the java program. JVM launches the java program by invoking the main() method. Static is a keyword. The role of adding static before any entity is to make that entity a class entity. It
3 min read
Difference between static and non-static method in Java
A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class. Every method in java defaults to a non-static method without static keyword preceding it. Non-static methods can access any static method and static variable, without cr
6 min read
Difference between static and non-static variables in Java
There are three types of variables in Java: Local VariablesInstance VariablesStatic Variables The Local variables and Instance variables are together called Non-Static variables. Hence it can also be said that the Java variables can be divided into 2 categories: Static Variables: When a variable is declared as static, then a single copy of the vari
4 min read
Why non-static variable cannot be referenced from a static method in Java
Java is one of the most popular and widely used programming language and platform. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In java, methods can be declared as either static or non-static. In this article, let's discuss why non-static vari
4 min read
Difference Between Static and Non Static Nested Class in Java
Nested classes are divided into two categories namely static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes. A class can either be static or non-static in java. So there is a lot of difference between making a class static or non-static. There are two kind
4 min read
Static and non static blank final variables in Java
A variable provides us with named storage that our programs can manipulate. There are two types of data variables in a class: Instance variables : Instance variables are declared in a class, but outside a method, constructor or any block. When a space is allocated for an object in the heap, a slot for each instance variable value is created. Instan
5 min read
Understanding storage of static methods and static variables in Java
In every programming language, memory is a vital resource and is also scarce. Hence the memory must be managed thoroughly without any leaks. Allocation and deallocation of memory is a critical task and requires a lot of care and consideration. In this article, we will understand the storage of static methods and static variables in Java. Java Virtu
6 min read
Using Instance Blocks in Java
The instance block can be defined as the name-less method in java inside which we can define logic and they possess certain characteristics as follows. They can be declared inside classes but not inside any method. Instance block logic is common for all the objects. Instance block will be executed only once for each object during its creation. Illu
3 min read
Text Blocks in Java 15
In this article, we are going to discuss the Java 15 text blocks feature to declare multi-line strings most efficiently. We all know that how we can declare multi-line strings and that too quite easily with the help of concatenation, string's join method, StringBuilder append method, etc. Now the question will arise in our mind that if everything i
3 min read
Order of execution of Initialization blocks and Constructors in Java
Prerequisite : Static blocks, Initializer block, Constructor In a Java program, operations can be performed on methods, constructors and initialization blocks. Instance Initialization Blocks : IIB are used to initialize instance variables. IIBs are executed before constructors. They run each time when object of the class is created. Initializer blo
4 min read
Nested try blocks in Exception Handling in Java
In Java , we can use a try block within a try block. Each time a try statement is entered, the context of that exception is pushed onto a stack. Given below is an example of a nested try. In this example, the inner try block (or try-block2) is used to handle ArithmeticException, i.e., division by zero. After that, the outer try block (or try-block)
3 min read
Comparison of static keyword in C++ and Java
Static keyword is used for almost the same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java. Similarities between C++ and Java for Static KeywordStatic data members can be defined in both languages.Static member functions can be defined in both languages
6 min read
Can we Overload or Override static methods in java ?
Let us first define Overloading and Overriding. Overriding: Overriding is a feature of OOP languages like Java that is related to run-time polymorphism. A subclass (or derived class) provides a specific implementation of a method in the superclass (or base class). The implementation to be executed is decided at run-time and a decision is made accor
5 min read
Static Control Flow in Java
Static Control Flow decides the sequence of activities/steps that will be executed in order when we run a java class that contains static variables, methods, and blocks. This article will explain how static control flow occurs whenever a Java program is executed. Prerequisite: Static Blocks The Static Control Flow mechanism performs the following 3
4 min read
Static method in Interface in Java
Static Methods in Interface are those methods, which are defined in the interface with the keyword static. Unlike other methods in Interface, these static methods contain the complete definition of the function and since the definition is complete and the method is static, therefore these methods cannot be overridden or changed in the implementatio
2 min read
Static Block and main() method in Java
In Java static block is used to initialize the static data members. Important point to note is that static block is executed before the main method at the time of class loading. This is illustrated well in the following example: // Java program to demonstrate that static // block is executed before main() class staticExample { // static block stati
2 min read
Why can't static methods be abstract in Java?
In Java, a static method cannot be abstract. Doing so will cause compilation errors.Example: Java Code // Java program to demonstrate // abstract static method import java.io.*; // super-class A abstract class A { // abstract static method func // it has no body abstract static void func(); } // subclass class B class B extends A { // class B must
3 min read
Initialize a static map in Java with Examples
In this article, a static map is created and initialized in Java. A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Method 1: Creating a static map variable. Instantiating it in a static block. Below is the implementation of the above approach: // Java program to creat
1 min read
Initialize a static Map using Stream in Java
In this article, a static map is created and initialized in Java using Stream. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Stream In Java Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of
2 min read
Initialize a static Map using Java 9 Map.of()
In this article, a static map is created and initialised in Java using Java 9. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Java 9 feature - Map.of() method In Java 9, Map.of() was introduced which is a convenient way to create instances of Map
2 min read
Initialize a static Map in Java using Double Brace Initialization
In this article, a static map is created and initialised in Java using Double Brace Initialization. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Double Brace Initialization In Double Brace Initialization: The first brace creates a new Anonymous
2 min read
Constructor Overloading with Static Block in Java
In Java, Constructor is a block of codes similar to the method that is used to initialize the object’s state. A constructor is invoked at the time of object or instance creation. Each time an object is created using a new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of
4 min read
Why a Constructor can not be final, static or abstract in Java?
Prerequisite: Inheritance in Java Constructor in java is a special type of method which is different from normal java methods/ordinary methods. Constructors are used to initialize an object. Automatically a constructor is called when an object of a class is created. It is syntactically similar to a method but it has the same name as its class and a
6 min read
Using Static Variables in Java
Here we will discuss the static variables in java. Java actually doesn’t have the concept of Global variable. To define a Global variable in java, the keyword static is used. The advantage of the static variable is discussed below. Now geeks you must be wondering out what are the advantages of static variable, why to incorporate in our program. Now
3 min read
Difference Between Constructor and Static Factory Method in Java
Whenever we are creating an object some piece of code will be executed to perform initialization of that object. This piece of code is nothing but a constructor, hence the main purpose of the constructor is to perform initialization of an object but not to create an object. Let us go through the basic set of rules for writing a constructor. They ar
4 min read
Difference Between Singleton Pattern and Static Class in Java
Singleton Pattern belongs to Creational type pattern. As the name suggests, the creational design type deals with object creation mechanisms. Basically, to simplify this, creational pattern explains to us the creation of objects in a manner suitable to a given situation. Singleton design pattern is used when we need to ensure that only one object o
6 min read
Java - Calling Non Static Members Directly From Constructor Without Using the Object Name
Java is an Object-Oriented Programming(OOP) language. We need to create objects in order to access methods and variables inside a class. However, this is not always true. While discussing static keywords in java, we learned that static members are class level and can be accessed directly without any instance. Here we will be discussing how we can a
3 min read
Article Tags :
Practice Tags :