Can someone explain the (String [] args) of the main method.

Recommended Answers

All 4 Replies

Sure - Those are the command line arguments that are passed to the program.
Just like any method in Java that can accept parameters, the main method accepts the String args[] as a parameter. When you run the program:

programName param1 param2 param3

The program will start with the args array populated in such a way that

args[0] = param1;
args[1] = param2;
args[2] = param3;

You can have as many parameters as you see fit :)

It allows the program to take arguments from the command line. Not used very often, but it allows you to do something like

public class DoStuffToStrings{
public static void main(String[] args)
  {
  for (String s:args)
    { 
     //do stuff to the strings
    }
  }

}

You can call this as follows:
> java DoStuffToStrings banana apple wombat fruitbat

and the array args will contain the values "banana", "apple", "wombat", and "fruitbat", so whatever "do stuff" entails, it'll happen to those strings.

Thanks for the clear explanation Jon. I've learned something new today :D

Glad to hear it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.