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.

  1. 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.
  2. Input Search Element:

    • The user is prompted to enter the integer value (searchElement) to search for in the array.
  3. Convert Array to List:

    • The Arrays.asList() method converts the array into a List object.
    • The resulting List is wrapped into an ArrayList (inputList) for additional flexibility.
  4. Check for Element Presence:

    • The List.contains() method is used to check if the searchElement is present in the inputList.
    • If the element is found, the program prints "Element is present". Otherwise, it prints "Element is not present".

Key Points:

  • Array to List Conversion:
    • The program converts the array to a List to utilize the contains() method, which simplifies checking for element presence.
  • 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.

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