2

Possible Duplicate:
What is “String args[]”? in Java

So I recently (well, three days ago) started teaching myself Java, with absolutely zero previous programming experience unless you count HTML/CSS.

Now I've been looking through both books and online tutorials, including the Sun tutorials. I don't quite understand what the purpose of (string args[]) in a method is.

What I've got from looking online is that when using the console to run a program, it substitutes whatever comes after ">Java myprogram" in place of the "args".

Firstly, is that correct? If so, why would you do that?

Cheers!

Community
  • 1
  • 1
Adam
  • 345
  • 2
  • 15
  • 6
    Take a look at this [question](http://stackoverflow.com/q/890966/334274). – Jivings Dec 12 '12 at 19:29
  • 3
    Be sure that you have "String" and not "string". Java's case sensitive. The first one means java.lang.String; the second one....? – duffymo Dec 12 '12 at 19:30
  • @duffymo ...Is a compiler error. – Jivings Dec 12 '12 at 19:31
  • How are you learning? Better follow a tutorial, they explain these things – Miserable Variable Dec 12 '12 at 19:31
  • @Adam Answer 1: Yes it could be used to access user input through command line. Answer 2: Hardly anyone use that, java has AWT swing to take user input. – Smit Dec 12 '12 at 19:32
  • 1
    @smit Wat. Except for every Java command line program that takes arguments. – Jivings Dec 12 '12 at 19:35
  • @Jivings Yes thats true +1. But after my student life I never saw anyone make use of that. – Smit Dec 12 '12 at 19:37
  • @Jivings - Not so if you happen to have a "string" class. But I do agree that the JVM won't be running that version of main when you start up, because it looks for a precise signature when it does so. This method won't make the cut. – duffymo Dec 12 '12 at 20:37

2 Answers2

4

The String[] args which can be written as String args[] or String ... args is an array of the arguments you gave the program.

why would you do that?

So you can give your program inputs on the command line. It isn't used in Java programs so often but it is quite commong for command line utilities to take arguments e.g.

In this case the MyClass.java is an argument.

javac MyClass.java

Or like the following has three arguments.

java -cp . MyClass
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

This is, more or less, correct. Every whitespace-separated word that comes after java Program is stored into an array of Strings, which happens to be called args.

An example on how to use this for your benefit:

public class Test {
    public static void main(String[] args)
    {
        if(args.length > 0)
        {
            System.out.println(args[0] + "\n");
        }
    }
}

Compile this with:

> javac Test.java

And then run it:

> java Test Yes

"Yes" is then printed to your screen.

Chris Forrence
  • 10,042
  • 11
  • 48
  • 64