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.

Welcome to ShikshaSanchar!

ShikshaSanchar is a simple and helpful learning platform made for students who feel stressed by exams, assignments, or confusing topics. Here, you can study with clarity and confidence.

Here, learning is made simple. Notes are written in easy English, filled with clear theory, code examples, outputs, and real-life explanations — designed especially for students like you who want to understand, not just memorize.

Whether you’re from school, college, or someone learning out of curiosity — this site is for you. We’re here to help you in your exams, daily studies, and even to build a strong base for your future.

Each note on this platform is carefully prepared to suit all levels — beginner to advanced. You’ll find topics explained step by step, just like a good teacher would do in class. And the best part? You can study at your pace, anytime, anywhere.

Happy Learning! – Team ShikshaSanchar