Friday 25 November 2011

What will be the result of compiling and running the following program

public class Test
{

static int i;
static public void main(String[] args)
{


do
{


System.out.println(args[++i]);


} while (i < args.length);


}


}

Choices:
A. Prints "hello"
B. Prints "Test"
C. Code does not compile
D. Throws an ArrayIndexOutOfBoundsException

Correct choice:

  • D


Explanation:

The variable i is automatically initialized to 0. Inside the loop, i is incremented by 1 first before printing the value of args[i]. Here the args array has only one element -- "hello." Attempting to access the second element causes the exception.

1 comment: