Command Line Arguments In Java
Command Line Arguments
In Java, the command line argument is an argument, which is used to pass at the time of running Java program. This argument is passed from the console and can be received in the program. It can be used as an input.
A command line argument provides a simple and easy way to check the behavior of the program for the different values and we can pass the numbers of the arguments from the command prompt.
Let’s see an example, given below.
Code
- public class CommandLineArg {
- public static void main(String args[]) {
- System.out.println("Hello," + args[0]);
- }
- }
Compile by: javac CommandLineArg.java
Run by: java CommandLineArg Java
Output
In the example, mentioned above, we receive only one argument and print it. To run this program, we must pass at least one argument from the command prompt.
Let’s see another example, given below.
Code
- public class CommandLineArg {
- public static void main(String args[]) {
- for (int i = 0; i < args.length; i++) {
- System.out.println(args[i]);
- }
- }
- }
Compile by: javac CommandLineArg.java
Run by: java CommandLineArg Hello Java 8
Output
In the example, mentioned above, we print all the arguments passed from the command-line. For this purpose, we have traversed the array, using for loop.
Summary
Thus, we learnt that a command line argument provides a simple and easy way to check the behavior of the program for the different values and we can pass the numbers of the arguments from the command prompt and also learnt how we can create it in Java.