Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need main method when you have static blocks

Tags:

java

This question was asked to someone I know. What I could think of is that main method will be required to accept command line arguments as the method parameters.

Are there any other arguments in defense of public static void main(String args[]) method?

like image 503
Nishan Avatar asked Apr 08 '11 04:04

Nishan


4 Answers

  • It makes it possible to test a main method
  • It makes it possible to invoke a main method from other classes
  • It makes it possible to invoke a main method multiple times, whereas type initialization only occurs once
  • It makes it possible to create an instance of a class containing a main method without running the program.

The thought of type initialization for the "main" class blocking until the application has finished is abhorrent.

Could we cope with it? I dare say. But I suspect I would always end up writing:

public class EntryPoint
{
    static
    {
        // Workaround for entry points being static initializers
        String[] arguments = getArgumentsHoweverThatHappens();
        RealEntryPoint.execute(arguments);
    }
}

... and nothing else would ever touch EntryPoint.

like image 102
Jon Skeet Avatar answered Oct 17 '22 23:10

Jon Skeet


Static initializers and the main method have different intents. The main method's purpose is to be invoked if, and only if, the JVM is called with the containing class as the main class (or if it's called directly by code). The purpose of static initialiers is to do class initialization. Initializers are always run, but it's possible to have main methods that are not.

like image 29
ataylor Avatar answered Oct 18 '22 01:10

ataylor


In addition to above stated, the need for main (not the characteristics of static blocks) is that your application needs a starting point, thats is, when you execute your application, you pass the JVM dozens of classes and the JVM needs to know which method to invoke first in order to start and execute your application. You need to declare which point is the beginning of your application because the JVM can't guess it. (Sorry for my english)

like image 8
David Oliván Ubieto Avatar answered Oct 18 '22 00:10

David Oliván Ubieto


Static blocks are meant to be run once the corresponding class is loaded. The main(), however, is the entry point to your program and as Jon said, it can be invoked multiple times.

like image 5
asgs Avatar answered Oct 17 '22 23:10

asgs