Published: 29 April 2025 | Reading Time: 7 minutes
In Java, command-line arguments are a very practical feature of the language that enables a user to transmit input parameters directly to a program during runtime. It has the ability to change the way a program behaves at runtime without modifying the source code, thereby making Java applications even more flexible and dynamic.
This comprehensive guide covers what is command line arguments in Java and how they can be used by developers to add value to their applications. Knowing how to use command-line arguments, you can not only allow your programs to take input from users but also use it to set parameters and switch between different operation modes without changing the code.
Command-line arguments in Java allow users to pass input parameters to a program during execution via the terminal or command prompt. These arguments are essential for making a program dynamic, as they enable external inputs without modifying the source code. They are stored as an array of String values using the main method and can be accessed using indexing.
To pass command-line arguments to a Java program, follow this syntax:
java YourProgramClassName arg1 arg2 arg3 ...
Components:
Here's a simple Java program demonstrating what is command line arguments in Java and how they are used:
public class CommandLineExample {
public static void main(String[] args) {
System.out.println("Command-line arguments are: ");
for (String arg : args) {
System.out.println(arg);
}
}
}
Execution:
java CommandLineExample Hello World 123
Output:
Command-line arguments are:
Hello
World
123
Java provides various java command line options that control how the Java Virtual Machine (JVM) executes a program. These options help manage memory, define system properties, specify classpaths, and enable debugging.
The -version option displays the installed Java version. This is useful for verifying which version of Java is currently in use.
Example:
java -version
Output:
java version "17.0.2" 2022-01-18 LTS
Java(TM) SE Runtime Environment (build 17.0.2+8)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.2+8, mixed mode)
The -classpath or -cp option specifies where Java should look for user-defined classes and external libraries. This is essential when using dependencies stored in .jar files or custom directories.
Example:
java -cp myLibrary.jar MyClass
If MyClass depends on myLibrary.jar, this command ensures the JVM can find and load it.
Multiple directories example:
java -cp "lib/*:classes/" MyMainClass
Here, Java will search for required class files inside the lib directory (including .jar files) and the classes/ folder.
The -Xms option sets the initial heap memory size, while -Xmx defines the maximum heap memory that the JVM can allocate. These options help optimize memory usage in Java applications.
Example:
java -Xms256m -Xmx1g MyClass
In this case, MyClass starts with 256MB of heap memory and can expand up to 1GB if needed. This prevents OutOfMemoryError in memory-intensive applications.
The -D option allows you to define system properties that can be accessed within a Java program using System.getProperty(). This is commonly used for configuration settings.
Example:
java -Denv=production MyClass
Inside the Java program:
public class MyClass {
public static void main(String[] args) {
String env = System.getProperty("env");
System.out.println("Running in environment: " + env);
}
}
Output:
Running in environment: production
Debugging Java applications requires enabling remote debugging options so that external tools can connect and inspect the execution of the program.
The -Xdebug option enables debugging, while -Xrunjdwp allows external debuggers to connect to the JVM.
Example:
java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 MyClass
Parameters explained:
To debug using an IDE like IntelliJ or Eclipse:
In Java, command-line arguments are passed to the main method through the args parameter, which is an array of strings. These arguments allow users to provide input dynamically when running the program. By processing the args array, developers can customize program behavior based on user input.
The args parameter in the main method stores all command-line arguments as elements in a String array. Since it is an array, you can access its values using an index and check its length to determine the number of arguments provided.
Example:
public class ArgsExample {
public static void main(String[] args) {
System.out.println("Number of arguments: " + args.length);
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i + 1) + ": " + args[i]);
}
}
}
Execution:
java ArgsExample Java Programming 101
Output:
Number of arguments: 3
Argument 1: Java
Argument 2: Programming
Argument 3: 101
In this example, args.length gives the count of arguments, and a loop iterates through the array to print each argument separately.
Let's create a program that takes a name as input from the command line and prints a personalized greeting.
public class GreetUser {
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("Hello, " + args[0] + "!");
} else {
System.out.println("No name provided!");
}
}
}
Execution:
java GreetUser Alice
Output:
Hello, Alice!
The following program takes two arguments (first name and last name) and prints a full greeting.
public class FullNameGreeting {
public static void main(String[] args) {
if (args.length >= 2) {
System.out.println("Hello, " + args[0] + " " + args[1] + "!");
} else {
System.out.println("Please provide both first and last name.");
}
}
}
Execution:
java FullNameGreeting John Doe
Output:
Hello, John Doe!
Since args stores String values, numerical inputs must be converted into numbers before performing arithmetic operations. This example takes two numbers from the command line and calculates their sum.
public class SumCalculator {
public static void main(String[] args) {
if (args.length >= 2) {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int sum = num1 + num2;
System.out.println("Sum: " + sum);
} else {
System.out.println("Please provide two numbers.");
}
}
}
Execution:
java SumCalculator 10 20
Output:
Sum: 30
When running Java applications packaged as JAR (Java Archive) files, command-line arguments can be passed to customize the program's behavior. These arguments are received in the args array inside the Java program, just like in normal Java execution.
To execute a Java application from a JAR file while passing arguments, use the following syntax:
java -jar myapp.jar arg1 arg2 arg3
Components:
Inside the Java application, these arguments are stored in the args array, which can be accessed in the main method.
Here is a simple Java program that accepts command-line arguments and prints them.
public class JarArgumentsExample {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No arguments provided.");
} else {
System.out.println("Arguments received:");
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i + 1) + ": " + args[i]);
}
}
}
}
Execution:
java -jar JarArgumentsExample.jar Hello World 123
Output:
Arguments received:
Argument 1: Hello
Argument 2: World
Argument 3: 123
Command-line arguments can modify a Java program's behavior dynamically without requiring code changes. This is useful for passing data such as configuration settings, file paths, or numerical inputs.
The following program accepts two numbers from the command line, adds them, and prints the sum using Java command line arguments.
public class SumCalculator {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please provide two numbers");
return;
}
try {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
System.out.println("Sum: " + (num1 + num2));
} catch (NumberFormatException e) {
System.out.println("Invalid numbers provided");
}
}
}
Execution:
java SumCalculator 5 10
Output:
Sum: 15
Passing command-line arguments is easy if you're using an IDE like Eclipse. Just follow these steps:
java -jar myapp.jar arg1 arg2Command-line arguments in Java provide a powerful way to pass inputs dynamically without modifying source code. By using this feature, developers can enhance program flexibility, enabling users to specify parameters at runtime.
Understanding what is command line arguments in Java, argument handling, and JAR execution allows for better program control and optimization. Additionally, error handling and input validation ensure robust applications. Learning what is command line arguments in Java empowers developers to create interactive and scalable Java programs for various use cases, from simple calculations to complex system configurations.
Command-line arguments are inputs passed to a Java program at runtime via the terminal. They allow dynamic execution without modifying the source code.
You pass arguments when executing a Java program by providing values after the class name in the terminal. These arguments are stored in the args array inside the main method.
When running a Java application packaged as a JAR file, arguments can be passed after specifying the JAR filename. These arguments are then processed within the program.
Yes, but they are treated as strings. You need to convert them into appropriate numeric types before performing arithmetic operations.
If no arguments are passed, trying to access them directly may result in an error. It is recommended to check if arguments exist before using them.
Multiple arguments can be processed by iterating over the args array, allowing dynamic input handling based on the number of arguments provided.
In Eclipse and IntelliJ, command-line arguments can be set in the run configuration settings under the program arguments section before executing the Java application.
Prime Number Program in Java: Explained with Examples - Learn how to write a prime number program in Java with clear logic, optimized algorithms, examples, and interview-ready explanations. (8 min read)
Why Encapsulation in Java Matters: Learn with Code Snippets - Understand encapsulation in Java, a key object-oriented principle used to restrict direct access and protect internal data from unauthorized changes. (5 min read)
Master Binary Search in Java: Fast and Efficient Searching Explained - Learn Binary Search in Java with clear logic, easy code examples, and real-world applications. (5 min read)
Learn Bubble Sort in Java: Easy Sorting Technique Explained - Get a complete guide on bubble sort in Java, including coding examples and tips to understand this basic but important sorting algorithm. (6 min read)
Best Java Training Institutes in Hyderabad: Your Guide to Career Success - Find the best Java training institutes in Hyderabad for hands-on learning, placement support, and industry-recognized certifications. (5 min read)
Understanding Inheritance in Java: Key Concepts & Benefits Explained - Learn all about inheritance in Java with clear examples. Understand types, benefits & how it supports code reusability in object-oriented programming. (8 min read)
About NxtWave: NxtWave provides industry-recognized IT training and certifications to help students and professionals build successful careers in technology.
Contact: [email protected] | WhatsApp: +919390111761