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");
}
}
}
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