For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
Command line arguments in Java are a powerful feature that allows users to pass information to a Java program during its execution, directly from the command line. This mechanism is frequently used in automation, scripting, and configuration-based applications where user input is provided externally rather than through interactive prompts or GUI-based forms.
When you execute a Java program using the java command in the terminal, you can provide a series of values—known as command line arguments—which are captured in the main() method of your program. These arguments are stored in the String[] args array, allowing the program to use them at runtime.
This concept not only enhances flexibility but also helps in customizing application behavior without changing the source code.
Learning Java? Take the next step with a full-fledged Software Engineering course designed for real-world success.
In Java, command line arguments are the values passed to the main() method when a program is launched. The Java Virtual Machine (JVM) automatically captures these inputs and stores them in the String[] args array.
public static void main(String[] args)
Boost your development career with these top-rated tech programs:
• upGrad Full Stack Development Bootcamp
• AI-Powered Full Stack Development by IIIT Bangalore
• upGrad Cloud Computing & DevOps Certificate
Let’s look at a simple example.
Example: HelloUser.java
public class HelloUser {
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("Hello, " + args[0] + "!");
} else {
System.out.println("Hello, user!");
}
}
}
Compile and Run:
javac HelloUser.java
java HelloUser Alice
Output:
Hello, Alice!
If no name is passed, it defaults to "user".
Must explore: Exploring Java Architecture: A Guide to Java's Core, JVM and JDK Architecture
All command line arguments are stored as strings in Java. You must convert them manually to other types (e.g., int, double).
public class AddNumbers {
public static void main(String[] args) {
if (args.length == 2) {
try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println("Sum: " + (a + b));
} catch (NumberFormatException e) {
System.out.println("Please enter valid integers.");
}
} else {
System.out.println("Provide exactly two integers.");
}
}
}
Run:
java AddNumbers 5 10
Output:
Sum: 15
Also read: Array in Java: Types, Operations, Pros & Cons
Before accessing any command line argument, it’s crucial to verify that the expected number of arguments has been provided using args.length. Failing to do so can lead to an ArrayIndexOutOfBoundsException, causing your program to crash.
For example, if your program expects two arguments but receives only one, attempting to access args[1] will result in an error. By checking the argument count beforehand, you ensure that your program behaves reliably and can respond with informative messages when arguments are missing.
Must explore: String Array In Java: Java String Array With Coding Examples
Using meaningful variable names improves readability, maintainability, and clarity in your code. Instead of referencing arguments directly through indices like args[0] or args[1], assign them to clearly named variables such as String username = args[0]; or String filePath = args[1];. This makes the purpose of each argument immediately obvious to anyone reading the code, which is especially valuable in collaborative or large-scale projects.
Command line arguments are always passed as strings, and converting them into other data types (like integers or doubles) can lead to runtime exceptions if the input format is incorrect. For example, trying to convert "abc" to an integer will throw a NumberFormatException.
To avoid such crashes and provide a better user experience, wrap your parsing logic in try-catch blocks and display helpful error messages guiding the user to provide valid input. This approach ensures your program can fail gracefully and continue running where possible.
As projects grow, parsing and validating command-line arguments manually becomes inefficient. Let's look at how to enhance your programs professionally.
A robust library that helps define options, parse arguments, and display help.
import org.apache.commons.cli.*;
public class CLIExample {
public static void main(String[] args) throws ParseException {
Options options = new Options();
options.addOption("n", "name", true, "User's name");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("n")) {
System.out.println("Hello, " + cmd.getOptionValue("n") + "!");
}
}
}
A modern and annotation-based library for rich CLI tools.
import picocli.CommandLine;
import picocli.CommandLine.Option;
public class PicoExample implements Runnable {
@Option(names = {"-n", "--name"}, description = "Name of the user")
String name;
public void run() {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
CommandLine.run(new PicoExample(), args);
}
}
Also read: How to Code, Compile, and Run Java Projects: A Beginner’s Guide
Good CLI apps should support --help or -h to guide users.
if (args.length == 0 || args[0].equals("--help")) {
System.out.println("Usage: java ProgramName <arg1> <arg2>");
return;
}
CLI libraries like Apache CLI and Picocli auto-generate help sections for you.
Passing sensitive data (like passwords or API keys) through command line arguments can expose them to system-level process monitors.
Best practice: Use environment variables or secure prompts instead.
import java.io.Console;
Console console = System.console();
String password = console.readPassword("Enter password: ");
Some characters (like <, >, &, |) are interpreted by the shell. To pass them literally, wrap them in quotes:
java MyApp "<filename>"
Also, be cautious with spaces in arguments—quote them too:
java MyApp "Hello World"
This helps users not comfortable with the terminal to test argument-based applications.
Feature | Java | Python | C/C++ |
Entry Point | main(String[] args) | sys.argv[] | int main(int argc, char* argv[]) |
Argument Type | Always String | Always String | Raw C strings |
Libraries for Parsing | Apache CLI, Picocli | argparse, click | getopt, boost::program_options |
Java requires explicit type conversion, just like C/C++, whereas Python provides more dynamic handling.
Command line arguments in Java provide a flexible way to pass data into applications at runtime. While the basic mechanism using String[] args is powerful enough for simple tasks, advanced scenarios benefit greatly from parsing libraries, help options, input validation, and secure handling.
Whether you're building automation scripts, developer tools, or system utilities, mastering command line arguments gives your Java applications more power and versatility.
Command line arguments in Java are values passed to a program when it is run from the terminal or command prompt. They are stored in the String[] args array of the main() method, allowing the program to receive dynamic input at runtime. This feature is commonly used for automation, configuration, and user-driven customizations without altering the source code.
To access command line arguments in Java, you refer to the String[] args array passed to the main() method. You can access individual arguments using array indices like args[0], args[1], etc., ensuring you check the length of the array to prevent ArrayIndexOutOfBoundsException.
Command line arguments are always passed as strings, so if you want to use them as other data types, such as integers or floats, you need to convert them manually. You can use methods like Integer.parseInt() for integers and Double.parseDouble() for floating-point numbers. Always handle exceptions like NumberFormatException to ensure the program doesn’t crash with invalid input.
If no command line arguments are provided, the args[] array will be empty, and its length will be zero. In such cases, accessing elements in the array without checking args.length can result in an ArrayIndexOutOfBoundsException. Therefore, it’s important to include conditionals to handle scenarios where arguments may or may not be passed.
Java itself doesn’t impose a strict limit on the number of command line arguments you can pass; the operating system typically determines this based on the system's command line buffer size. While most systems support several thousand characters, it's best practice to keep the number of arguments manageable to ensure efficient handling and debugging.
Yes, spaces are allowed in command line arguments, but they will split a single argument into multiple parts unless you enclose the argument in quotation marks. For example, if you want to pass a filename with spaces, you would use quotes: "My Document.txt".
In Eclipse, you can pass arguments by going to the Run Configurations > Arguments tab, where you can type in the desired arguments for your program. In IntelliJ, navigate to Run > Edit Configurations, then input arguments in the Program arguments field. These methods allow you to simulate passing arguments without needing to run the program from the command line.
While manually handling command line arguments works fine for basic programs, using libraries like Apache Commons CLI or Picocli makes parsing more efficient and user-friendly. These libraries provide features like handling options and flags, generating help messages, and supporting complex argument structures.
You can implement a --help flag to provide users with usage instructions on how to run the program, including available arguments and their expected formats. If you're using a library like Apache Commons CLI or Picocli, they automatically generate detailed help documentation. This is a good practice to improve user experience and make your CLI application more intuitive.
Command line arguments are not the most secure way to pass sensitive information, as they can be exposed in process lists or command history files on some operating systems. For secure data transmission, consider using environment variables or prompting users to input sensitive information interactively using Console.readPassword().
Yes, Java fully supports Unicode, meaning you can pass and process command line arguments in any language, including non-English characters like Chinese, Arabic, or Russian. However, ensure that the terminal or script you're using supports UTF-8 encoding to avoid misinterpretation of characters.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.