How to Check If an Array Contains a Specific Element in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a specific element exists within a Java array using different techniques. We will start by exploring the fundamental approach of iterating through the array using a traditional for loop to search for the element.

Following the basic iteration method, you will discover how to leverage the Arrays.stream() method for a more concise and potentially more efficient way to check for element presence. Finally, we will address the important consideration of handling null elements within the array during your search operations.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/FileandIOManagementGroup(["File and I/O Management"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java(("Java")) -.-> java/DataStructuresGroup(["Data Structures"]) java/BasicSyntaxGroup -.-> java/for_loop("For Loop") java/StringManipulationGroup -.-> java/strings("Strings") java/DataStructuresGroup -.-> java/arrays("Arrays") java/DataStructuresGroup -.-> java/arrays_methods("Arrays Methods") java/FileandIOManagementGroup -.-> java/stream("Stream") java/SystemandDataProcessingGroup -.-> java/object_methods("Object Methods") subgraph Lab Skills java/for_loop -.-> lab-559997{{"How to Check If an Array Contains a Specific Element in Java"}} java/strings -.-> lab-559997{{"How to Check If an Array Contains a Specific Element in Java"}} java/arrays -.-> lab-559997{{"How to Check If an Array Contains a Specific Element in Java"}} java/arrays_methods -.-> lab-559997{{"How to Check If an Array Contains a Specific Element in Java"}} java/stream -.-> lab-559997{{"How to Check If an Array Contains a Specific Element in Java"}} java/object_methods -.-> lab-559997{{"How to Check If an Array Contains a Specific Element in Java"}} end

Loop Through Array for Element

In this step, you will learn how to check if a specific element exists within a Java array by iterating through it using a traditional for loop. This is a fundamental technique for searching within collections of data.

First, let's create a new Java file named ArraySearch.java in your ~/project directory. You can do this using the WebIDE file explorer on the left or by running the following command in the terminal:

touch ~/project/ArraySearch.java

Now, open the ArraySearch.java file in the WebIDE editor and add the following Java code:

public class ArraySearch {

    public static void main(String[] args) {
        // Define an array of strings
        String[] fruits = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};

        // The element we want to search for
        String searchElement = "Cherry";

        // Variable to keep track if the element is found
        boolean found = false;

        // Loop through the array
        for (int i = 0; i < fruits.length; i++) {
            // Check if the current element is equal to the search element
            if (fruits[i].equals(searchElement)) {
                found = true; // Element found
                break; // Exit the loop since we found the element
            }
        }

        // Print the result
        if (found) {
            System.out.println(searchElement + " was found in the array.");
        } else {
            System.out.println(searchElement + " was not found in the array.");
        }
    }
}

Let's break down this code:

  • String[] fruits = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};: This line declares and initializes a string array named fruits with several fruit names.
  • String searchElement = "Cherry";: This line declares a string variable searchElement and assigns the value "Cherry" to it. This is the element we are looking for in the array.
  • boolean found = false;: This line declares a boolean variable found and initializes it to false. We will set this to true if we find the searchElement in the array.
  • for (int i = 0; i < fruits.length; i++): This is a standard for loop that iterates through the array. i starts at 0 and goes up to (but not including) the length of the fruits array.
  • if (fruits[i].equals(searchElement)): Inside the loop, this if statement checks if the current element of the array (fruits[i]) is equal to the searchElement. We use the .equals() method to compare strings in Java, not the == operator.
  • found = true;: If the elements are equal, we set the found variable to true.
  • break;: Once the element is found, we use the break statement to exit the loop early, as there's no need to continue searching.
  • The final if/else block prints a message indicating whether the searchElement was found based on the value of the found variable.

Save the ArraySearch.java file (Ctrl+S or Cmd+S).

Now, let's compile and run the program in the terminal. Make sure you are in the ~/project directory.

Compile the code:

javac ArraySearch.java

If there are no errors, a ArraySearch.class file will be created.

Run the compiled code:

java ArraySearch

You should see the following output:

Cherry was found in the array.

Now, try changing the searchElement to something that is not in the array, like "Grape", save the file, recompile, and run it again to see the different output.

Use Arrays.stream() for Element Check

In this step, you will learn a more modern and often more concise way to check for an element in a Java array using the Streams API, specifically Arrays.stream(). This approach leverages functional programming concepts and can make your code more readable for certain tasks.

We will modify the ArraySearch.java file you created in the previous step. Open ~/project/ArraySearch.java in the WebIDE editor.

Replace the existing code with the following:

import java.util.Arrays;

public class ArraySearch {

    public static void main(String[] args) {
        // Define an array of strings
        String[] fruits = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};

        // The element we want to search for
        String searchElement = "Cherry";

        // Use Arrays.stream() to check if the element exists
        boolean found = Arrays.stream(fruits).anyMatch(fruit -> fruit.equals(searchElement));

        // Print the result
        if (found) {
            System.out.println(searchElement + " was found in the array.");
        } else {
            System.out.println(searchElement + " was not found in the array.");
        }
    }
}

Let's look at the changes:

  • import java.util.Arrays;: We need to import the Arrays class to use its stream() method.
  • boolean found = Arrays.stream(fruits).anyMatch(fruit -> fruit.equals(searchElement));: This is the core of the new approach.
    • Arrays.stream(fruits): This converts the fruits array into a Stream. A stream is a sequence of elements that supports various operations.
    • .anyMatch(fruit -> fruit.equals(searchElement)): This is a stream operation. anyMatch() checks if any element in the stream matches the given condition. The condition is provided as a lambda expression fruit -> fruit.equals(searchElement). This lambda expression takes each fruit from the stream and checks if it is equal to the searchElement. If a match is found, anyMatch() returns true immediately.

This stream-based approach achieves the same result as the for loop but in a more declarative style โ€“ you describe what you want to do (find if any element matches the condition) rather than how to do it (iterate step-by-step).

Save the ArraySearch.java file (Ctrl+S or Cmd+S).

Now, compile and run the modified program in the terminal from the ~/project directory:

Compile the code:

javac ArraySearch.java

Run the compiled code:

java ArraySearch

You should see the same output as before:

Cherry was found in the array.

Again, feel free to change the searchElement to test the else case.

Handle Null Elements

In this step, we will consider a common scenario in Java: dealing with null values in arrays. If an array contains null elements, our previous methods might encounter issues. We will learn how to safely handle nulls when searching for an element.

Open the ~/project/ArraySearch.java file in the WebIDE editor again.

Modify the fruits array to include a null element:

import java.util.Arrays;
import java.util.Objects; // Import the Objects class

public class ArraySearch {

    public static void main(String[] args) {
        // Define an array of strings with a null element
        String[] fruits = {"Apple", null, "Banana", "Cherry", "Date", "Elderberry"};

        // The element we want to search for
        String searchElement = "Cherry";

        // Use Arrays.stream() and handle nulls
        boolean found = Arrays.stream(fruits)
                              .anyMatch(fruit -> Objects.equals(fruit, searchElement)); // Use Objects.equals

        // Print the result
        if (found) {
            System.out.println(searchElement + " was found in the array.");
        } else {
            System.out.println(searchElement + " was not found in the array.");
        }

        // Let's also search for null itself
        String searchNullElement = null;
        boolean foundNull = Arrays.stream(fruits)
                                  .anyMatch(fruit -> Objects.equals(fruit, searchNullElement));

        if (foundNull) {
            System.out.println("null was found in the array.");
        } else {
            System.out.println("null was not found in the array.");
        }
    }
}

Here's what we changed:

  • import java.util.Objects;: We import the Objects class, which provides utility methods for objects, including safe handling of null.
  • String[] fruits = {"Apple", null, "Banana", "Cherry", "Date", "Elderberry"};: We added null as the second element in the fruits array.
  • .anyMatch(fruit -> Objects.equals(fruit, searchElement)): Instead of fruit.equals(searchElement), we now use Objects.equals(fruit, searchElement). The Objects.equals() method is designed to handle null values gracefully. It returns true if both arguments are null, and it avoids throwing a NullPointerException if the first argument (fruit in this case) is null.
  • We added a second search to demonstrate finding null itself in the array using the same Objects.equals() method.

Save the ArraySearch.java file (Ctrl+S or Cmd+S).

Compile and run the modified program in the terminal from the ~/project directory:

Compile the code:

javac ArraySearch.java

Run the compiled code:

java ArraySearch

You should see the following output, demonstrating that both "Cherry" and null were found:

Cherry was found in the array.
null was found in the array.

Using Objects.equals() is the recommended way to compare objects, especially when there's a possibility of one or both objects being null. This prevents unexpected NullPointerException errors.

Summary

In this lab, you learned a fundamental method for checking if a specific element exists within a Java array: iterating through the array using a traditional for loop. You practiced creating a Java file, defining an array and a search element, implementing the loop to compare elements, and using a boolean flag to track if the element was found. This hands-on exercise demonstrated how to perform a basic search operation and print the result based on whether the element was present in the array.