Command Line Argument In Java

Introduction

 
In this article, we discuss command line arguments in Java.
 

What is command line argument

 
An argument passed when a Java program is run is called a command line argument. The arguments can be used as input. So, it provides a convenient way to check out the behavior of the program on various values. We can pass any number of arguments from the command prompt or nearly anywhere a Java program is executed. This allows the user to specify configuration information when the application is launched.
 
Advantages
  • We can provide any number of arguments using a command line argument.
  • Information is passed as Strings. So we can convert it to numeric or another format easily.
  • While launching our application it is useful for configuration information.
1. Example
 
In this example, we are printing the first command line argument as in the following.
 
CommandLineEx.java
  1. class CommandLineEx {  
  2.     public static void main(String x[]) {  
  3.         System.out.println("First Command line Argument is: " + x[0]);  
  4.     }  
  5. }  
Output
 
Fig-1.jpg
 
2. Example
 
In this example, we are printing or showing all the command-line arguments using a for loop.
 
CommandLineEx1.java
  1. class CommandLineEx1 {  
  2.     public static void main(String x[]) {  
  3.         for (int a = 0; a < x.length; a++)  
  4.             System.out.println(x[a]);  
  5.     }  
  6. }  
Output
 
Fig-2.jpg
 
3. Example
 
In this example; we show a program that supports only numeric command-line arguments, using parse int to convert a string value to a number (like "1234" string as a number 1234).
 
CommandLineEx2.java
  1. class CommandLineEx2 {  
  2.     public static void main(String x[]) {  
  3.         int argFirst;  
  4.         if (x.length > 0) {  
  5.             try {  
  6.                 argFirst = Integer.parseInt(x[0]);  
  7.                 System.out.println(x[0]);  
  8.             } catch (NumberFormatException nfe) {  
  9.                 System.err.println("Given argument" + " should be an integer");  
  10.             }  
  11.         }  
  12.     }  
  13. }  
Output
 
This program throws a NuberFormatException if the format of x[0] is not valid as in the following.
 
Fig-3.jpg
 
When we provide an integer value it works fine as in the following.
 
fig-4.jpg


Similar Articles