Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

public class CommandArgs 
{
    public static void main(String [] args) 
    {
        String s1 = args[1];
        String s2 = args[2];
        String s3 = args[3];
        String s4 = args[4];
        System.out.print(" args[2] = " + s2);
    }
}

and the command-line invocation is

> java CommandArgs 1 2 3 4

  • A.args[2] = 2
  • B.args[2] = 3
  • C.args[2] = null
  • D.An exception is thrown at runtime.

Answer: D

Correct answer: An exception is thrown at runtime.

Four arguments give args indices 0 to 3, so args[4] is out of bounds and throws ArrayIndexOutOfBoundsException. The throw happens on the fourth assignment, before any output is produced, so nothing is printed at all - not even the value of args[2], which had been read successfully a moment earlier.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.