Reading history

Java Command-Line Arguments and Properties

7 min read 0 views

Read command-line arguments in Java, parse options safely, and load settings from system properties, environment variables and .properties files.

A program is more useful when you can change its behaviour without editing the code. Java gives you three ways to pass settings in from outside. Command-line arguments arrive in the String[] args of main. System properties are set with -D when you start Java. Environment variables come from the shell or server. On top of these, a .properties file can hold a whole list of settings. This lesson shows each one with a small tool you could really use.

In this lesson you will learn

  • What String[] args holds, and how to run a program with arguments
  • Parsing options like --name Rafi --times 2
  • Handling unknown options and bad numbers
  • Reading system properties and environment variables with defaults
  • Loading settings from a .properties file

You should know how to run a Java program, switch and exception handling.

Command-Line Arguments

Everything you type after the class name becomes one element of args, split at spaces:

javac Main.java
java Main --name Rafi --times 2 --shout
# Java 11 and later can also run a single file directly:
java Main.java --name Rafi

To keep this lesson’s output fixed, the program below calls a run method with sample arrays, exactly as if you had typed them.

import java.util.*;

public class Main {
    // A small command-line tool: java Main --name Rafi --times 2 --shout
    static void run(String[] args) {
        System.out.println("args.length = " + args.length + ", args = " + Arrays.toString(args));
        String name = "World";
        int times = 1;
        boolean shout = false;
        for (int i = 0; i < args.length; i++) {
            switch (args[i]) {
                case "--name"  -> name = args[++i];
                case "--times" -> times = Integer.parseInt(args[++i]);
                case "--shout" -> shout = true;
                default -> {
                    System.out.println("  Unknown option: " + args[i]);
                    return;
                }
            }
        }
        String msg = "Hello, " + name + "!";
        for (int i = 0; i < times; i++) System.out.println("  " + (shout ? msg.toUpperCase() : msg));
    }

    public static void main(String[] args) {
        // Here we call run() with sample arrays, as if typed on the command line
        run(new String[]{});
        run(new String[]{"--name", "Rafi", "--times", "2", "--shout"});
        run(new String[]{"--colour", "red"});
        try {
            run(new String[]{"--times", "two"});
        } catch (NumberFormatException e) {
            System.out.println("  Bad number: " + e.getMessage());
        }
    }
}

Output

args.length = 0, args = []
  Hello, World!
args.length = 5, args = [--name, Rafi, --times, 2, --shout]
  HELLO, RAFI!
  HELLO, RAFI!
args.length = 2, args = [--colour, red]
  Unknown option: --colour
args.length = 2, args = [--times, two]
  Bad number: For input string: "two"
  • With no arguments, args is an empty array, not null. The program falls back to its defaults: “World” and 1 time.
  • args[++i] moves to the next element and reads it, because an option like --name is followed by its value.
  • Everything in args is a String. Integer.parseInt turns “2” into 2, and throws NumberFormatException for “two”.
  • An unknown option prints a clear message and stops, instead of silently doing the wrong thing.
  • If a value has spaces, put it in quotes: java Main --name "Rafi Hasan" passes it as one argument.

System Properties, Environment Variables and Settings Files

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        // 1. System properties: set with  java -Dkey=value Main
        System.setProperty("app.mode", "test");               // the same as -Dapp.mode=test
        System.out.println("app.mode     = " + System.getProperty("app.mode"));
        System.out.println("app.lang     = " + System.getProperty("app.lang", "bn")
            + "  (default used: not set)");
        System.out.println("Java version = " + Runtime.version().feature());
        System.out.println("line.separator is \\n? " + System.lineSeparator().equals("\n"));

        // 2. Environment variables: set by the shell, read-only in Java
        String home = System.getenv("HOME");
        System.out.println("HOME is set? " + (home != null));
        System.out.println("APP_KEY      = " + Objects.requireNonNullElse(System.getenv("APP_KEY"), "(missing)"));

        // 3. A .properties file for settings
        String file = """
            # school app settings
            school.name = Ideal School
            exam.passMark = 33
            exam.year=2026
            """;
        Properties p = new Properties();
        p.load(new StringReader(file));                       // normally new FileReader("app.properties")
        System.out.println("school.name  = " + p.getProperty("school.name"));
        int pass = Integer.parseInt(p.getProperty("exam.passMark"));
        System.out.println("passMark + 7 = " + (pass + 7));
        System.out.println("exam.board   = " + p.getProperty("exam.board", "Dhaka"));
        System.out.println("keys         = " + new TreeSet<>(p.stringPropertyNames()));
    }
}

Output

app.mode     = test
app.lang     = bn  (default used: not set)
Java version = 21
line.separator is \n? true
HOME is set? true
APP_KEY      = (missing)
school.name  = Ideal School
passMark + 7 = 40
exam.board   = Dhaka
keys         = [exam.passMark, exam.year, school.name]
  • System properties are key–value pairs inside the running Java program. You normally set them on the command line, as in java -Dapp.mode=test Main. getProperty(key, default) returns the default when a key is missing.
  • Java also sets many properties itself, such as java.version, user.home and os.name. Runtime.version().feature() gives the main Java version as a number.
  • Environment variables come from the operating system. System.getenv returns null if a variable is not set, so the program uses requireNonNullElse to show a fallback.
  • Secrets such as API keys or database passwords belong in environment variables, not in your source code, where anyone who sees the code would see them.
  • A .properties file holds one key = value per line. Lines starting with # are comments, and spaces around = are ignored. Properties.load reads it; values are always strings, so convert numbers yourself.
  • The program reads from a StringReader so you can see the file’s contents. In a real app you would use new FileReader("app.properties") inside try-with-resources.
SourceSet withRead withGood for
Argumentsjava Main a bargs[0]Input that changes every run
System propertyjava -Dkey=value MainSystem.getPropertySwitches such as a test mode
Environment variableShell or server settingsSystem.getenvSecrets and server addresses
Properties fileA text fileProperties.loadMany settings kept together

Common Mistakes

  1. Reading args[0] without checking args.length. With no arguments it throws ArrayIndexOutOfBoundsException.
  2. Putting -D after the class name. java Main -Dx=1 passes “-Dx=1” as an argument. Options for Java go before the class name.
  3. Forgetting that values are strings. Parse numbers and booleans yourself, and handle bad input.
  4. Writing passwords into code or into a properties file in your project. Use environment variables.
  5. Assuming an environment variable exists. getenv can return null.

Practice Exercises

Exercise 1. Write a main that adds up all the numbers given as arguments, so java Main 5 10 20 prints 35.

Show answer
public static void main(String[] args) {
    int sum = 0;
    for (String a : args) sum += Integer.parseInt(a);
    System.out.println(sum);
}

Exercise 2. Read a port number from the property app.port, using 8080 if it is not set.

Show answer
int port = Integer.parseInt(System.getProperty("app.port", "8080"));
// or: Integer.getInteger("app.port", 8080)

Run it with java -Dapp.port=9000 Main to change the port.

Frequently Asked Questions

What is String[] args in Java?

It is the array of command-line arguments passed to main. Each word typed after the class name becomes one string in the array. If no arguments are given, args is an empty array with length 0.

What is the difference between System.getProperty and System.getenv?

System.getProperty reads Java system properties, which Java sets itself or you pass with -D when starting the program. System.getenv reads environment variables from the operating system. Both return text, and both can be missing.

Summary

  • args holds the words typed after the class name; it is never null.
  • Check the length, parse numbers carefully, and reject unknown options.
  • Set system properties with -D before the class name and read them with defaults.
  • Keep secrets in environment variables.
  • Use a .properties file for a group of settings.

Next: Java Project: Student Result System.

Lessons are also marked complete when you click Next.

Leave a Reply

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