IndexOutOfBoundsException

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

No — array indexes start at zero, and go up to length-1.

IndexOutOfBoundsException

Here is a program that asks the user for an integer and for an array index where it is to be placed. Only indexes 0 through 9 are allowed. Any other index causes an IndexOutOfBoundsException.

import java.util.* ;

public class IndexPractice
{
  public static void main ( String[] a )
  {
    Scanner scan = new Scanner( System.in );
    int data=0, slot=0 ;
    int[] value = new int[10];

    try
    { 
      System.out.print("Enter the data: ");
      data = scan.nextInt();
      System.out.print("Enter the array index: ");
      slot = scan.nextInt();
      value[slot] = data;
    }

    catch (InputMismatchException ex )
    {  
      System.out.println("This is your problem: " +  ex.getMessage()   
          + "/nHere is where it happened:/n");
       ex.printStackTrace();  
    } 

    catch (IndexOutOfBoundsException ex )
    {  
       System.out.println("This is your problem: " +  ex.getMessage()   
          + "/nHere is where it happened:/n");
       ex.printStackTrace(); 
     } 

    System.out.println("Good-by" );
  }
}

 

QUESTION 3:

If the user enters:

Enter the data: 8
Enter the array index: 10
will an exception be thrown?