Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String [ ] args

 
Parth Sagdeo
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is that, and what does it do?
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is how you access the arguments passed to your program from the java command.

"java MyProgram alpha beta gamma" will pass your MyProgram.main() method a 3 element array of strings looking like this:
String[] args = { "alpha", "beta", "gamma" };
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A String array is the argument type to the main method used as a Java entry point:

public static void main(String[] args){ ... }

Any legal identifier can be used for this array, although "args" or "argv" are probably the most common (for "arguments" and "argument values" respectively).

The general purpose of this array is a means to pass initial information into a program. When running from the Command Line, arguments can be added after the file name, separated by spaces. For example, "c:\>java FileName Zero One" will invoke the main method of FileName.class, with "Zero" and "One" as elements of the String array passed to that method.

Try compiling the following code, then run with the following commands:
  • java MainArgs
  • java MainArgs what is this


  • Note that args (or whatever you might call it) is like any other argument, in that the reference to the String array is local to the main method; so it's legal (although not advisable) to define another String[] called "args" elsewhere in the class. Also note that a main method can be called like any other method -- it is not restricted to being invoked from the Command Line.
    [ January 03, 2005: Message edited by: marc weber ]
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic