Java 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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











ThisarticleusesvariousapproachesforselectingthecommandsinsertedintheopenedcommandwindowthroughtheJavacode.Thecommandwindowisopenedbyusing‘cmd’.Here,themethodsofdoingthesamearespecifiedusingJavacode.TheCommandwindowisfirstopenedusingtheJavaprogram.Iti

Please consider the table below to know the eligibility criteria of different companies - The Chinese translation of CGPA is: GPA greater than or equal to 8 Eligible companies Google, Microsoft, Amazon, Dell, Intel, Wipro greater than or equal to 7 Tutorial points, accenture, Infosys , Emicon, Rellins greater than or equal to 6rtCamp, Cybertech, Skybags, Killer, Raymond greater than or equal to 5Patronics, Shoes, NoBrokers Let us enter the java program to check the eligibility of tpp students for interview. Method 1: Using ifelseif condition Normally when we have to check multiple conditions we use

The size of a file is the amount of storage space that a specific file takes up on a specific storage device, such as a hard drive. The size of a file is measured in bytes. In this section, we will discuss how to implement a java program to get the size of a given file in bytes, kilobytes and megabytes. A byte is the smallest unit of digital information. One byte equals eight bits. One kilobyte (KB) = 1,024 bytes, one megabyte (MB) = 1,024KB, one gigabyte (GB) = 1,024MB and one terabyte (TB) = 1,024GB. The size of a file usually depends on the type of file and the amount of data it contains. Taking a text document as an example, the file size may be only a few kilobytes, while a high-resolution image or video file may be

Inheritance is a concept that allows us to access the properties and behavior of one class from another class. The class that inherits methods and member variables is called a superclass or parent class, and the class that inherits these methods and member variables is called a subclass or subclass. In Java, we use "extends" keyword to inherit a class. In this article, we will discuss a Java program to calculate interest on fixed deposits and time deposits using inheritance. First, create these four Java files - Acnt.java − in your local machine IDE. This file will contain an abstract class ‘Acnt’ which is used to store account details like interest rate and amount. It will also have an abstract method 'calcIntrst' with parameter 'amnt' for calculating

The Java language is one of the most commonly used object-oriented programming languages in the world today. The concept of classes is one of the most important features of object-oriented languages. A class is like a blueprint for an object. For example, when we want to build a house, we first create a blueprint of the house, in other words, we create a plan that shows how we are going to build the house. According to this plan we can build many houses. Likewise, using classes, we can create many objects. Classes are blueprints for creating many objects, where objects are real-world entities like cars, bikes, pens, etc. A class has the characteristics of all objects, and the objects have the values of these characteristics. In this article, we will write a Java program to find the perimeter and faces of a rectangle using the concept of classes

Roman Numerals - Based on the ancient Roman system that uses symbols to represent numbers. These numbers are called Roman numerals. The symbols are I, V, X, L, C, D and M, which represent 1, 5, 10, 50, 100, 500 and 1,000 respectively. Integers - An integer is an integer consisting of positive, negative and zero values. Fractions are not whole numbers. Here we set the symbol value based on the integer value. Whenever a Roman numeral is given as input, we divide it into units and then calculate the appropriate Roman numeral. I-1II–2III–3IV–4V–5VI–6…X–10XI–11..XV-15 In this article, we will learn how to convert Roman numerals to integers in Java. Show you some examples - Example 1InputR

An image file can be rotated clockwise or counterclockwise. To rotate an image, you need to download a random image file and save it in any folder on your system. Also, a .pdf file is required and after opening the downloaded image file, some angle can be rotated in that particular .pdf file. For a 90 degree rotation, the anchor points of the new image can help us perform the rotation using the translation transform in Java. The anchor point is the center of any particular image. AlgorithmtoRotateanImagebyUsingJavaThe"AffineTransformOp"classisthesimplestwaytorotatea

If anyone wants to get a solid foundation in Java programming language. Then, it is necessary to understand how the loop works. Furthermore, solving Pyramid Pattern problems is the best way to enhance your knowledge of Java basics as it includes extensive use of for and while loops. This article aims to provide some Java programs to print pyramid patterns with the help of different types of loops available in Java. Java Program to Create Pyramid Pattern We will print the following pyramid patterns through Java program - Inverted Star Pyramid Star Pyramid Number Pyramid Let's discuss one by one. Mode 1: The inverted star pyramid method declares and initializes an integer "n" with the specified number of rows. Next, define the initial count of the space as 0 and the initial count of the star as "n+
