Search code examples
javastringprogram-entry-point

Why is it necessary to have `String[] args` as main() parameter?


I'm not asking what is (String args[]) because that was answered here: What is "String args[]"? parameter in main method Java.

My question is why is it necessary to write it while writing main()?

I had my practical exams, where I faced a problem and realized I hadn't written String args[] while writing public static void main(). But then after writing main(String args[]) the problem was solved. (How and Why I still don't know!)

On that same day I was asked in Viva I was asked - "Is it necessary to write this String args[] while writing main()?" and thanks to the error that occurred I replied "YES" but was left without answer when asked "WHY?".
So I want to know why is it necessary to write String[] args.


Solution

  • From Java Language Specification 12.1.4

    The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:

    public static void main(String[] args)

    public static void main(String... args)

    (note that you can't have two main methods with String[] and String... in same class, since varargs are simply syntactic sugar which at compilation time will be replaced with arrays so you would end up with two methods handing String[] and one class can't have two methods with same name and parameters)

    So when you execute command like

    java YourClass foo bar
    

    Java Virtual Machine will place foo and bar parameters in String[] array and will try to pass that array to main method which can accept it as parameter.

    This method is also used when command doesn't have any arguments like

    java YourType
    

    This decision simplifies our life because we don't need to focus on handling cases where there are two entry points

    • one for command with arguments
    • and one where command doesn't have any arguments.

    We can simply allow user to pass arguments but if we don't wan to handle them we can simply ignore them.

    Also remember that we are allowed to have in our class any method which has proper declaration (and doesn't violate any rules inherited from superclass like widening member visibility - we can't make protected method public), so there is nothing wrong with having

    public static void main(){
        /*your code*/
    }
    

    But you need to realize that this method can't be used as entry point, so if you want to start your application from this method you will need to create proper main method which will execute your main() method:

    public static void main(String ...){
        main();
    }