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.
-
Input Array Size and Elements:
- The user is prompted to enter the size of the array (
size
). - A
String
arrayinputArray[]
is created to store the elements. - The user enters the string elements, which are stored in the array.
- The user is prompted to enter the size of the array (
-
Input Search Element:
- The user is prompted to input the string (
searchElement
) to search for in the array.
- The user is prompted to input the string (
-
Convert Array to List:
- The program converts the array into a
List
usingArrays.asList(inputArray)
. - The resulting
List
is wrapped in anArrayList
(inputList
) to use its methods effectively. - Converting the array to a
List
allows easy use of thecontains()
method for searching elements.
- The program converts the array into a
-
Check for Element Presence:
- The
List.contains()
method is used to check if thesearchElement
exists in theinputList
. - If the element is found, it prints
"Element is present"
. Otherwise, it prints"Element is not present"
.
- The
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