search
HomeJavajavaTutorialJava program to check array bounds while inputting array elements

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};

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] + " ");
      }
   }
}

Output

Elements of the array item: Rice Milk Bread Butter Peanut

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]);
      }
   }
}

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)

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 ");
      }
   }
}

Output

Enter number of items: 3

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!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

How do Java's Top Features Impact Performance and Scalability?How do Java's Top Features Impact Performance and Scalability?May 12, 2025 am 12:08 AM

Java'stopfeaturessignificantlyenhanceitsperformanceandscalability.1)Object-orientedprincipleslikepolymorphismenableflexibleandscalablecode.2)Garbagecollectionautomatesmemorymanagementbutcancauselatencyissues.3)TheJITcompilerboostsexecutionspeedafteri

JVM Internals: Diving Deep into the Java Virtual MachineJVM Internals: Diving Deep into the Java Virtual MachineMay 12, 2025 am 12:07 AM

The core components of the JVM include ClassLoader, RuntimeDataArea and ExecutionEngine. 1) ClassLoader is responsible for loading, linking and initializing classes and interfaces. 2) RuntimeDataArea contains MethodArea, Heap, Stack, PCRegister and NativeMethodStacks. 3) ExecutionEngine is composed of Interpreter, JITCompiler and GarbageCollector, responsible for the execution and optimization of bytecode.

What are the features that make Java safe and secure?What are the features that make Java safe and secure?May 11, 2025 am 12:07 AM

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

Must-Know Java Features: Enhance Your Coding SkillsMust-Know Java Features: Enhance Your Coding SkillsMay 11, 2025 am 12:07 AM

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)Object-orientedprogrammingallowsmodelingreal-worldentities,exemplifiedbypolymorphism.2)Exceptionhandlingprovidesrobusterrormanagement.3)Lambdaexpressionssimplifyoperations,improvingcodereadability

JVM the most complete guideJVM the most complete guideMay 11, 2025 am 12:06 AM

TheJVMisacrucialcomponentthatrunsJavacodebytranslatingitintomachine-specificinstructions,impactingperformance,security,andportability.1)TheClassLoaderloads,links,andinitializesclasses.2)TheExecutionEngineexecutesbytecodeintomachineinstructions.3)Memo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft