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.

public class Test
{
  public static  void main(String[] balaji)
  {
    System.out.println("Element count: " + balaji.length);
    System.out.println("2nd argument passed: " + balaji[1]);

    System.out.println("\nRetrieving the elements passed");
    for(int i=0; i
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.

10 thoughts on “Command-line Arguments”

  1. I got the build failed for the above programe carried out in NetBeans.
    The following is the exception report.
    kindly clarify and enlighten me.
    Element count: 0
    Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 1
    at test.Test.main(Test.java:16)
    C:\Users\DDRAO\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:52: Java returned: 1
    BUILD FAILED (total time: 0 seconds)

  2. If I print the value of X and Y without any conversion.. What will be printed?.some hexadecimal value or some invalid string?

Leave a Comment

Your email address will not be published.