Write a Java Program to Check if An Array Contains a Given Value

In Java, we can easily check if an array contains a given value using a loop.

The process involves iterating through each element of the array and checking if the element matches the given value.


Here’s a Java program that demonstrates this process:

public class ArrayContainsValue {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int value = 3;

        boolean containsValue = false;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == value) {
                containsValue = true;
                break;
            }
        }

        if (containsValue) {
            System.out.println("The array contains the value " + value);
        } else {
            System.out.println("The array does not contain the value " + value);
        }
    }
}

In this program, we define an array of integers arr and a variable value that represents the value we want to check for.

We then define a boolean variable containsValue that will be set to true if the array contains the value.

Next, we use a for loop to iterate through each element of the array.

Inside the loop, we use an if statement to check if the current element is equal to the given value.

If it is, we set containsValue to true and break out of the loop.

Finally, we use another if statement to check the value of containsValue.

If it is true, we print a message saying that the array contains the value.

If it is false, we print a message saying that the array does not contain the value.

This program can be easily modified to work with arrays of different types (e.g. strings, floats, etc.) by changing the data type of the array and the value variable.


In conclusion, checking if an array contains a given value is a simple process in Java that involves iterating through each element of the array and checking for a match.

This can be accomplished using a for loop and an if statement, as demonstrated in the example program above.