[Tutorial] Command Line Arguments In Java With Example!

What is the Command Line Argument?

Command Line Argument is information passed to the program when you run the program. The passed information is stored as a string array in the main method. Later, you can use the command line arguments in your program.

Example While running a class Demo, you can specify command-line arguments as

java Demo arg1 arg2 arg3 …

Command Line Arguments in Java: Important Points

  • Command Line Arguments can be used to specify configuration information while launching your application.
  • There is no restriction on the number of java command line arguments. You can specify any number of arguments
  • Information is passed as Strings.
  • They are captured into the String args of your main method

Example: To Learn java Command Line Arguments

Step 1) Copy the following code into an editor.

class Demo{
     public static void main(String b[]){
         System.out.println("Argument one = "+b[0]);
         System.out.println("Argument two = "+b[1]);
    }
}

Step 2) Save & Compile the code

Step 3) Run the code as java Demo apple orange.

1

Step 4) You must get an output as below.

2

ENJOY & HAPPY LEARNING! :+1:

11 Likes

I always used to mess up between args[0],args[1] (here b[0],b[1]),
as in c/c++ & python arg[0] was program name followed by arguments :sweat_smile:

2 Likes