Initialization of static method when class loads in java

No, this isn't correct.

Neither of these methods are called when the class is loaded.

main() is called when you execute the class Test.

Only static initialisers are called when the class is loaded. A static initialiser looks like this:

static
{
    //code here
}

A class is loaded before the main() method is executed, and therefore its static initialiser is run before the main() method. The following snippet will make that clear.

public class TestA
{
    static
    {
        System.out.println( "hello" );
    }

    public static void main( String[] args )
    {
        System.out.println( "bye" );
    }
}

Let me explain it in detail

Types of methods There are basically two types of methods,

  1. Instance methods
  2. Class Methods

Instance Methods Belong to objects and you will always need an object/instance to call such methods.

static methods are the class methods and they can be called directly by class name, there is no need to have an instance of class to call them.

For example,

class Demo{
    public void sayHello(){
         System.out.println("Hello");
    }

    public static void sayHi(){
         System.out.println("Hi")
    }

    public static void main(String args[]){
          Demo.sayHi();    //Call to static/class method

          Demo.sayHello(); //It will not work

          Demo d = new Demo();
          d.sayHello();    //It will work.
    }
}

**But NONE of them gets called automatically when class loads.**

Main Difference between the two

In memory there is ONLY ONE copy of static methods which will be available for all the objects. But whenever an object is created a new copy of instance method is created for the object, so each object has its own instance method. Similar to instance & class variables.

Static methods are not meant to be run automatically, instead they are shared by all objects. Why main() method is called, because it is the entry point of the program.

Apart from them, there is static block which is called automatically only once when the class is loaded.

Example

class Main{
     static{
           System.out.println("static block");
     }

     public static void main(String args[]){
           System.out.println("main");
     }
}

Output will be

static block

main


main() method is not executed because it's static, it executes because it is the Entry Point for any Java program. If you want something to run, you'll need to call it from the main method. No other methods are automatically called when the class is executed.

Tags:

Java