Skip to main content
Engineering LibreTexts

17.9: Command-line Arguments

  • Page ID
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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.

    This page titled 17.9: Command-line Arguments is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) .

    • Was this article helpful?