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?

  1. args[2] = 2
  2. args[2] = 3
  3. args[2] = null
  4. args[2] = 1
  5. Compilations fails
  6. 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:

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Furl
  • Ma.gnolia
  • Reddit
  • Slashdot
  • Technorati
  • YahooMyWeb
  • BlinkList
  • Netscape
  • NewsVine
  • StumbleUpon
  • TailRank
  • blinkbits
  • blogmarks
  • BlogMemes
  • co.mments
  • DotNetKicks
  • MisterWong
  • Smarking

Leave a Reply