A SCJP question about arrays
Question: Given the following:
1.public class CommandArgs {
2. public static void main(String[] args) {
3. String s1 = args[1];
4. String s2 = args[2];
5. String s3 = args[3];
6. String s4 = args[4];
7. System.out.println(" args[2] = " + s2);
8. }
9.}
and the command-line invocation,
java CommandArgs 1 2 3 4
what is the result?
- args[2] = 2
- args[2] = 3
- args[2] = null
- args[2] = 1
- Compilations fails
- An exception is thrown at runtime
Ok, this question is trying to cheat you. Look well. First of all, the first index in a Java array is zero. Then, the command line showed sets args[0] = 1, args[1] = 2, args[2] = 3 and args[3] = 4. The assignment:
6. String s4 = args[4];
Causes a RuntimeException, or more precisely, an ArrayOutOfBoundsException. The correct answer is 6.
References:
- Kathy Sierra and Bert Bates, Sun Certified Programmer & Developer for Java 2 Study Guide (Exam 310-035 & 310-027)
, McGraw-Hill Osborne Media



















