Computing Magazine

What Happens When A Java Program Runs

Posted on the 30 May 2014 by Abhishek Somani @somaniabhi
This simple program describes execution order of different block and methods when a java program runs.

public class WhatHappensInJavaProgram
{
static
{
System.out.println("Static block ");
}
public WhatHappensInJavaProgram()
{
System.out.println("Constructor");
}
public static void testStatic()
{
System.out.println("Static method");
}
public void test()
{
System.out.println("Instance method");
}
public static void main(String args[])
{
System.out.println("Main Method");
testStatic();
WhatHappensInJavaProgram obj =new WhatHappensInJavaProgram();
obj.test();

}
}
In this program , first of all this class WhatHappensInJavaProgram get loaded in JVM and class object is created.While loading the class , the jvm runs its static blocks and initilizes static variables . So the very first line which gets printed will be static block . After this , main method runs. Then if we create new instance , first the memory is allocated in heap , then constructor runs , and then the reference is assigned . After that , instance method runs .

Static block
Main Method
Static method
Constructor
Instance method


Back to Featured Articles on Logo Paperblog

Magazines