Thursday, 20 August 2009

Java Certification Question 0070

You want to find out the value of the last element of an array. You write the following code. What will happen when you compile and run it.?

public class MyAr{

public static void main(String argv[]){

int[] i = new int[5];

System.out.println(i[5]);

}

}

1) An error at compile time
2) An error at run time
3) The value 0 will be output
4) The string "null" will be output


Answer 2) An error at run time

This code will compile, but at run-time you will get an ArrayIndexOutOfBounds exception. This becuase counting in Java starts from 0 and so the 5th element of this array would be i[4].

Remember that arrays will always be initialized to default values wherever they are created.



No comments: