Command Line Arguments In Java

Command Line Arguments In Java
Command Line Arguments In Java

Introduction

Developers frequently use Command Line Interfaces(CLI) to run applications in their daily tasks. It helps them do repetitive tasks efficiently and is quite powerful in execution as it requires fewer resources and has high precision. 

A Java command-line program takes the input from the user from the command line during execution. The command-line interface removes the requirement for a graphical user interface (GUI) to take input from the user. 

Let’s learn how to use it along with some examples. 


What is a Command Line?

A command line is a test interface for the system. This takes in commands and passes them on the computer’s operating system for execution. Developers mostly use this quick and powerful tool to work efficiently and accomplish a wider set of tasks in a short time.

Command-line helps the user accomplish tasks like navigating through the folder, creating text files, open editors, etc. It’s just another way of communicating with the system. To get the CLI, search for the Terminal application in the system.

Tasks accomplished using a CLI

What are Command Line Arguments in Java?

The command line arguments in Java are the arguments passed to a program during runtime. As the name suggests, arguments are passed through the command line. The java program receives this argument and uses it as the input.

The command line arguments in Java from the command line are passed to the Java Virtual Machine (JVM). The JVM then wraps these arguments and stores them in the String type args parameter of the main() method. 

The entry point of any Java program is the main() method. So when the program is executed, these arguments are fetched by accessing the String[] args parameter of the main() method and used as the input.

To access these arguments, JVM traverses the args parameter in the loop or uses the direct index value because args is an array of type String.

blog banner 1

Example

Let’s look at this simple example to understand command line arguments in Java. This program prints all the arguments passed from the command line.

public class Main {
 public static void main(String[] args) {
   // check if any argument is passed checking the length of args using args.length
   if (args.length > 0) {
     // traverse the args parameter to access the arguments
     for(int i = 0 ; i < args.length ; i++) {
       // displays the arguments
       System.out.println(args[i]);
     }
   } else {
     System.out.println("Arguments not passed.");
   }
 }
}

Steps to Execute the program

To compile and run the above java program in the command prompt, follow the following steps:

1. The javac command is used to compile the code, which then creates a .class file.

Syntax:

javac <filename>.java

2. After compilation, the .class file can be executed using the java command. 

To simply run the code, use java <classname> Here, the class name is the name of the user’s class. Like in the above case, the user’s class is Main, and “Main” has to be mentioned in the place of the class name.

To pass arguments while running the program, the arguments are mentioned after the class name.

  
java <classname> arguments

Output:

Passing Numeric Command-Line Arguments

The main() method only accepts string arguments, so the arguments passed are stored as Strings in the String array. Hence, it is not possible to directly pass numeric arguments through the command line. 

So to have numeric arguments, the string arguments have to be parsed into an integer, double, float, etc., using the parseInt() method, parseDouble() method, parseFloat() method, respectively.

Example: 

Let’s look at this simple example to calculate the sum of two numbers.

public class Main {
public static void main(String[] args) {
  // check if two arguments are passed
  if (args.length == 2) {
    // access the first argument
    int num1 = args[0];
    // access the second argument
    int num2 = args[1];
    int sum = num1 + num2;
    System.out.println("Sum of "+num1+" and "+num2+" = "+sum);
  } else {
    System.out.println("Enter two numbers.");
  }
}
}

In the above example, the arguments are used as such without converting them into it. This produces the incompatible types error.

Error:

This can be solved by converting the string argument into an integer using the parseInt() method of the Integer class.

public class Main {
 public static void main(String[] args) {
   // check if two arguments are passed
   if (args.length == 2) {
     // access the first argument
     int num1 = Integer.parseInt(args[0]);
     // access the second argument
     int num2 = Integer.parseInt(args[1]);
     int sum = num1 + num2;
     System.out.println("Sum of "+num1+" and "+num2+" = "+sum);
   } else {
     System.out.println("Enter two numbers.");
   }
 }
}

Output: 

BMI Calculator using Command-Line Arguments In Java

Let’s write a program to find the BMI using command-line arguments in Java. In this program, the first argument is the name, the second argument is the weight (in kg), and the third argument is the height(in meters).

Formula for BMI

public class Main {
 public static void main(String[] args) {
   // check if three arguments are passed
   if (args.length == 3) {
     // access the first argument
     String name = args[0];
     // access the second argument
     float weight = Float.parseFloat(args[1]);
     // access the third argument
     float height = Float.parseFloat(args[2]);
     float bmi = weight / (float)Math.pow(height,2);
     System.out.println("Name: "+name);
     System.out.println("BMI: "+bmi);
     String bmiCategory;
     // assign bmi category
     if(bmi < 18.5) {
       bmiCategory = "Underweight";
     } else if((bmi >= 18.5) && (bmi <= 24.9)) {
       bmiCategory = "Normal weight";
     } else if((bmi >= 25.0) && (bmi <= 29.9)) {
       bmiCategory = "Overweight";
     } else {
       bmiCategory = "Obesity";
     }
     System.out.println("BMI Category: "+bmiCategory);
   } else {
     System.out.println("Enter name, weight, and height in exact order.");
   }
 }
}

Output:

Important Points

Some important points to note regarding the command line arguments are:

  • Command line arguments in Java directly follow the class name on the command line when executed.

For example, if the class name is Main and arguments are Java, C, Python, etc., the command must be written as mentioned below.

java Main Java C Python
  • Any number of arguments can be passed through the command line.
  • The arguments passed are stored as Strings in the String array.
  • The arguments are always separated by white space.
  • The command line arguments in Java are stored in the String[] args parameter of the main() method.
  • String[] args contains the command-line arguments in the same order as it was passed at execution.

Frequently Asked Questions

What is the use of command line arguments in Java?

The command line arguments in Java are used to pass arguments during the program’s execution.

What are command line arguments in Java?

The command line Arguments in Java are the arguments passed to a program during runtime through the command line.

What is String [] args in Java?

String[] args in Java is an array of strings named args as its parameter.

Why do you need String [] args?

String[] args in Java store the command line Arguments passed through the command line at runtime in the string format.

When does the NumberFormatException occur?

If the arguments cannot be converted into the specified numeric value, then the NumberFormatException is thrown.

What are the other ways to take input in Java?

Input in Java can also be taken with the help of the Java Scanner Class, Java BufferedReader Class, and the Java Console Class.

Key Takeaways

That’s all about the topic! With the help of this knowledge, one can easily create command line applications in Java. Don’t stop here. Check out the various other ways to give input to the Java program using the Java Scanner Class, Java BufferedReader Class, and the Java Console Class.

By Hari Sapna Nair