Can main() method take an argument other than String array?

No, an argument of main() method must be String array. But, from the introduction of var args you can pass var args of string type as an argument to main() method. Again, var args are nothing but the arrays.

Below diagram demonstrates that main() method should have an argument as String array or var args:

Other arguments for the main method

You can write the public static void main() method with arguments other than String the program gets compiled.

Since the main method is the entry point of the Java program, whenever you execute one the JVM searches for the main method, which is public, static, with return type void, and a String array as an argument.
public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.
}
If anything is missing the JVM raises an error. Therefore, if you write a method with other data types (except String array) as arguments, at the time of execution, JVM does not consider this new method as the entry point of Java and generates an error.

Example

In the following Java program, we are trying to use an integer array as arguments of the main method.
public class MainExample {
   public static void main(int args[]) {
      System.out.println("Hello how are you");
   }
}

Output

On executing, this program generates the following error −
Error: Main method not found in class MainMethodExample, please define the main
method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application



Comments