Thursday, April 25, 2019

ArrayIndexOutOfBoundsException Exception

Q- What is an index out of bounds (ArrayIndexOutOfBoundsExceptionexception in java?

ArrayIndexOutOfBoundsException is a runtime exception.
ArrayIndexOutOfBoundsException is thrown when we are trying to access the index of arrey which is not exist in your array.
This exception is thrown when the index is either negative or greater than or equal to the size of the array.


package com.shubh.example;

public class NullPointerException {

 public static void main(String[] args) {

  int arr[] = new int[5];
  for (int i = 0; i<6; i++) {
   arr[i] = i;
  }
  for (int j = 0; j < arr.length; j++) {
   System.out.println("Print array :" + arr[j]);
  }
 }
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
 at com.shubh.example.NullPointerException.main(NullPointerException.java:11)

Soultion: Use the currect size of array while getting or filling array elemeny.

package com.shubh.example;

public class NullPointerException {

 public static void main(String[] args) {

  int arr[] = new int[5];
  for (int i = 0; i<5; i++) {
   arr[i] = i;
  }
  for (int j = 0; j < arr.length; j++) {
   System.out.println("Print array :" + arr[j]);
  }
 }
}
Output:

Print array :0
Print array :1
Print array :2
Print array :3
Print array :4

No comments:

Post a Comment