user3766874 user3766874 - 6 months ago 14
Java Question

Initialization of static method when class loads in java

I have a doubt regarding static methods. In the program written below, output will be:

main
. I understand this because
main
is a static method, so when class loads, it executes. If so, the same principle should apply for
met()
also, right? As it is also static. Why does only
main
executes whereas
met()
doesn't when the class loads?

public class Test {

static void met() {
System.out.println("method");
}

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

Answer

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.