Exercise 3-10: (2) Write a program that prints three arguments taken from the command line. To do this, you’ll need to index into the command-line array of Strings.
public class Arguments
{
public static void main(String[] args) throws Exception
{
System.out.println("args[0] = " + args[0]);
System.out.println("args[1] = " + args[1]);
System.out.println("args[2] = " + args[2]);
}
}
/*
javac Arguments.java
java Arguments
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at Arguments.main(Arguments.java:5)
java Arguments Hello
args[0] = Hello
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at Arguments.main(Arguments.java:6)
java Arguments Hello, guys!
args[0] = Hello,
args[1] = guys!
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
at Arguments.main(Arguments.java:7)
java Arguments How are you?
args[0] = How
args[1] = are
args[2] = you?
java Arguments How are you, friend?
args[0] = How
args[1] = are
args[2] = you,
*/
First, we call java Arguments with no arguments, so we get an exception on line 5 of the source file: Arguments.main(Arguments.java:5), where we try to print the first command line argument: System.out.println("args[0] = " + args[0]);
Then we call java Arguments Hello (with 1 argument), so we get an exception on line 6, where we try to print args[1] (the second argument from the command line), and so on.
When we provide at least 3 argument, the first 3 are printed.