Command Line Arguments

Command Line Arguments

In this tutorial, we are going to discuss Command Line Arguments in Java. Command-line arguments are parameters passed to a program when it is executed via the command line or terminal. In Java, command-line arguments are provided to the main method as an array of strings.

The main object of command line arguments are we can customize the behavior of main.

Command Line Arguments
java Test a b c
Here a = arg[0];
b = arg[1];
c = arg[2];
args.length = 3;
package com.ashok.test;

public class Test {
   public static void main(String args[]) {
      for(int i = 0; i < args.length; i++) {
         System.out.print(args[i]);
      }
   }
}

Output

java Test // Nothing Display
java Test A B // A B
  • Within the main() command line arguments are available in string form.
package com.ashok.test;

public class Test {
   public static void main(String args[]) {
      System.out.print(args[0]+args[1]]);
   }
}

Output

java Test 10 20 // 1020
  • Space is the separator between command line arguments, if the command line arguments itself contain space then we should enclose with in double quotes.
package com.ashok.test;

public class Test {
   public static void main(String args[]) {
      System.out.print(args[0]);
   }
}

Output

java Test "Ashok Kumar" // Ashok Kumar 
package com.ashok.test;

public class Test {
   public static void main(String args[]) {
      String argh = {'A','B'};
      args = argh;
      for(String s : args) {
         System.out.println(s);
      }
   }
}
java Test X Y
O/P A B

java Test X Y Z
O/P A B

java Test
O/P A B

Note

The maximum allowed number of command line arguments is 2147483647 which is maximum size of integer data type and minimum is 0.

Command-line arguments are useful for passing input parameters, configuration options, file paths, or any other data to a Java program when it is executed.

That’s all about Command line arguments in Java. If you have any queries or feedback, please write us at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!

Command Line Arguments
Scroll to top