Do something like:

Arrays.asList(array).contains(x);

since that return true if the String x is present in the array (now converted into a list...)

Example:

if(Arrays.asList(myArray).contains(x)){
    // is present ... :)
}

since Java8 there is a way using streams to find that:

boolean found = Arrays.stream(myArray).anyMatch(x::equals);
if(found){
    // is present ... :)
}
Answer from ΦXocę 웃 Пepeúpa ツ on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java array › check if a java array contains a value
Check if a Java Array Contains a Value | Baeldung
September 7, 2024 - We’ve seen several methods of searching through an array. Based on our results, a HashSet works best for searching through a list of values. However, we need to create them in advance and store them in the Set.
🌐
codippa
codippa.com › home › how to check if array contains a value in java in 5 different ways
How to check if array contains a value in java in 5 different ways - codippa
January 13, 2025 - Check out different methods for conversion of array to list in java here. ... Method 3 : Using Apache Commons Library This method utilizes ArrayUtils class from Apache Commons Library. This class has a method contains which takes two arguments : an array and a value. It searches for the value in the array and returns true if the value is found in the array, false otherwise. import org.apache.commons.lang.ArrayUtils; public class StringChecker { public static void main(String[] args) { methodThree(); } static void methodThree() { // initialize array String[] array = { "one", "two", "three", "four" }; // initialize value to search String valueToSearch = "three"; // check if string exists in array if (ArrayUtils.contains(array, valueToSearch)) { System.out.println("String is found in the array"); } else { System.out.println("String is not found in the array"); } } }
🌐
YouTube
youtube.com › pace edu.
Search String in Array of Strings Java - YouTube
search string in array of strings javaJava - search a string in string arraysearch string in array of strings javascripthow to search an arraylist of objects...
Published   February 26, 2022
Views   2K
🌐
Learning About Electronics
learningaboutelectronics.com › Articles › How-to-search-an-array-in-Java.php
How to Search an Array in Java
This is because arrays increase by 1 at each index. It starts at 0, then the next element is 1, then the next element is 2, then the next element is 3... and so on. Underneath this for loop, we create our if statement which searches for the particular word or string or character we are looking for.
🌐
Coderanch
coderanch.com › t › 405806 › java › Searching-string-array
Searching string in the array (Beginning Java forum at Coderanch)
Implement a method that receives the following parameters: 1. an array of Strings 2. a String called "searched" The method looks for the "searched" string and returns its index. If the string isn't found, the method returns -1. You can assume that the array doesn't contain null values. Find a string in an array package com.javala.exercise; public class FindStringInArrayExercise { public int findString(String[] elements, String searched) { //write code here } }
🌐
Coderanch
coderanch.com › t › 506493 › java › search-String-array
How to search the String array (Beginning Java forum at Coderanch)
Vijaypal Singh wrote:import java.util.*; public class AlgaeDiesel { public static void main(String [] args){ String [] sa = {"foo","bar","baz"}; List<String> thisList = Arrays.asList(sa); String searchParam = "bar"; //Arrays.sort(sa); for(String s : sa){ System.out.println(s); } search(thisList,searchParam); } public static void search(final List<String> searchTarget,final String searchParam){ System.out.println("thisList------"+searchTarget); if(searchTarget.contains(searchParam)){ int index = searchTarget.indexOf(searchParam); System.out.println("Found at ------ "+index); }else{ System.out.println("Search Param Not found "); } } } Thanks Bhaaaji! ... Have a closer look at the java.util.Arrays class.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › check-if-a-value-is-present-in-an-array-in-java
Check If a Value is Present in an Array in Java - GeeksforGeeks
In the Linear Search method, each element of the array is sequentially compared with the key until a match is found or the end of the array is reached. Example: Java · // Java program to check if an element is present using Linear Search class Geeks { private static boolean isElementPresent(int[] arr, int key) { for (int element : arr) { if (element == key) { return true; } } return false; } public static void main(String[] args) { int[] arr = {3, 5, 7, 2, 6, 10}; int key = 7; boolean res = isElementPresent(arr, key); System.out.println("Is " + key + " present in the array: " + res); } } Output ·
Published   November 10, 2025
🌐
TutorialsPoint
tutorialspoint.com › how-to-search-for-a-string-in-an-arraylist-in-java
How to search for a string in an ArrayList in java?
October 15, 2019 - Verify whether each element in the array list contains the required string. If so print the elements. ... import java.util.ArrayList; import java.util.Iterator; public class FindingString{ public static void main(String[] args){ ArrayList <String> list = new ArrayList<String>(); //Instantiating ...
🌐
Baeldung
baeldung.com › home › java › java list › searching for a string in an arraylist
Searching for a String in an ArrayList | Baeldung
April 4, 2025 - public List<String> findUsingLoop(String search, List<String> list) { List<String> matches = new ArrayList<String>(); for(String str: list) { if (str.contains(search)) { matches.add(str); } } return matches; } The Java 8 Streams API provides us with a more compact solution by using functional operations.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-array-contains-value
How to Check if a Java Array Contains a Value? | DigitalOcean
September 16, 2025 - This comprehensive guide covers the four essential methods every Java developer should know: the enhanced for-loop that works in any situation, the convenient Arrays.asList().contains() method for quick lookups in object arrays, modern Java 8 Streams with their functional programming power, ...
🌐
TutorialsPoint
tutorialspoint.com › javaexamples › arrays_find.htm
How to Find an Object or a String in an Array using Java
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList objArray = new ArrayList(); ArrayList objArray2 = new ArrayList(); objArray2.add(0,"common1"); objArray2.add(1,"common2"); objArray2.add(2,"notcommon"); objArray2.add(3,"notcommon1"); objArray.add(0,"common1"); objArray.add(1,"common2"); System.out.println("Array elements of array1"+objArray); System.out.println("Array elements of array2"+objArray2); System.out.println("Array 1 contains String common2??
Top answer
1 of 2
4

I can't see anything wrong with the code, but I would recommend eliminating the local variable that holds the return value:

 public static int Search(String[] thewords, String answer) {
     for (int i = 0; i < thewords.length; i++) {
         if (answer.equals(thewords[i])){
             return i;
         }
     } 
     return -1;
 }

With this simplified logic, there's little or no chance of there being a bug in this code.


I assume this is course work, and you are not allowed to use library methods. If you were allowed, your method could be a single line:

return Arrays.asList(theWords).indexOf(answer);
2 of 2
1

You can optionally make a copy of the array since sorting might be unwanted for consumers of the method

public static int Search(String[] thewords, String answer) {  
     if(thewords == null) {  
        throw new NullPointerException();  
     }  
     String[] copy = new String[thewords.length];  
     System.arraycopy(thewords,0,copy,0,copy.length);  
     Arrays.sort(thewords);    
     return Arrays.binarySearch(thewords, answer);  
}  

Note: It returns -pos and not -1

If you need -1:

public static int Search(String[] thewords, String answer) {  
     if(thewords == null) {  
        throw new NullPointerException();  
     }  
     String[] copy = new String[thewords.length];  
     System.arraycopy(thewords,0,copy,0,copy.length);  
     Arrays.sort(thewords);  
     int idx = Arrays.binarySearch(thewords, answer);  
     return idx < 0? -1:idx;  
}  

Concerning your code: I believe the problem would be related to casing or spacing:
Replace with something like: if (answer.equalsIgnoreCase(theWords[i].trim())){

For large arrays go with binary search.

🌐
Sentry
sentry.io › sentry answers › java › find a specific value in an array in java
Find a specific value in an array in Java | Sentry
January 15, 2024 - An alternative but less generalizable method for achieving this is to cast our array to a list using Arrays.asList and then use the contains method on that list. While this may be more readable for a developer unfamiliar with Java’s Stream API, it does not work for primitive values like for arrays with ints, doubles, or longs. However, it will work for an array of strings:
🌐
Coderanch
coderanch.com › t › 373057 › java › Searching-string-array
Searching string in an array. (Java in General forum at Coderanch)
A linear search algo runtime is O(log n) and not O(n). HTH. Gabe [ March 03, 2004: Message edited by: Gabriel White ] [ March 03, 2004: Message edited by: Gabriel White ] ... I have seen one more algorithm that is java.util.Array.binarySearch You did not mention that the String array is already sorted in ascending order according to the natural ordering of its elements.
🌐
Stack Abuse
stackabuse.com › java-check-if-array-contains-value-or-element
Java: Check if Array Contains Value or Element
November 19, 2020 - The found variable is initially set to false because the only way to return true would be to find the element and explicitly assign a new value to the boolean. Here, we simply compare each element of the array to the value we're searching for, and return true if they match: ... For Strings, and custom Objects you might have in your code, you'd be using a different comparison operator.
Top answer
1 of 16
3431
Arrays.asList(yourArray).contains(yourValue)

Warning: this doesn't work for arrays of primitives (see the comments).


Since java-8 you can now use Streams.

String[] values = {"AB","BC","CD","AE"};
boolean contains = Arrays.stream(values).anyMatch("s"::equals);

To check whether an array of int, double or long contains a value use IntStream, DoubleStream or LongStream respectively.

Example

int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);
2 of 16
465

Concise update for Java SE 9

Reference arrays are bad. For this case we are after a set. Since Java SE 9 we have Set.of.

private static final Set<String> VALUES = Set.of(
    "AB","BC","CD","AE"
);

"Given String s, is there a good way of testing whether VALUES contains s?"

VALUES.contains(s)

O(1).

The right type, immutable, O(1) and concise. Beautiful.*

Original answer details

Just to clear the code up to start with. We have (corrected):

public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

This is a mutable static which FindBugs will tell you is very naughty. Do not modify statics and do not allow other code to do so also. At an absolute minimum, the field should be private:

private static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

(Note, you can actually drop the new String[]; bit.)

Reference arrays are still bad and we want a set:

private static final Set<String> VALUES = new HashSet<String>(Arrays.asList(
     new String[] {"AB","BC","CD","AE"}
));

(Paranoid people, such as myself, may feel more at ease if this was wrapped in Collections.unmodifiableSet - it could then even be made public.)

(*To be a little more on brand, the collections API is predictably still missing immutable collection types and the syntax is still far too verbose, for my tastes.)