Command-Line Arguments

 


 

Overview

Java parses command-line arguments specified after the name of the class:

java Class arg1 arg2 arg3 ...

The runtime system passes the command-line arguments to the app's main method via an array of Strings called args.

  1. To display command-line arguments:

    public class Echo 
    {
        public static void main (String[] args) 
        {
            for (int i = 0; i < args.length; i++)
                System.out.println(args[i]);
        }
    }
    
    
    $ java Echo Drink Hot Java
    Drink 
    Hot 
    Java
    

  2. To display the output on a single line, enclose the arguments in double quotes:

    $ java Echo "Drink Hot Java"
    Drink Hot Java
    

  3. To display the number of command-line arguments:

    public class Echo 
    {
        public static void main (String[] args) 
        {
            numberOfArgs = args.length;
            System.out.println(numberOfArgs);
        }
    }
    

  4. To parse numeric command-line arguments, convert String arguments to a number. For example, to convert an argument of "144" to an int:

    int firstArg;
    if (args.length > 0)
        firstArg = Integer.parseInt(args[0]);
    

    parseInt throws a NumberFormatException if the format of args[0] isn't valid.

 


 

 

 

Home