Arrays and Strings · Introduction to Java Programming

Command Line Arguments

Watch lectures

Command Line Arguments

1. What They Are (beginner)

Command-line args = words typed after java ClassName → arrive as String[] args in main. Lets users pass input without Scanner (e.g. filenames, numbers).

2. Code — Echo + Sum (run from terminal!)

public class Args {
    public static void main(String[] args) {
        System.out.println("count=" + args.length); // how many words?
        for (int i = 0; i < args.length; i++)
            System.out.println(i + ":" + args[i]);
    }
}

Sum version (parse needed!):

int a = Integer.parseInt(args[0]); // "42" → 42 (String→int!)
int b = Integer.parseInt(args[1]);
System.out.println(a + b);

3. Traps

  • All args are String (parse numbers with Integer.parseInt / Double.parseDouble).
  • No args + args[0] → ArrayIndexOutOfBoundsException! Check args.length first.
  • Spaces split args: java Hi "Asha Kumar" (quotes = one arg!).

4. Exam Points

  • Echo + sum program with run commands — 5-7 marks, very frequent.
  • Parse + length-check — 3 marks, frequent.
Budget AppAndroid App

Pocketly on Android

Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.

← All Introduction to Java Programming modules