Ankaj Gupta
March 23, 2021

How to find out nth value by using array in Java | java code examples with output

Java Essentials

Find the Nth Element in a Java Array (Safely)

Accessing a specific position in an array is a foundational task in Java, but it is easy to cause ArrayIndexOutOfBoundsException if you don't validate user input. This quick guide shows you how to request an index from the console, verify it, and safely retrieve the element.

Workflow Overview

1. Prepare data

Create or receive an array, and clarify whether indexes are zero-based (Java's default).

2. Request input

Prompt the user for the position (1-based makes more sense for humans), then translate it to a valid index.

3. Validate & respond

Check bounds, return the element if valid, or guide the user to retry.

Sample Implementation

The example below reads an integer from the console, validates it, and prints the corresponding element. It also uses a helper method to keep the main() flow clear.

import java.util.Scanner;

public class FindNthElement {

    private static final int[] VALUES = {5, 10, 15, 20, 23};

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("Enter the position (1-" + VALUES.length + "): ");
            int position = scanner.nextInt();

            int element = getElementAt(position);
            System.out.println("Element at position " + position + " is: " + element);
        } catch (IndexOutOfBoundsException ex) {
            System.out.println("Please enter a position between 1 and " + VALUES.length + ".");
        }
    }

    private static int getElementAt(int position) {
        int index = position - 1; // convert to zero-based index
        if (index < 0 || index >= VALUES.length) {
            throw new IndexOutOfBoundsException();
        }
        return VALUES[index];
    }
}

Example Run

Enter the position (1-5): 4
Element at position 4 is: 20

Enter the position (1-5): 9
Please enter a position between 1 and 5.

Edge Cases to Consider

Empty arrays

Guard against zero-length arrays; return a message or throw a custom exception before requesting user input.

Multiple lookups

Wrap the input logic in a loop if you want to allow several queries without restarting the program.

Different data types

Replace int with generics or wrapper classes if you plan to store complex objects.

User experience

Normalize input (e.g., trim whitespace) and communicate errors clearly to prevent confusion.

Practice Ideas

  • Reverse lookup: Ask the user for a value and return its index or a message if it's missing.
  • Random access: Populate the array with random numbers and let the program explain the difference between positions and indexes.
  • Unit tests: Use JUnit to verify getElementAt() for valid, invalid, and boundary positions.
Java program Java programming

Related Posts