Command Line Arguments

Command line arguments are a way for you to pass information to your program when you run it. You simply type the information you want to give your program after the name of your java program when you run. So to pass the arguments “hello” “world” to the class Args, you would type

java Args hello world

Open the file Args.java, provided in your lab1 repository. When you open it, you should see this code

public class Args {

    public static void main(String[] args) {


    }

}

The main() method is the entry point to your program. It is passed an array of Strings corresponding to the command line arguments.
Let’s print out each of the arguments. Add the following for loop to the main method.

for (int i = 0; i < args.length; i++) {
    System.out.println(args[i]);
}

Now try compiling and running with the command line arguments “one” “two” “three” by typing the following commands into the Terminal:

javac Args.java
java Args one two three

You should see it print:

one
two
three

Now try:

java Args “Hello world” “How are you?”

Click run again. Notice how the text between the quotation marks is treated as a single argument. With your partner, modify the for loop to print out the arguments in reverse order. Once you’ve finished, remember to add everything to GitHub with the following commands:

git add Args.java
git commit -m “finished reversing the arguments”
git push

Now if you look at your repository on GitHub, you should see Args.java has the time you committed it (approximately now), and the commit message “finished reversing the arguments”. From now on, you will be making up your own commit messages - you should try to make them something that will tell you what change you made to the file before you committed it. If you click on Args.java on GitHub, you should see it has the code you just added.