To check if a specified element is present in an array in Java, you can use methods like Arrays.asList
with contains
or Arrays.binarySearch
.
In this example,
numbers
with values 10, 20, 30, 40, 50.Arrays.asList
.contains
method of the list to check if element 30 is present.contains
method returns true if the element is found, otherwise false.import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
Integer[] numbers = {10, 20, 30, 40, 50};
List<Integer> list = Arrays.asList(numbers);
boolean isPresent = list.contains(30);
System.out.println("Element 30 is present: " + isPresent);
}
}
Element 30 is present: true
In this example,
numbers
with values 10, 20, 30, 40, 50.Arrays.binarySearch
method to check if element 60 is present in the array.binarySearch
method returns the index of the element if found, otherwise a negative value.import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int isPresent = Arrays.binarySearch(numbers, 60);
boolean result = isPresent >= 0;
System.out.println("Element 60 is present: " + result);
}
}
Element 60 is present: false
In this tutorial, we learned How to check if Specified Element is present in the Array in Java language with well detailed examples.