w3resource

Java: Find the index of an array element

Java Array: Exercise-6 with Solution

Write a Java program to find the index of an array element.

Pictorial Presentation:

Java Array Exercises: Find the index of an array element

Sample Solution:

Java Code:

import java.util.OptionalInt;
// Define a class named Main.
public class Main {
    // Define a method 'findIndex' that searches for an integer 't' in an integer array 'my_array'.
    public static OptionalInt findIndex(int[] my_array, int t) {
        // Check if the array is null and return an empty OptionalInt if it is.
        if (my_array == null)
            return OptionalInt.empty();
        // Get the length of the array.
        int len = my_array.length;
        int i = 0;
        // Iterate through the elements in the array.
        while (i < len) {
            // Check if the current element is equal to 't' and return its index as an OptionalInt if found.
            if (my_array[i] == t)
                return OptionalInt.of(i);
            else
                i = i + 1;
        }
        // If 't' is not found in the array, return an empty OptionalInt.
        return OptionalInt.empty();
    }
    // The main method where the program execution starts.
    public static void main(String[] args) {
        // Declare an integer array 'my_array' and initialize it with values.
        int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
        // Find and print the index position of value 25 in the array.
        findIndex(my_array, 25).ifPresent(index -> System.out.println("Index position of 25 is: " + index));
        // Find and print the index position of value 877 in the array.
        findIndex(my_array, 877).ifPresent(index -> System.out.println("Index position of 877 is: " + index));
        // Find and print the index position of value 29 in the array.
        findIndex(my_array, 29).ifPresent(index -> System.out.println("Index position of 29 is: " + index));
    }
}

Sample Output:

Index position of 25 is: 0                                                                                    
Index position of 29 is: 8 

Note:

'java.util.OptionalInt' is a class introduced in Java 8 as part of the 'java.util' package. It is part of the broader 'java.util.Optional' family of classes, which includes 'OptionalInt', OptionalLong, and OptionalDouble for handling optional values of primitive types. The 'OptionalInt' class is designed to represent an optional 'int' value, meaning it can either contain an 'int' value or be empty. It is useful in cases where a method might not always produce a valid result. You want to make it clear that the results may not be available.

Some key methods provided by 'OptionalInt' include:

  • of(int value): Returns an 'OptionalInt' with the specified value if it is non-null; otherwise, it throws a 'NullPointerException'.
  • empty(): Returns an empty 'OptionalInt'.
  • isPresent(): Returns 'true' if there is a value present; otherwise, returns 'false'.
  • ifPresent(IntConsumer action): If a value is present, performs the given action with the value; otherwise, does nothing.
  • orElse(int other): Returns the value if present; otherwise, returns the specified other value.

By using 'OptionalInt', we can avoid using special values like -1 to represent the absence of a result. This makes our code more expressive and reducing misinterpretation.

Flowchart:

Flowchart: Java exercises: Find the index of an array element

Java Code Editor:

Previous: Write a Java program to test if an array contains a specific value.
Next: Write a Java program to remove a specific element from an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.