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

Discussion

What is the output of the following piece of code?

public class array
{
 public static void main(String args[])
 {
  int []arr = {1,2,3,4,5};
  System.out.println(arr[5]);
 }
}

 

  • A.4
  • B.5
  • C.ArrayIndexOutOfBoundsException
  • D.InvalidInputException

Answer: C

Correct answer: ArrayIndexOutOfBoundsException

The array has five elements, so its valid indices are 0 to 4. arr[5] is one past the end. Java checks every index at run time and throws an ArrayIndexOutOfBoundsException - unlike C, which would read whatever happens to lie at that address.

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

Post your comment

Please log in or register to post a comment.