Home > Java > javaTutorial > Java program to check array bounds while inputting array elements

Java program to check array bounds while inputting array elements

WBOY
Release: 2023-08-28 10:29:05
forward
1209 people have browsed it

An array is a linear data structure used to store groups of elements with similar data types. It stores data in a sequential manner. Once we create an array, we cannot change its size, i.e. it is fixed length.

This article will help you understand the basic concepts of arrays and array binding. Also, we will discuss the java program to check the bounds of an array while inputting elements into the array.

Arrays and array binding

We can access array elements by index. Suppose we have an array of length N, then

Java program to check array bounds while inputting array elements

In the above picture we can see that there are 7 elements in the array, but the index values ​​are from 0 to 6, that is, 0 to 7 - 1.

The range of an array is called its boundary. The range of the above array is from 0 to 6, therefore, we can also say that 0 to 6 are the bounds of the given array. If we try to access an out-of-range index value or a negative index, we will get an ArrayIndexOutOfBoundsException. This is an error that occurs at runtime.

Syntax for declaring arrays

Data_Type[] nameOfarray; 
// declaration
Or,
Data_Type nameOfarray[]; 
// declaration
Or,
// declaration with size
Data_Type nameOfarray[] = new Data_Type[sizeofarray]; 
// declaration and initialization
Data_Type nameOfarray[] = {values separated with comma};
Copy after login

We can use any of the above syntax in our program.

Checking array bounds when entering elements into an array

Example 1

If we access elements within the range of the array, then we will not get any error. The program will execute successfully.

public class Main {
   public static void main(String []args) {
      // declaration and initialization of array ‘item[]’ with size 5
      String[] item = new String[5]; 
      // 0 to 4 is the indices 
      item[0] = "Rice";
      item[1] = "Milk";
      item[2] = "Bread";
      item[3] = "Butter";
      item[4] = "Peanut";
      System.out.print(" Elements of the array item: " );
      // loop will iterate till 4 and will print the elements of ‘item[]’
      for(int i = 0; i <= 4; i++) {
         System.out.print(item[i] + " ");
      }
   }
}
Copy after login

Output

Elements of the array item: Rice Milk Bread Butter Peanut
Copy after login

Example 2

Let us try to print values ​​outside the range of the given array.

public class Tutorialspoint {
      public static void main(String []args) {
      String[] item = new String[5];
      item[0] = "Rice";
      item[1] = "Milk";
      item[2] = "Bread";
      item[3] = "Butter";
      item[4] = "Peanut";
      // trying to run the for loop till index 5
      for(int i = 0; i <= 5; i++) {
         System.out.println(item[i]);
      }
   }
}
Copy after login

Output

Rice
Milk
Bread
Butter
Peanut
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at Tutorialspoint.main(Tutorialspoint.java:11)
Copy after login

As we discussed before, if we try to access an array with an index value that is outside its range or a negative index, we will get an ArrayIndexOutOfBoundsException.

In the above program, we tried to execute a for loop until index 5 of the array "item[]", but its range is only 0 to 4. So after printing the elements till 4 we get the error.

Example 3

In this example, we try to handle ArrayIndexOutOfBoundsException using try and catch blocks. We will check the array bounds when the user enters elements into the array.

import java.util.*;
public class Tutorialspoint {
   public static void main(String []args) throws ArrayIndexOutOfBoundsException {
      // Here ‘sc’ is the object of scanner class
      Scanner sc = new Scanner(System.in); 
      System.out.print("Enter number of items: ");
      int n = sc.nextInt();
      // declaration and initialization of array ‘item[]’
      String[] item = new String[n]; 
      // try block to test the error
      try {
         // to take input from user
         for(int i =0; i<= item.length; i++) {
            item[i] = sc.nextLine();
         }
      }
      // We will handle the exception in catch block
      catch (ArrayIndexOutOfBoundsException exp) {
         // Printing this message to let user know that array bound exceeded
         System.out.println(
         " Array Bounds Exceeded  \n Can't take more inputs ");
      }
   }
}
Copy after login

Output

Enter number of items: 3
Copy after login

in conclusion

In this article, we learned about arrays and array binding. We have discussed why we receive an error if we try to access an array element beyond its scope and how to handle this error using try and catch blocks.

The above is the detailed content of Java program to check array bounds while inputting array elements. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template