Does main() method accept arguments other than string array, in java?


The public static void main() method accepts an array of values of the type String Java from the user.

public class{
   public static void main(String[] args){
   }
}

You can pass them at the time of execution right after the class name separated with spaces as −

java ClassName 10 20 30

And, in the program (from the main method) you can extract these values from the String array and use.

Example

For example, you can use command line arguments to pass a and b in the above program as −

public class Sample {
   public static void main(String[] args){
      int a = Integer.parseInt(args[0]);
      int b = Integer.parseInt(args[1]);
      int c = a+b;
      System.out.println("Sum of the two numbers is "+c);
   }
}

Output

You can compile and, run the program by passing the values at execution line through command prompt as shown below −

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[]){
}

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.

 Live Demo

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

Updated on: 29-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements