Java Program to check if String 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 CheckStringArrayForValuePresent {
  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();
    String inputArray[] = new String[size];
    System.out.println("Enter the elements of the array: ");
    for (int i = 0; i < size; i++) {
      inputArray[i] = reader.next();
    }
    System.out.println("Enter the element you want to search: ");
    String searchElement = reader.next();
    List<String> 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 string element is present in an array.

  1. Input Array Size and Elements:

    • The user is prompted to enter the size of the array (size).
    • A String array inputArray[] is created to store the elements.
    • The user enters the string elements, which are stored in the array.
  2. Input Search Element:

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

    • The program converts the array into a List using Arrays.asList(inputArray).
    • The resulting List is wrapped in an ArrayList (inputList) to use its methods effectively.
    • Converting the array to a List allows easy use of the contains() method for searching elements.
  4. Check for Element Presence:

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

Output 1

javac .\CheckStringArrayForValuePresent.java
java CheckStringArrayForValuePresent        
Enter the required size of the array: 
4
Enter the elements of the array: 
c++
python
java
hadoop
Enter the element you want to search: 
hadoop
Element is present

Output 2

javac .\CheckStringArrayForValuePresent.java
java CheckStringArrayForValuePresent
Enter the required size of the array: 
4
Enter the elements of the array: 
Python
Perl
F#
CSS
Enter the element you want to search: 
Java
Element is not present