«Back to Home

Core Java

Topics

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
  1. public class CommandLineArg {  
  2.     public static void main(String args[]) {  
  3.         System.out.println("Hello," + args[0]);  
  4.     }  
  5. }  
56

Compile by: javac CommandLineArg.java
 
Run by: java CommandLineArg Java
 
Output

57

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
  1. public class CommandLineArg {  
  2.     public static void main(String args[]) {  
  3.         for (int i = 0; i < args.length; i++) {  
  4.             System.out.println(args[i]);  
  5.         }  
  6.     }  
  7. }  
58

Compile by: javac CommandLineArg.java
 
Run by: java CommandLineArg Hello Java 8
 
Output

59

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.