Scientech Easy Static Block in Java | Example Program & Advantage | Scientech Easy

Tuesday, September 18, 2018

Static Block in Java | Example Program & Advantage

Static Block in Java

Static block is the group of statements that gets executed only once when the class is loaded into the memory by Java ClassLoader.
Syntax of the static block is
    static {
                 // Logics here or group of statements.
               
               }

Why static block is executed before the main method?


When we execute a particular class, JVM performs two actions at the runtime.
1. JVM loads the corresponding dot class file (bytecode) into memory.
2. During the dot class file loading into memory, the static blocks are executed. After the loading dot class file, JVM calls the main method to start execution. Therefore, the static block is executed before the main method. In other words, we can also say that Static block always gets executed first in Java because they are stored in the memory at the time of class loading or before the object creation.

How many times dot class file is loaded into the memory?


Dot class file is loaded into the memory only one time. That is only one time the static blocks will be executed.
Always Remember:
Instance block's execution depends upon the object creation. If we create 10 objects, 10 times instance blocks will be executed but the static block's execution depends upon the class loading. Since the class is loaded only one time So static blocks will be executed only one time. 
Program source code 1:
    package com.scientecheasy; public class StaticBlockTest { //Declare two instance blocks. { System.out.println("Instance block-1"); } { System.out.println("Instance block-2"); } // Declare two static blocks. static { System.out.println("Static block-1"); } static{ System.out.println("Static block-2"); } // Declare zero parameter constructor. StaticBlockTest(){ System.out.println("0-arg constructor"); } // Declare one parameter constructor with int parameter named a. StaticBlockTest(int a){ System.out.println("1-arg constructor"); } public static void main(String[] args) { // Create the object of the class. new StaticBlockTest(); // Nameless object. // Create another object of the class and pass the integer argument value. new StaticBlockTest(20); // Nameless object. } }
    Output: Static block-1 Static block-2 Instance block-1 Instance block-2 0-arg constructor Instance block-1 Instance block-2 1-arg constructor
In this example, We have declared two instance blocks, two static blocks, two constructors, and created two objects. Since we have created two objects. So instance blocks will execute two times but the dot class file is loaded only one time into the memory. Therefore, only a one-time static block will be executed.
Always Remember:
Instance block and constructor both are executed during the object creation but the instance block will execute first before the execution of the constructor during the object creation.


Order of execution of multiple Static blocks in Java


A class can have multiple static blocks that will execute in the same sequence as written in the program. That is the order of execution of multiple static blocks will be executed automatically from top to bottom during the dot class file loading.
Program source code 2:
    package com.scientecheasy; public class MultipleStaticBlocks { { System.out.println("Instance block-1"); } { System.out.println("Instance block-2"); } static{ System.out.println("Static block-1"); } static{ System.out.println("Static block-2"); } public static void main(String[] args) { new MultipleStaticBlocks(); } }
static block in java with example program and advantages, java static block, why static block executed first in java, use of static block in java.
Flow of Execution in multiple Static blocks

    Output: Static block-1 Static block-2 Instance block-1 Instance block-2

Can we execute static block without a main method inside the class?


It is possible to execute the static block without a main method inside the class up to Java 1.5 version but Java 1.6 version onwards, the main method is mandatory to execute a static block inside the class. During the dot class file loading, First, static blocks are executed and then JVM calls the main method. Let's see an example program. 
Program source code 3:
    package com.scientecheasy; public class Test { static{ System.out.println("Hello Java"); } static{ System.out.println("Welcome you"); } }
    Error: Main method not found in class staticblockExample.Test, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend JavaFX.application.Application

What is the need/purpose of a static block?


➲ The purpose of a static block is to write those logics inside the static block that are executed during the class loading.
➲ It is mostly used for changing the default value of the static variables.
➲ It is used to initialize the static variables of the class.
Program source code 4:
    package staticblockExample; public class Employee { static String eName="Deep"; static int eID; static int age; String companyName="TCS"; // Instance variable. // Change the value of static variable in the S.B. static{ eName="Shubh"; System.out.println("Name of Employee: " +eName); } // Initialize the value of static variable in the S.B. static { eID=2342; System.out.println("Employee's Id: " +eID); } // If you don't assign the value of static variable then it will print default value. Here I am assigning any value to the employee's age. So it will print default value 'zero' on the console. Zero is the default value of an integer. static{ System.out.println("Employee's age: " +age); } static { System.out.println("Company name: " +companyName); // Compile time error because we cannot access not-static variables in the static block. } public static void main(String[] args) { } }
    Output: Name of Employee: Shubh Employee's Id: 2342 Employee's age: 0
Always Remember: Static block cannot access instance(non-static) variables and methods.
Let' see one more example.
Program source code 5:
    package staticblockExample; public class MemberTest { static int a=20; // Static variable int b=30; // Instance variable // Declare instance variable. void display(){ System.out.println("Hello Java"); } static void show(){ System.out.println("You cannot access instance variable in static method "); System.out.println(b); // Compile time error because cannot make a static reference to the non-static field b. } // Declare instance block. { display(); // Call the instance method. } static { display(); // Compile time error because we cannot call instance method in static area. System.out.println(a); // Calling S.V. System.out.println(" " +b); // Compile time error because we cannot call instance variable in static block. } public static void main(String[] args) { MemberTest mt=new MemberTest(); mt.display(); show(); } }
Program source code 6: In this example program, we will cover all five elements variable, method, constructor, instance block, and static block within a class.
    package staticblockExample; public class AllTest { int x=10; static int y=20; void m1(int a){ System.out.println("Instance method"); } static void m2(String str){ System.out.println("Static method"); } AllTest(){ System.out.println("0-arg constructor"); } AllTest(int a){ System.out.println("1-arg constructor"); } { System.out.println("Instance block"); } static { System.out.println("Static block"); } public static void main(String[] args) { AllTest at=new AllTest(); AllTest at1=new AllTest(10); at.m1(50); AllTest.m2("Shubh"); } }
    Output: Static block Instance block 0-arg constructor Instance block 1-arg constructor Instance method Static method

Advantage of Static block in Java


1. Static blocks are used to write logic that you want to execute during the class loading.
2. They are used to initialize the static variables.

Difference between Static block and Instance block 


1. Static block is also known as a static initialization block whereas Instance block is also known as instance initialization block or non-static block.
2. They execute before the instance block whereas instance block executes after the static blocks.
3. Only static variables can be accessed inside the static block whereas static and non-static both variables can be accessed inside the instance block.
4. Static blocks execute when the class is loaded into the memory whereas instance blocks execute only when instance of the class is created.
5. 'this' keyword cannot be used in the static block whereas this keyword can be used in the instance block.

Final words:
I hope that this article will help you to understand the Static block in Java with example programs and advantage. This article has covered almost all the important topics. The practical example programs are very important to clear the concepts.



Popular