Skip to main content
Engineering LibreTexts

17.9: Command-line Arguments

  • Page ID
  • Now that you know about arrays and strings, we can finally explain the args parameter for main that we have been ignoring since Chapter 1. If you are unfamiliar with the command-line interface, please read or review Appendix A.3.

    Continuing an earlier example, let’s write a program to find the largest value in a sequence of numbers. Rather than read the numbers from, we’ll pass them as command-line arguments. Here is a starting point:

    public class Max {
        public static void main(String[] args) {

    You can run this program from the command line by typing:

    java Max

    The output indicates that args is an empty array; that is, it has no elements:


    But if you provide additional values on the command line, they are passed as arguments to main. For example, if you run it like this:

    java Max 10 -3 55 0 14

    The output is:

    [10, -3, 55, 0, 14]

    But remember that the elements of args are strings. To find the maximum number, we have to convert the arguments to integers.

    The following fragment uses an enhanced for loop to parse the arguments (using the Integer wrapper class) and find the largest value:

    int max = Integer.MIN_VALUE;
    for (String arg : args) {
        int value = Integer.parseInt(arg);
        if (value > max) {
            max = value;
    System.out.println("The max is " + max);

    The initial value of max is the smallest (most negative) number an int can represent, so any other value is greater. If args is empty, the result is MIN_VALUE.