Understanding args[] Indexing and Example
In Java, command line arguments are passed to the program through a String array called args[] in the main() method. Each value given in the command line becomes an element in this array. Just like other arrays in Java, indexing starts from 0.
Example:
class Main {
public static void main(String[] args) {
System.out.println("Student name: " + args[0]);
System.out.println("City: " + args[1]);
System.out.println("Country: " + args[2]);
}
}
Command with Quoted Inputs:
D:/shikshasanchar/> java Main "Simran Saini" "Panipat" "India"
Output:
Student name: Simran Saini
City: Panipat
Country: India
Explanation:
In this example, the input values are enclosed in double quotes, which ensures that multi-word strings like "Simran Saini" are treated as a single argument. This works because Java uses a space character as the default delimiter to split input into separate arguments. When values are quoted, the delimiter (space) is ignored within the quotes.
Stored in args[]:
| Index | Value |
|---|---|
| args[0] | Simran Saini |
| args[1] | Panipat |
| args[2] | India |
Command Without Quotes (Using Delimiters Normally):
java Main Simran Saini Panipat India
Since double quotes are not used, the default delimiter (space) separates each word:
| Index | Value |
|---|---|
| args[0] | Simran |
| args[1] | Saini |
| args[2] | Panipat |
| args[3] | India |
So the output would be:
Student name: Simran
City: Saini
Country: Panipat
Note that the value “India” will be ignored unless you use it in args[3].
Accessing Invalid Index:
Trying to access more arguments than provided results in: ArrayIndexOutOfBoundsException
So always be careful while accessing indexes, especially when input is optional.
Summary:
- args[] stores command line inputs as strings.
- Java uses space as the default delimiter to separate arguments.
- Use double quotes if your input contains spaces.
- Always check the number of arguments before accessing indexes to avoid errors.