Java Program to check if Integer element is present in an array
Program
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CheckIntegerArrayForValuePresent {
public static void main(String[] args) {
System.out.println("Enter the required size of the array: ");
Scanner reader = new Scanner(System.in);
int size = reader.nextInt();
Integer inputArray[] = new Integer[size];
System.out.println("Enter the elements of the array: ");
for (int i = 0; i < size; i++) {
inputArray[i] = reader.nextInt();
}
System.out.println("Enter the element you want to search: ");
Integer searchElement = reader.nextInt();
List<Integer> inputList = new ArrayList<>(Arrays.asList(inputArray));
if (inputList.contains(searchElement)) {
System.out.println("Element is present");
} else {
System.out.println("Element is not present");
}
}
}
This Java program checks if a specified integer element is present in an array.
-
Input Array Size and Elements:
- The user is prompted to enter the size of the array (
size
) and the elements of the array. - An integer array
inputArray[]
is created to store the user-input elements.
- The user is prompted to enter the size of the array (
-
Input Search Element:
- The user is prompted to enter the integer value (
searchElement
) to search for in the array.
- The user is prompted to enter the integer value (
-
Convert Array to List:
- The
Arrays.asList()
method converts the array into aList
object. - The resulting
List
is wrapped into anArrayList
(inputList
) for additional flexibility.
- The
-
Check for Element Presence:
- The
List.contains()
method is used to check if thesearchElement
is present in theinputList
. - If the element is found, the program prints
"Element is present"
. Otherwise, it prints"Element is not present"
.
- The
Key Points:
- Array to List Conversion:
- The program converts the array to a
List
to utilize thecontains()
method, which simplifies checking for element presence.
- The program converts the array to a
- Dynamic User Input:
- The program dynamically handles user-defined array sizes and search elements.
- Flexibility:
- Using a
List
instead of directly searching the array allows for easier extensibility if more operations are needed in the future.
- Using a
Output 1
javac .\CheckIntegerArrayForValuePresent.java
java CheckIntegerArrayForValuePresent
Enter the required size of the array:
5
Enter the elements of the array:
23
44
12
56
79
Enter the element you want to search:
79
Element is present
Output 2
javac .\CheckIntegerArrayForValuePresent.java
java CheckIntegerArrayForValuePresent
Enter the required size of the array:
4
Enter the elements of the array:
29
77
45
10
Enter the element you want to search:
44
Element is not present