Command Line Arguments in Java With Examples

Command-line arguments in Java are used to pass arguments to the main program. If you look at the Java main method syntax, it accepts String array as an argument.

When we pass command-line arguments, they are treated as strings and passed to the main function in the string array argument. The arguments have to be passed as space-separated values.

We can pass strings and primitive data types as command-line arguments. The arguments will be converted to strings and passed into the main method string array argument.

Command Line Arguments in Java

Let’s say we have a simple java class to print command line arguments values.

If we run this class without any arguments, the output will be as follows.

Now, let’s pass some arguments to the main class. We have to pass the arguments as space-separated values.

Note: If you are using Java 11 or higher, you don’t need to compile the java source file explicitly. The java command will compile and run the class simultaneously.

How to Pass Command Line Arguments in Eclipse

We can also pass command-line arguments to a program in Eclipse using Run Configurations.

Step 1: Open the Class Run Configurations Settings

From the class editor, right click and chose “Run As” -> “Run Configurations…”.

Eclipse Run ConfigurationsEclipse Run Configurations

Step 2: Specify the Program Arguments in the Arguments Tab

In the pop up window, click on the Arguments tab. Then provide the command line arguments value in the “Program Arguments” text box.

Eclipse Command Line ArgumentsEclipse Command Line Arguments

Step 3: Click on the Run button

When you will click on the Run button, the run configurations will be saved and the program will execute with the specified command-line arguments.

eclipse-command-line-arguments-exampleEclipse Command Line Arguments Example

If you run the class again, the saved run configuration will be used. So if you want to override the command-line arguments or remove them, you will have to open the run configurations window and make necessary changes.

Conclusion

The command-line arguments are used to provide values that are essential to run the program. For example, we can specify the database credentials to be used by the program. We can specify the configuration file location from where the program should pick the required values.

Reference: Command-Line Arguments Oracle Docs

By admin

Leave a Reply