Java Command-Line Arguments

In the last lesson you learned about Java formatting output. But what if you want to hand your program some values before it starts, without a Scanner prompt? That is what command-line arguments are for.

🤔 Why command-line arguments?

A Scanner tool stops and waits for the user to type each value. Slow for a quick tool you run all day. Command-line arguments are values you type right next to the program name when you launch it.

  • The program reads them at once. No waiting, no prompts.
  • You already use this with java MyProgram. Extra words after the name become arguments.
  • Compilers, file copiers, and backup scripts all take settings this way.
  • It is fast and scriptable, so you will reach for it often.

📦 Where the arguments arrive

You have written main many times. The part inside the brackets is what catches the arguments.

public static void main(String[] args) {
}
  • String[] args is an array of Strings, a numbered list of values.
  • It holds every word you typed after the program name.
  • Java fills it in automatically before main starts. You only read from it.
  • args is short for “arguments”. Any name works, but everyone uses args, so keep it.

▶️ Passing arguments from the terminal

You run a program by typing java and the class name. Any extra words after that become arguments. This program prints back the first thing you pass it.

public class Echo {
public static void main(String[] args) {
System.out.println("You passed: " + args[0]);
}
}

args[0] is the first item. Arrays count from 0, not 1, so the first argument sits at index 0. Run it with a word after the name.

Output

java Echo hello
You passed: hello

hello landed in args[0]. Change it and that new value prints. The code never changed, only the value you handed it. That is the power here.

Pass more than one argument by separating them with spaces. Each word becomes its own item.

public class ShowArgs {
public static void main(String[] args) {
System.out.println("First: " + args[0]);
System.out.println("Second: " + args[1]);
}
}

Output

java ShowArgs hello 42
First: hello
Second: 42
  • hello went to args[0], 42 went to args[1].
  • Spaces split one argument from the next.
  • For a value with a space inside, like a full name, wrap it in double quotes: java ShowArgs "Riya Sharma" 42.

🔢 How many arguments came in?

You will not always know how many arguments came in. Every array knows its own size, read with args.length. This program reports the count and lists each one.

public class CountArgs {
public static void main(String[] args) {
System.out.println("You passed " + args.length + " arguments.");
for (int i = 0; i < args.length; i++) {
System.out.println("args[" + i + "] = " + args[i]);
}
}
}
  • args.length is the number of items.
  • The loop walks from index 0 up to that count, printing each item.
  • It stops at i < args.length, not i <= args.length. The last valid index is one less than the length, because counting starts at 0.

Output

java CountArgs apple banana cherry
You passed 3 arguments.
args[0] = apple
args[1] = banana
args[2] = cherry

With no arguments, args.length is 0 and the loop never runs. The array still exists, just empty. Reading args[0] on an empty array will crash. We deal with that next.

⚠️ Arguments are always text

The most important fact: arguments always arrive as Strings. Type 42 and Java sees the characters 4 and 2 as text, not the number. So you cannot do math on them directly. Look at what goes wrong if you forget this.

public class BadAdd {
public static void main(String[] args) {
System.out.println(args[0] + args[1]); // ❌ joins text, does not add
}
}

Output

java BadAdd 10 20
1020

You wanted 30 but got 1020. The + glued two strings together because both sides were text. To do math, turn the text into a number first:

  • Integer.parseInt turns a String into an int.
  • Double.parseDouble turns a String into a double.
public class GoodAdd {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println(a + b); // ✅ real addition now
}
}

Integer.parseInt(args[0]) reads the text and gives back a real int. Now the + adds the numbers properly.

Output

java GoodAdd 10 20
30

For decimals, swap in Double.parseDouble. So double price = Double.parseDouble(args[0]); reads 9.99 as a real decimal you can multiply.

🧮 A worked example: a calculator

Let’s put the pieces together. This tool takes two numbers from the command line and prints their sum.

public class Calculator {
public static void main(String[] args) {
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
int sum = first + second;
System.out.println(first + " + " + second + " = " + sum);
}
}
  • Read both arguments and parse each into an int.
  • Add them and print a clear result line.
  • The text join in the last line is fine. We want the numbers shown in a sentence, not added into it.

Output

java Calculator 15 27
15 + 27 = 42

Change the numbers and the answer changes. The program is reusable, unlike hard-coding the values inside the code.

🛡️ Check the length before you read

That calculator has a hidden problem. Run it with no numbers and args[0] points at an item that does not exist, crashing with an ArrayIndexOutOfBoundsException (you asked for an index past the end of the array). The fix: check args.length first, and read only if enough arguments are present.

public class SafeCalculator {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please pass two numbers. Example: java SafeCalculator 5 7");
return;
}
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
System.out.println(first + second);
}
}
  • The if checks that we have at least two arguments.
  • If not, it prints a helpful message and return stops main before any unsafe read.
  • This small habit turns an ugly crash into a clear message.

Output

java SafeCalculator
Please pass two numbers. Example: java SafeCalculator 5 7

👋 A greeting that uses args[0]

One more example, this time with text instead of numbers. It greets whoever you name, and falls back to a default if you name nobody.

public class Greet {
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("Hello, " + args[0] + "!");
} else {
System.out.println("Hello, friend!");
}
}
}

If at least one argument came in, we greet args[0] by name, otherwise a friendly default. No parsing needed, because a name is already text, which is what args holds.

Output

java Greet Alex
Hello, Alex!

💻 Passing arguments from an IDE

You will not always run from a terminal. IDEs like IntelliJ IDEA or Eclipse have a settings box called Program arguments in the run configuration. Same idea as the terminal, just typed in a settings window.

  • Open the run configuration for your class.
  • Find the field named “Program arguments”.
  • Type your values there, separated by spaces.
  • Run as normal. The IDE passes them straight into args.

⚠️ Common Mistakes

These mistakes come up over and over. Name them so you can spot them fast.

  • Reading an index without checking the length. This is the top cause of crashes here.
String name = args[0]; // ❌ crashes with ArrayIndexOutOfBoundsException if no args
if (args.length > 0) { // ✅ check first, then read
String name = args[0];
}
  • Forgetting that arguments are text. Trying to add them directly joins strings instead of doing math.
System.out.println(args[0] + args[1]); // ❌ "10" + "20" gives "1020"
int sum = Integer.parseInt(args[0]) + Integer.parseInt(args[1]); // ✅ gives 30
  • Passing text where a number is expected. If the user types a word, Integer.parseInt throws a NumberFormatException, because the text is not a valid number.
int n = Integer.parseInt(args[0]); // ❌ crashes if args[0] is "hello"

The fix: make sure the value really is a number before you parse, or handle the error, which you will learn in the exceptions lessons.

✅ Best Practices

Build these habits and your command-line tools stay solid.

  • Always check args.length before reading by index. Never assume an argument is there.
  • Parse text to numbers explicitly. Use Integer.parseInt for whole numbers and Double.parseDouble for decimals.
  • Print a helpful usage message. When arguments are missing, tell the user exactly what to pass and show an example.
  • Keep the args name. It is the convention everyone expects, so stick with it.
  • Wrap multi-word values in quotes. Use "Riya Sharma" so the terminal keeps it as one argument.

🧩 What You’ve Learned

Nice work. You can feed values to a program at launch now.

  • ✅ The String[] args parameter of main holds the values you pass when you run the program.
  • ✅ You read arguments by index, like args[0], and counting starts at 0.
  • args.length tells you how many arguments arrived.
  • ✅ Arguments are always Strings, so parse them with Integer.parseInt or Double.parseDouble for math.
  • ✅ Always check args.length before reading, to avoid an ArrayIndexOutOfBoundsException.
  • ✅ You can pass arguments from the terminal after the class name, or from an IDE run configuration.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What does the args parameter of main hold?

    Why: args is filled with the command-line arguments you pass after the program name when you launch it.

  2. 2

    You run 'java App hello 42'. What is args[0]?

    Why: The class name is not part of args. The first argument after it, hello, sits at args[0].

  3. 3

    Why must you use Integer.parseInt on a number argument?

    Why: All arguments come in as Strings, so you must parse the text into a real int before doing math.

  4. 4

    How do you avoid an ArrayIndexOutOfBoundsException when reading args[0]?

    Why: Check args.length first, and only read by index when enough arguments are present.

🚀 What’s Next?

You can pass values in and parse them now. Next, let’s learn how a program makes decisions based on those values, so it can react differently depending on what it gets.

Java if Statement

Share & Connect