Java Program to Check if An Array Contains a Given Value

Updated on December 20, 2024
Check if an array contains a given value header image

Introduction

Determining if an array contains a specific value is a common task in programming. In Java, this functionality can be useful in numerous applications, such as data validation, searching, and processing logic conditions. The Java programming language offers several methods to accomplish this task, ranging from straightforward loops to streamlined API methods.

In this article, you will learn how to check if an array in Java contains a given value. By exploring different approaches, including the use of loops, streams, and utility classes, you'll gain the ability to select the most appropriate method based on your specific scenario and performance needs.

Using Loops to Check for a Value

Basic for Loop

  1. Initialize an array and the value to search for.

  2. Iterate through the array using a for loop, comparing each element with the target value.

    java
    public class Main {
        public static void main(String[] args) {
            int[] array = {1, 2, 3, 4, 5};
            int valueToFind = 3;
            boolean found = false;
    
            for (int i = 0; i < array.length; i++) {
                if (array[i] == valueToFind) {
                    found = true;
                    break;
                }
            }
    
            System.out.println("Value found: " + found);
        }
    }
    

    This code snippet searches for the value 3 in the array. The boolean variable found is set to true if the value is present.

Enhanced for Loop (for-each Loop)

  1. Follow similar steps, using an enhanced for loop to simplify the syntax and improve readability.

    java
    public class Main {
        public static void main(String[] args) {
            int[] array = {1, 2, 3, 4, 5};
            int valueToFind = 3;
            boolean found = false;
    
            for (int element : array) {
                if (element == valueToFind) {
                    found = true;
                    break;
                }
            }
    
            System.out.println("Value found: " + found);
        }
    }
    

    In this version, the enhanced for loop iterates directly over each element, eliminating the need for index manipulation.

Using Stream API

Stream AnyMatch

  1. Utilize Java Stream API introduced in Java 8 to check for the presence of a value in a more functional style.

  2. Use the anyMatch() method which returns true as soon as it encounters an element that fulfills the condition.

    java
    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            int[] array = {1, 2, 3, 4, 5};
            int valueToFind = 3;
            boolean found = Arrays.stream(array).anyMatch(x -> x == valueToFind);
            System.out.println("Value found: " + found);
        }
    }
    

    This snippet efficiently checks if 3 is within the array using a single line of code, providing a more concise and readable solution.

Using Arrays Utility Class

  1. Apply a binary search to find a value if the array is sorted. This method is part of the Arrays utility class and offers optimized performance for large, sorted arrays.

  2. Remember to sort the array before performing a binary search to ensure correct results.

    java
    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            int[] array = {1, 2, 3, 4, 5};
            int valueToFind = 3;
            Arrays.sort(array);
            int result = Arrays.binarySearch(array, valueToFind);
            boolean found = result >= 0;
    
            System.out.println("Value found: " + found);
        }
    }
    

    The binarySearch() function returns the index of the searched value if it is found, or a negative value if the element is not present. Checking result >= 0 confirms the presence of the target value.

Conclusion

Different scenarios and requirements might influence the decision of which method to use when checking if an array contains a certain value in Java. By mastering several approaches—from simple loops to powerful utility methods and streams—you can make your code both efficient and readable. The choice often depends on factors such as array size, whether the array is sorted, and the frequency of search operations. With these examples under your belt, confidently apply these techniques in your next Java project to create robust and efficient applications.