Example for command line arguments in java

Command-Line Arguments

A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.

The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run. For example, suppose a Java application called Sort sorts lines in a file. To sort the data in a file named friends.txt , a user would enter:

When an application is launched, the runtime system passes the command-line arguments to the application’s main method via an array of String s. In the previous example, the command-line arguments passed to the Sort application in an array that contains a single String : «friends.txt» .

Echoing Command-Line Arguments

The Echo example displays each of its command-line arguments on a line by itself:

The following example shows how a user might run Echo . User input is in italics.

java Echo Drink Hot Java Drink Hot Java

Note that the application displays each word — Drink , Hot , and Java — on a line by itself. This is because the space character separates command-line arguments. To have Drink , Hot , and Java interpreted as a single argument, the user would join them by enclosing them within quotation marks.

java Echo "Drink Hot Java" Drink Hot Java

Parsing Numeric Command-Line Arguments

If an application needs to support a numeric command-line argument, it must convert a String argument that represents a number, such as «34», to a numeric value. Here is a code snippet that converts a command-line argument to an int :

int firstArg; if (args.length > 0) < try < firstArg = Integer.parseInt(args[0]); >catch (NumberFormatException e) < System.err.println("Argument" + args[0] + " must be an integer."); System.exit(1); >>

parseInt throws a NumberFormatException if the format of args[0] isn’t valid. All of the Number classes — Integer , Float , Double , and so on — have parseXXX methods that convert a String representing a number to an object of their type.

Читайте также:  Edu omgpu ru grade report overview index php

Источник

Command Line Arguments in Java

Command Line Arguments in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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

package com.journaldev.examples; public class CommandLineArguments < public static void main(String[] args) < System.out.println("Number of Command Line Argument = "+args.length); for(int i = 0; i< args.length; i++) < System.out.println(String.format("Command Line Argument %d is %s", i, args[i])); >> > 
$ java com/journaldev/examples/CommandLineArguments.java Number of Command Line Argument = 0 

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

$ java com/journaldev/examples/CommandLineArguments.java "A" "B" "C" Number of Command Line Argument = 3 Command Line Argument 0 is A Command Line Argument 1 is B Command Line Argument 2 is C $ java com/journaldev/examples/CommandLineArguments.java 1 2 3 Number of Command Line Argument = 3 Command Line Argument 0 is 1 Command Line Argument 1 is 2 Command Line Argument 2 is 3 $ 

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

Step 1: Open the Class Run Configurations Settings

Eclipse Run Configurations

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

Step 2: Specify the Program Arguments in the Arguments Tab

Eclipse Command Line Arguments

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

Step 3: Click on the Run button

Eclipse Command Line Arguments Example

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. 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

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

Command Line Arguments in Java with Example

Scientech Easy

In this tutorial, we will learn about the command line arguments in Java with the help of example programs.

The command line arguments in Java allow the programmers to pass arguments (i.e. values) to the main() method during the execution of the program from the outside.

It represents the arguments passed to the main() method. To catch and store these arguments, the main() method has a parameter, String args[ ] as:

public static void main(String args[ ])

In the main() method, args[ ] is a one-dimensional array of string type. It can store a group of strings, passed to the main() method from the outside by the programmer.

The programmer should pass these arguments from the outside at the time of executing the program at the command prompt.

We can use these command line arguments or values as input in the Java program. Let’s understand it with the help of an example.

Simple Example of Command-line argument in Java

When we run a Java program from the command prompt, we can input values that get passed to the main() method as strings.

For example, suppose that we entered the following command to run CommandLine program from the command prompt, as:

C:\> java CommandLine hello 10 world

This command has three command-line arguments beyond the java CommandLine command: hello, 10, and world.

These three arguments are automatically passed into the main() method and stored in the args parameters (args[ ]) in the form strings.

This is because args[ ] is a one dimensional string type array. It can store as many command-line arguments as we enter.

To access these arguments inside main() method, we will need to use args with a subscript in square brackets. For example, args[0] is the first argument, args[1] is the second argument, args[3] is the third argument and so on.

In the current example, hello is stored as a string in args[0], 10 is stored as a string in args[1], and world is stored as a string in args[2]. See the below figure.

Java command line arguments example

How does Command Line Arguments work in Java?

The command line arguments works as follows:

1. When we will run CommandLine Java program, the operating system passes the list of arguments to the JVM.

2. Sometimes, the operating system modifies arguments list by interpreting their meanings and may pass a modified list of arguments to the JVM.

3. The JVM parses a list of arguments using a space as a separator.

4. It creates a string array whose length is the same as the number of argument values in the list.

5. It populates an array of string with elements in the arguments list sequentially.

6. Finally, JVM passes an array of string to the main() method of the CommandLine class that we are running.

7. If we do not provide command line argument, JVM creates a string array of length zero and passes it to the main() method.

8. We can also pass space-separated words as one argument. For it, we will need to enclose them in double quotes. We can also avoid the operating system interpretation of special characters by enclosing them in double quotes.

Command line arguments Example Programs

Let’s write a very simple Java program to demonstrate a command line argument in Java. In this example program, we will receive only one argument value and print it.

Program code 1:

Let us try to run this Java program through the command prompt.

Steps to run the above Java program

To compile and run java program from the command prompt, follow the all the below steps:

1. Save the program as CommandLine.java in the system.

2. Open the command prompt window and write the following command in the command prompt to compile the program:

3. After a successful compilation of the program, write the following command in the command prompt to run the program:

4. Now suppose we want to pass three argument values while running the program. So, we can pass the argument values after the class name. For example,

java CommandLine hello 10 world

Here, hello, 10, and world are argument values passed to the program through the command line. Now, we will get the following desired output of this program.

Output: First argument is: hello Second argument is: 10 Third argument is: world

In the above program, the main() method contains an array of strings named args[ ] as a parameter. This array of string stores all the arguments passed via the command line.

Note : Argument values are always stored as strings and always separated by white-space after the name of class.

How to print all values through command line arguments?

Let’s take an example program in which we will print all the arguments passed through the command line. For this purpose, we have used for loop for traversing the array.

Program code 2:

When we will execute the above program, the following output may generate at the command prompt:

C:\> javac CommandLine.java C:\> java CommandLine This is an example program for command line arguments.
Output: Command line arguments are: args[0]: This args[1]: is args[3]: an args[4]: example args[5]: program args[6]: for args[7]: command args[8]: line args[9]: arguments.

How to pass numeric command line arguments in Java?

In a Java program, the main() method only takes data of type string. Therefore, we can never pass numeric arguments (i.e. values) via the command line.

If we pass these numeric arguments to main(), they are converted into string and we can’t use them as numbers. So, we can’t perform any numeric operations with them.

But, we can convert these string argument values into numeric values with the help of parseInt() method of Integer class. Let’s take an example to understand it more clearly.

Program code 3:

public class NumericArguments < public static void main(String[] args) < for(String str: args) < // Converting string arguments into integer type. int argument = Integer.parseInt(str); System.out.println("Arguments in integer form are: " +argument); >> >

Let us try to run this program through the command line.

// compile the code javac NumericArguments.java // run the code java NumericArguments 20 45

In this command, 20 and 45 are command-line arguments. Now, the program may produce the following output.

Output: Arguments in integer form are: 20 Arguments in integer form are: 45

In the above example, we have used the parseInt() method of the Integer class to convert the string argument into an integer.

Similarly, we can use Double class’s parseDouble() and Float class’s parseFloat() methods to convert the string into double and float, respectively.

Note : If the passing arguments cannot be converted into a specific numeric value, then an exception named NumberFormatException occurs.

How to pass Command line arguments in Eclipse IDE

Using Run configurations, we can also pass command-line arguments to the main() method in Eclipse IDE. For this, just follow the all steps below:

Step 1: Write your Java program in Eclipse IDE.

Step 2: On the editor, right-click and go to “Run As” option. Inside it, choose the “Run Configurations…” option.

Step 3: When you will choose Run Configurations…, a pop-up window will open on the screen.

In the pop-up window, click on the Arguments tab. Now you enter your the command line argument values in the “Program arguments:” text box.

Step 4: After entering the values, click on the Run button. As you will click on the Run button, you will get the output on the console in Eclipse IDE.

Let’s take an example program in which we will calculate the factorial of a number in Eclipse IDE. We will pass the command line arguments to the main() method in Eclipse IDE.

Program code 5:

public class Factorial < public static void main(String[] args) < int i, fact = 1; int number = Integer.parseInt(args[0]); for(i = 1; i System.out.println("The factorial of " + number + " is " +fact); > >

To run this program, right click on the eclipse editor and go to Run As option. After that, select Run Configurations… Now click on the Arguments tab and write 4 in the Program arguments text box.

When you will click on Run button, you will get the following output.

Output: The factorial of 4 is 24

In this tutorial, you have learned command line arguments in Java with the help of some useful examples. Hope that you will have understood the basic concepts of command-line arguments and practiced all programs.

In the next tutorial, we will learn about recursion in Java with the help of examples.
Thanks for reading.

Источник

Оцените статью