Command-line Arguments

Command-line Arguments


Command-line Arguments

Summary: In this Command-line Arguments, you will understand how to pass data to a running Java program through command prompt.

command-line

: The line where we give the command is known as command-line. It is an imaginary line and nothing but the command prompt. It is another style of giving values to the program at runtime.
Here arguments are passed at running time (not readily at compile time); the traditional way is through method calls and taking input from keyboard. This requires the knowledge of parsing operations where a string is converted to a data type.

Following program is on passing Java command-line arguments.

Command-line Arguments

Output screen of Test.java

Let us see the writing the source code, compilation and execution. Writing the soruce code and compilation is as usual and as follows.

c:\snr\arrays> notepad Test.java // writing the source code
c:\snr\arrays> javac Test.java // compilation

c:\snr\arrays> java Test 15 20.65 world B true // execution

public static void main(String[] balaji)

Observe, the args is changed to balaji. Moreover, the square brackets are placed before the array object balaji which Java permits. After all, args is only an array object name which can be anything.

15, 20.65, world, B and true are the arguments passed, say, as command-line arguments. As long as you are concerned, they may be an integer, a double, a string etc. But they are converted into strings and passed to balaji array existing in the main() method. This is done implicitly by the JVM as balaji is a string array and an array stores similar data type value.

int x = Integer.parseInt(balaji[0]);
double y = Double.parseDouble(balaji[1]);

balaji[0] and balaji[1] are in string form and it is required to parse them (converting into data types) as they are used in product evaluation. With strings, printing can be done but not useful for arithmetic operations.

9 thoughts on “Command-line Arguments

Leave a Reply

Your email address will not be published. Required fields are marked *