VOOZH about

URL: https://www.geeksforgeeks.org/java/java-program-to-check-if-specified-element-is-present-in-the-array/

⇱ Java Program to Check if Specified Element is Present in the Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Program to Check if Specified Element is Present in the Array

Last Updated : 23 Jul, 2025

In Java, to check if a specified element is present in an array, we have to iterate through the array and compare each element with the target value. This can be done using loops, utility functions, or Java 8 Streams.

Example: The simplest way to check if an element is present in an array is by using a for loop.


Output
3 is present in the array.

Other Methods to Check if an Element is Present in an Array

1. Using a Utility Function

This method encapsulates the logic of checking element presence in an array, making the code reusable and cleaner. The utility function takes an array and the target element as inputs and returns a boolean result.


Output
25 is not present in the array.

2. Using Arrays.asList() for Non-Primitive Arrays

For non-primitive arrays (like String or Integer), we can use the Arrays.asList() method to convert the array into a list and then check for the presence of the element using contains().


Output
"Charlie" is present in the array.

Explanation: The Arrays.asList(names) converts the array to a List and the contains(target) checks if the List contains the specified element.

3. Using Streams (Java 8+)

The Streams API in Java 8 provides a concise way to check if an element exists in the array.


Output
4 is present in the array.

Explanation: The IntStream.of(numbers)converts the array into a stream of integers and the anyMatch(num -> num == target) returns true, if any element matches the condition.

Comment