0

Hey Guys,

I have the following code.

public class Main {

    static int a = 3;
    static int b;

    static void math(int x) {
        System.out.println("x = " + x);
        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }

     public static void main(String[] args) {
        math(100);
    }

    static {
        b = a * 4;
    }
}

When I ran the above program, the control first went to intialise the variable a, then static method in which variable b is calculated and then it went to the main method.

Can someone explain me why it doesn't first go to the main method?

2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by stephen84s
0

Well those are the steps that happen when a class is loaded for the first time(and your class has to be loaded before any static methods on it can be executed in this case the main) in your JVM,

  • First your static variables are initialised
  • Next your static blocks are executed

You could check this by moving the main method to another class and by trying to create an object of this class or by calling the math() method directly.

Edited by stephen84s: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.