Site icon TestingDocs.com

Java Program to Print Command line arguments

Overview

In this tutorial, we will write a simple Java program to print the command line argument passed to the Java program.

In Java, we have a special kind of array called args that holds the command line arguments passed to the Java program. args[0] holds the first command-line argument. args[1] holds the second command-line argument and so on.

Simple Java Program

An array stores a series of values. The values can be numbers, strings, objects, or just any other kind of Java data type. In Java, the first element of the array is at position 0, the second at position 1, and so on. This is illustrated in the below diagram.

 

To understand this better, Let’s see with the help of a simple example program called Greeting. You can pass the person’s name as a command line argument to the java program.

 

public class Greeting {
 public static void main (String args[]) {
 /* Say hello to person passed in command line */
 System.out.println("Hello " + args[0] );
 }
 }

 

Program Output

Compile the Java program

/> javac Greeting.java

Run the program by passing the name as an argument to the program.

/> java Greeting Surendra

The first argument is stored in args[0]. The program picks it up and displays the output as shown below.

 

Exercise

As an exercise, you can improvise the above code snippet

Task1: To avoid the common exception, handle the exception using a try-catch block.  ArrayIndexOutOfBoundsException while dealing with the command line.

Task2: This program only prints one command line argument. Using a loop, enhance the program to greet all the names provided in the command line.

Java Tutorial on this website: https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/in/java/

Exit mobile version