Java Initialization Blocks: Static & Non-Static Explained

Day 25 – Understanding Blocks in Java (Static & Non-Static) One interesting concept I learned today in Core Java is Initialization Blocks. Blocks are special members of a class used to initialize variables automatically during program execution. There are mainly two types of blocks in Java: 🔹 Static Block 🔹 Non-Static Block (Instance Initialization Block) ---------------------------------------------- 🔹 Static Block A static block is used to initialize static variables of a class. Key points: ✔ Executed only once ✔ Runs during class loading ✔ Executes before the main() method Example: class Employee { static int x; static { x = 20; } public static void main(String[] args) { System.out.println(Employee.x); } } 📌 Static block executes automatically when the class is loaded into memory. ---------------------------------------------- 🔹 Non-Static Block (Instance Block) A non-static block is used to initialize non-static (instance) variables. Key points: ✔ Executes every time an object is created ✔ Can run multiple times ✔ Runs before the constructor Example: class Employee { int id; String name; { id = 1; name = "Raj"; } } Whenever we create a new object: Employee e1 = new Employee(); Employee e2 = new Employee(); The non-static block runs twice because two objects are created. ---------------------------------------------- 🔹 Order of Execution in Java Understanding execution order is important: 📌 Static Block → main() → Non-Static Block → Constructor This explains how Java initializes classes and objects internally. 📌 Key Takeaway Initialization blocks help in automatic setup of variables before objects start working. Understanding this concept helps build strong fundamentals in Java memory behavior and object creation. Every day I’m learning something new about how Java actually works behind the scenes. #Java #CoreJava #JavaProgramming #JavaDeveloper #Programming #SoftwareDevelopment #LearningInPublic #CodingJourney #BackendDevelopment #100DaysOfCode

  • graphical user interface, text, application, chat or text message

Great explanation! Static block runs once during class loading, while non-static block runs every time an object is created. Very useful concept.

To view or add a comment, sign in

Explore content categories