When I execute the following program it displays an array bound exception:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Array {

  public static void main(String[] args) throws IOException
    BufferedReader ch=new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Hello World\n");

    System.out.println ("\nEnter the number of elements:");
    int n=Integer.parseInt(ch.readLine());

    int a[]=new int[n];

    for (int i=1;i<=n;i++)
    System.out.println ("\nThe elements are as follows:\n");

    for(int i=1;i<=n;i++)
        System.out.println (a[i]+"\t");


output: Hello World

Enter the number of elements: 1 2

The elements are as follows:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Array.main(Array.java:26)

1 Answer 1


When you are creating the array by giving the array size say 5, then array is created with indices 0 to 4. But you are looping from indices 1 to 5. Since you are trying to access array index 5, you are getting the error. Use for (int i=0;i<n;i++)


Not the answer you're looking for? Browse other questions tagged or ask your own question.