Java - Command Line Arguments

Java

Share

In this tutorial we will learn about command line arguments in Java programming language.

Since the beginning of this tutorial series we have been writing the main method like the following.

class NameOfTheClass {
  public static void main(String[] args) {
    // some code...
  }
}

Note! The parameter list of the main method is String[] args.

So, we have a variable args which is an array of String.

When, we run our program we can pass some arguments to our code from the command line and it will be saved in this args variable which we can later use in our code.

Syntax of command line argument

java cmdLine command_list

Where, cmdLine is the name of the class and command_list is the list of arguments passed to the class.

Note! The first command line argument is stored at index 0, the second one is stored at index 1 and so on.

Note! All command line arguments are passed as string.

Example #1: Write a program in Java to print the total number of arguments passed

class Example {
  public static void main(String[] args) {

    // total number of arguments passed
    int len = args.length;
    System.out.println("Total number of arguments: " + len);

  }
}

Output:

$ javac Example.java 
$ java Example
Total number of arguments: 0

$ java Example Hello World
Total number of arguments: 2

$ java Example My name is Yusuf Shakeel
Total number of arguments: 5

Example #2: Write a program in Java to print all the arguments passed

class Example {
  public static void main(String[] args) {

    // total number of arguments passed
    int len = args.length;
    System.out.println("Total number of arguments: " + len);

    System.out.println("Arguments:");
    for(int i = 0; i < len; i++) {
    	System.out.println("Index: " + i + " Arg: " + args[i]);
    }

  }
}

Output:

$ javac Example.java 
$ java Example My name is Yusuf Shakeel
Total number of arguments: 5
Arguments:
Index: 0 Arg: My
Index: 1 Arg: name
Index: 2 Arg: is
Index: 3 Arg: Yusuf
Index: 4 Arg: Shakeel

Example #3: Write a program in Java to take two string values as command line argument and check for equality

For this we will use the equals method provided by the String class.

class Example {
  public static void main(String[] args) {

    // total number of arguments passed
    int len = args.length;
    
    // check strings provided
    if (len < 2) {
    	System.out.println("Two strings required.");
    }
    else {
    	// check if provided strings are equal
    	if (args[0].equals(args[1])) {
    		System.out.println("Strings are equal.");
    	}
    	else {
    		System.out.println("Strings are not equal.");
    	}
    }

  }
}

Output:

$ javac Example.java 
$ java Example
Two strings required.

$ java Example Hello
Two strings required.

$ java Example Hello World
Strings are not equal.

$ java Example Hello hello
Strings are not equal.

$ java Example Hello Hello
Strings are equal.
Share