Check if an array contains a certain value

This example will show a few methods to check whether an array contains a specific value, and in what position that certain value is located.

The more traditional approach by using a loop to search

This first code example shows how to loop through an array of strings, looking for the certain value. If it is found, the position of the value in the array is printed out. Once the value is found we break out of the loop:

The output from this code is (remember that an array starts with position 0):

Using binary search

Next we will use a binary search to look for the specific element. This is done by using the static method binarySearch() method in the Arrays class. We send in four parameters to that method, the array to be sorted, the start position of the search, the end position of the search and last, the value to find. For this to work it is important that the array is sorted, so just in case we call the static method sort() of the Arrays class before we do a binary search (in this case though we know that the order will be the same after the call to sort).

The output from the code above is:

Using a Collection object

This next code example shows how we convert that array into a Collection object (more specifically a List) and then use the method contains() to check whether the value exists or not, and then use the indexOf method to find the position of the value. Normally just one of these are used depending on what you want to achieve:

The result of the code is:

A more compact way of achieving the same results is to just write:


Search for more Java info on this site here:
Custom Search

Any thoughts or questions?