`main()` and Command Line Argument | Java

Basics • Java Fundamentals

`main()` and Command Line Argument | Java

To run every Java programme main() is necessary otherwise the programme would compile or run.

Whether class contains main() or not and whether mean is declared according to requirement or not these things wont cheque by compiler.

At runtime JVM is responsible to check these things. If JVM unable to find main() that will be get runtime exception i.e., NoSuchMethod Error:main

class Test{
//No main() methods declared
}

At runtime JVM always searches for the main method with the following prototype -

public stating void main (string[] args)

  • public is an access modifier, indicating that the main method can be accessed from outside the class.

  • static keyword indicates that the method belongs to the class rather than an instance of the class. It is compulsory main method should be static. Without existing any object JVM has to call this method so static is used.

  • The return type is void be because main method won't return anything to JVM.

  • The main method is the entry point of a Java program. We cannot use any other name for main method because inside JVM main is the name which is configured that is why it is always search for main (method name).

  • string[] args is the parameter list for the main method. It allows the program to accept command-line arguments. String[] args is an array of strings that holds any command-line arguments passed to the program.

The above syntax is very strict and if we perform any change then we will get runtime exception saying no such method error mean.

Even though above syntax is very strict the following changes are acceptable:

  1. Instead of public static we can take static public that is order of identifier is not important.

  2. We can declare string a day in acceptable form -

  • public static void main (string[] args)
  • public static void main (string []args)
  • public static void main (string args[])
  1. Instead of args we can take any valid Java identifier. For example - public static void main(string[] vikas)

  2. We can replace string[] with string... args parameter i.e., public static void main(string... args)

We can declare main method with the following modifiers also i.e., final, strictfp, synchronized

class Test{
    static final synchronized strictfp public void main(String... args){
        System.out.println("Hello World"); //Valid
    }
}

Exceptional Cases in main()

Case 1: Overloading of main()

  • Overloading of build method is possible but JVM will always call string[] argument main method only.

  • The other overloaded method we have to call explicitly just like a normal method.

class Test{
    //default main method
    public static void main(String[] args){
        System.out.println("Hello World");
    }

    //overloaded main method
    public static void main(int[] args){
        System.out.println(10);
    }
}

Case 2: Inheritance with main()

  • Inheritance concept applicable for main method hence while executing child class if child class doesn't contain method then parent class bin method will be executed.
class Parents{
    public static void main(String[] args){
        System.out.println("Parent Class");
    }
}

class Child extends Parents{
    //no main method
}

When will compile the parent's class, Chevrier will create two class files that is child.class and parents.class.

Case 3: Overidding of main()

It seems overriding concept applicable for main method but it is not because its method hiding.

Method hiding is nothing but same method and passed argument but in different class.

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

class Child extends Parents{
    public static void main(String[] args){
        System.out.println("Child Class");
    }
}

1.7v Enhancement w.r.t main()

Until 1.6 version if class doesn't contain main() then we will get runtime exceptions saying No suchMethod Error:main but from 1.7 onwards instead of we get more elaborated error information instead i.e., Error: Main method not found in class test please define main method as public static void main(String[] args)

From 1.7 version onwards main() is mandatory to start programme execution hence even though class contains static block it wont be executed if the class doesn't contain main().

Command Line Argument

  • The arguments which are passed from command line or command prompt are called command argument.

  • With these JVM will create an array and by passing that array as argument JVM will call main().

class Test{
    public static void main(String[] args){
        //code
    }
}
C:\> javac Test.java
C:\> java Test A B C

args[0] = A, args[1] = B, args[2] = C; args.length will be 3

The main objective of command and argument is bigger customise behaviour of main method.

Let's say we want to merge two files. So, instead of using fixed variable value if we can pass the name of file or any file name that will do it that will be more convenient.

Command arguments are always passed as a string because it is most common data type and can be converted in any data type using parsing.

Exceptional Cases in Command line argument

Case 1

class Test{
    public static void main(String[] args){
        for(int i=0;i<args.length;i++){
            System.out.println(args[i]);
        }
    }
}
C:\> javac Test.java
C:\> java Test A B C
Runtmie Exception: ArrayIndexOutOfBoundException

Compiler complaining due to i<=args.length to if it will be i<args.length then it will be fine and wont complain or get any runtime exception.

Case 2

Usually space itself is the separator between command line argument.

in our command line arguments itself contains space then we have to enclose that command line argument within double quotes.

class Test{
    public static void main(String[] args){
            System.out.println(args[0]);
    }
}
C:\> javac Test.java
C:\> java Test "Note Book"
Note Book
C:\> java Test Note
Note

Conclusion

Understanding Java main() essentials: Its importance, syntax rules, runtime role, and command-line arguments. Explore nuances like overloading, inheritance, and overriding, with a focus on clean coding practices. Delve into exceptional cases and the significance of main() in Java 1.7+. Embrace command-line arguments for customized program behaviour.

Did you find this article valuable?

Support Xander | ᓕᘏᗢ by becoming a sponsor. Any amount is appreciated!