Skip to main content

Class Loading and Object Creation

class Hello {

int a = 99;
static int b = 88;

Hello() {
System.out.println("Hello D.C.");
}

{
System.out.println("Hello I.B");
}

static {
System.out.println("Hello S.B.");
}
}

🧠 Key Concepts Explained

🔹 1. Multiple main() Methods

  • You can define multiple main() methods
  • JVM executes only:
public static void main(String[] args)


🔹 2. Instance Block vs Constructor

  • Instance Block (I.B) → runs before constructor
  • Constructor (D.C) → runs after instance block

🔹 3. Static Block (S.B)

  • Executes only once when class is loaded

🔹 4. Execution Order (Very Important)

When object is created:

1. Static Block (only once)
2. Instance Block
3. Constructor

🔹 5. Multiple Classes with main()

  • You can run any class:
java Hello → runs Hello.main()
java Hai → runs Hai.main()

🔹 6. Calling another class main()

Hello.main(args);

✔ Valid

✔ Works like a normal method call


Quick Summary

  • ✔ Static block → class loading
  • ✔ Instance block → object creation
  • ✔ Constructor → object initialization
  • ✔ Only one main() is entry point

Hello h = new Hello();

🔄 Step-by-Step Execution


1) Memory Allocation for Reference Variable

  • JVM allocates 8 bytes for reference variable h
  • Initializes with null
h → null (8 byte s)

2) Check Class Loading

  • JVM checks whether class Hello is already loaded

3) If Class Not Loaded → Load Class

a) Load bytecode

  • Reads .class file
  • Loads into memory

b) Static variables initialization

static int b=88;
b → 88

c) Execute Static Blocks

static {
System.out.println("Hello S.B.");
}

4) Constructor Invocation

  • Constructor is called
  • (But execution happens after instance block)

5) Memory Allocation for Instance Variables

int a=99;
Object (say address: 99723)
a → 99

6) Instance Block Execution

{
System.out.println("Hello I.B");
}

7) Constructor Execution

Hello() {
System.out.println("Hello D.C.");
}

8) Assign Object Reference

  • Object address assigned to h
h → 99723

🧠 Final Memory Representation

h (reference) → 99723

Object:
a = 99

Class Area:
b = 88

Execution Order Summary

1. Reference variable → null
2. Class loading
3. Static variables + static block
4. Instance variable memory allocation
5. Instance block
6. Constructor
7. Assign reference

⚠️ Important Notes

  • ✔ Static block runs only once per class
  • ✔ Instance block runs every object creation
  • ✔ Constructor runs after instance block
  • ✔ Reference variable stores address, not object