Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
The Initializer Block in Java
Next article icon

Static Blocks in Java

Last Updated : 10 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 


Next Article
The Initializer Block in Java

K

kartik
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

    Java Constructors
    In Java, constructors play an important role in object creation. A constructor is a special block of code that is called when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values to its attributes. This process happens automaticall
    10 min read
    Default constructor in Java
    Like C++, Java automatically creates default constructor if there is no default or parameterized constructor written by user, and (like C++) the default constructor automatically calls parent default constructor. But unlike C++, default constructor in Java initializes member data variable to default
    1 min read
    Private Constructors and Singleton Classes in Java
    In Java, the private constructor is a special type of constructor that cannot be accessed from outside the class. This is used in conjunction with the singleton design pattern to control the instantiation. Private ConstructorThe private constructor is used to resist other classes to create new insta
    2 min read
    Copy Constructor in Java
    Like C++, Java also supports a copy constructor. But, unlike C++, Java doesn't create a default copy constructor if you don't write your own. A prerequisite prior to learning copy constructors is to learn about constructors in java to deeper roots. Below is an example Java program that shows a simpl
    4 min read
    Constructor Chaining In Java with Examples
    Constructor chaining is the process of calling one constructor from another constructor with respect to current object. One of the main use of constructor chaining is to avoid duplicate codes while having multiple constructor (by means of constructor overloading) and make code more readable. Prerequ
    5 min read
    Why Constructors are not inherited in Java?
    Constructor is a block of code that allows you to create an object of class and has same name as class with no explicit return type. Whenever a class (child class) extends another class (parent class), the sub class inherits state and behavior in the form of variables and methods from its super clas
    2 min read
    Constructor Overloading in Java
    Java supports Constructor Overloading in addition to overloading methods. In Java, overloaded constructor is called based on the parameters specified when a new is executed. When do we need Constructor Overloading? Sometimes there is a need of initializing an object in different ways. This can be do
    5 min read
    Static Blocks in Java
    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
    4 min read
    The Initializer Block in Java
    In order to perform any operations while assigning values to an instance data member, an initializer block is used. In simpler terms, the initializer block is used to declare/initialize the common part of various constructors of a class. It runs every time whenever the object is created. The initial
    2 min read
    Order of Execution of Initialization Blocks and Constructors in Java
    In Java, there are various techniques, which we can use to initialize and perform operations on objects such as methods, constructors, and initialization blocks. These tools are used to ensure that the program works as expected. Instance Initialization Blocks (IIB) are used to initialize instance va
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences