Java Command Line Arguments

The program arguments passed at the time of launching of the Java application are called command line arguments.

A Java program can be launched either from console or from an editor e.g. Eclipse. To launch a program we use "java className" command from command prompt or system console.

While launching the program, we can pass the additional arguments (no limit on the numbers of arguments) in below syntax.

1. Java Command Line Parameters Syntax

In given below syntax, we are passing 5 parameters to the Main class MyClass. MyClass has the main() method which accepts these arguments in form of an String array.

$ java MyClass arg1 arg2 arg3 arg4 arg5

2. Java Command Line Arguments Example

Let’s create an example to understand how command-line program arguments work in Java. This class simple accepts the arguments and prints them in the console.

As a programmer, we can use these arguments as startup parameters to customize the behavior of the application in runtime.

package app;

public class Main 
  public static void main(String[] args) 
    for(int i = 0; i< args.length; i++) 
      System.out.println( args[i] );

Now run this class from the console.

$ java Main 1 2 3 4



3. Summary

  • Command line args can be used to specify configuration information while launching the application.
  • There is no restriction on the maximum number of arguments. We can specify any number of arguments.
  • Arguments are passed as strings.
  • Passed arguments are retrieved as the string array in the main() method argument.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment


A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.