Java Objects checkIndex() Method

The Objects.checkIndex() method in Java, part of the java.util.Objects class, is used to validate whether a given index is within the bounds of a specified range.

Table of Contents

  1. Introduction
  2. checkIndex() Method Syntax
  3. Understanding checkIndex()
  4. Examples
    • Basic Usage
    • Handling Exceptions
  5. Real-World Use Case
  6. Conclusion

Introduction

The checkIndex() method ensures that an index is within the valid range of 0 (inclusive) and a specified length (exclusive). If the index is out of bounds, the method throws an IndexOutOfBoundsException. This method is useful for preventing index-related errors in collections and arrays.

checkIndex() Method Syntax

The syntax for the checkIndex() method is as follows:

public static int checkIndex(int index, int length)

Parameters:

  • index: The index to be checked.
  • length: The length of the range.

Returns:

  • The given index if it is within the bounds of the specified range.

Throws:

  • IndexOutOfBoundsException: If the index is out of bounds.

Understanding checkIndex()

The checkIndex() method validates whether the specified index is within the bounds of the given length. If the index is valid, the method returns the index; otherwise, it throws an IndexOutOfBoundsException. This method is typically used to ensure safe access to arrays and collections.

Examples

Basic Usage

To demonstrate the basic usage of checkIndex(), we will validate an index for an array.

Example

import java.util.Objects;

public class CheckIndexExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        int index = 3;

        try {
            Objects.checkIndex(index, numbers.length);
            System.out.println("Index " + index + " is within bounds.");
            System.out.println("Value at index " + index + ": " + numbers[index]);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Index " + index + " is out of bounds.");
        }
    }
}

Output:

Index 3 is within bounds.
Value at index 3: 4

Handling Exceptions

This example shows how to handle exceptions when an index is out of bounds.

Example

import java.util.Objects;

public class CheckIndexExceptionHandling {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        int index = 6; // Out of bounds

        try {
            Objects.checkIndex(index, numbers.length);
            System.out.println("Index " + index + " is within bounds.");
            System.out.println("Value at index " + index + ": " + numbers[index]);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Caught exception: Index " + index + " is out of bounds.");
        }
    }
}

Output:

Caught exception: Index 6 is out of bounds.

Real-World Use Case

Validating User Input for Array Access

In a real-world scenario, you might use the checkIndex() method to validate user input before accessing an array or list. This ensures that the program does not crash due to invalid index access.

Example

import java.util.Objects;
import java.util.Scanner;

public class UserInputValidation {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter an index to retrieve the fruit: ");
        int index = scanner.nextInt();

        try {
            Objects.checkIndex(index, fruits.length);
            System.out.println("Fruit at index " + index + ": " + fruits[index]);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Invalid index. Please enter a number between 0 and " + (fruits.length - 1) + ".");
        }
    }
}

Output:

Enter an index to retrieve the fruit: 2
Fruit at index 2: Cherry

Enter an index to retrieve the fruit: 5
Invalid index. Please enter a number between 0 and 4.

Conclusion

The Objects.checkIndex() method in Java provides a way to validate whether an index is within the bounds of a specified range. By using this method, you can prevent index-related errors and ensure safe access to arrays and collections. Whether you are working with user input or internal logic, the checkIndex() method offers a reliable way to handle index validation at runtime.

Comments