Home » Command line Arguments in Java

Command line Arguments in Java

Command line Arguments in Java

The java command-line argument is an argument i.e. passed at the time of running the java program.The arguments passed from the console can be received in the java program and it can be used as an input.So, it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so on) numbers of arguments.

In Java, the main() method plays a crucial role in receiving these command line argument. It acts as a gatekeeper, accepting the inputs you provide when running the program. The program can then use these arguments to customise its behaviour based on your instructions.

command-line-arguments.png

How To Pass Command Line Arguments In Java

In Java programming, you can pass command line arguments to a program, providing it with additional information or instructions. Here’s a simple guide on how to pass command line arguments:

Open your command prompt or terminal.

Navigate to the directory where your Java program is located.

Compile the Java program: javac MyProgram.java.

Run the program with command line arguments: java MyProgram 10 20.

That’s it! The program will receive the command line argument and you can access them in your Java program using the String[] args parameter in the main() method.

Simple example of command-line argument in java

public class CommandLineArgumentsExample {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No command line arguments provided.");
} else {
System.out.println("Command line arguments:");
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i + 1) + ": " + args[i]);
} }
} }
Java

Replace arg1, arg2, arg3, etc. with the arguments you want to pass. The program will then display each argument on a new line.

  • Output
Arguments provided:
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3
Java

Command line arguments allow users to provide input to a program at runtime without modifying the source code. This makes the program more flexible and versatile as it can be customized for different use cases without recompilation.

Overall, using command line argument enhances the usability, flexibility, and automation capabilities of Java programs.

Conclusion

Command line arguments in Java provide a convenient way to pass inputs to a program during runtime. They offer flexibility and customization, allowing you to modify the behavior of your program without changing its code.

Frequently Asked Questions