How to Pass and Access Command Line Arguments in Java

When a Java program is launched from the terminal or command line, the arguments passed at the time of launching are called command-line arguments.

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

1. How to Pass Arguments from Command Line

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

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

$ java MyClass arg1 arg2 arg3 arg4 arg5

2. How to Access Command Line Arguments

Let’s create an example to understand how command-line program arguments work in Java. This class simply 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.

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

#prints

1
2
3
4

Since Java 5, we can use varargs in the main() method. Even though, accessing the variables remains the same.

public static void main(String... args) {

    //...
}

3. Conclusion

  • 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 !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.