AI Hints
Home›Java Tutorial›The Enhanced for Loop, The Arrays Class and Searching an Array
Java · Lesson 51 of 120

Searching an Array

Is it there, and where?.

⏱ 2 min read▶ Video at 1:03:38🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Is a name on the guest list, and if so, where? Searching an array means looking at each value, until you find the one you want.

  • Is it there?
  • Where is it?
  • Look one by one

We want to find Chen. Found starts at minus one, which means not found yet. The loop compares each guest, using equals. When it matches, we remember the position, and break. Afterwards, found tells us the answer. Run it. Chen is at position two.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String[] guests = {"Ana", "Ben", "Chen", "Dina"};
        String wanted = "Chen";
        int found = -1;
        for (int i = 0; i < guests.length; i++) {
            if (guests[i].equals(wanted)) {
                found = i;
                break;
            }
        }
        if (found >= 0) {
            System.out.println(wanted + " is at position " + found);
        } else {
            System.out.println(wanted + " is not on the list");
        }
    }
}
Output
Chen is at position 2

If an array is already sorted, there's a much faster way. Binary search jumps to the middle, and throws away the half that can't contain the value. Arrays dot binary search does this for you. A negative answer means not found. Run it. Thirty four is at index four. And ten is not there.

Main.javajava
import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        int[] sorted = {3, 8, 15, 21, 34, 50, 72};
        System.out.println(Arrays.binarySearch(sorted, 34));
        System.out.println(Arrays.binarySearch(sorted, 10) < 0);
    }
}
Output
4
true

A linear search checks every value, one by one. It works on any array. A binary search needs a sorted array, but it's incredibly fast. A million values take only about twenty steps.

Linear

  • Check one by oneAny arraySlow for big arrays

Binary

  • Halve each timeMust be sortedAbout 20 steps for a million

Summary

A linear search checks each value. Binary search is much faster, but needs a sorted array. Next, arrays with rows and columns.

Key takeaways
  • Loop + equals
  • -1 means not found
  • binarySearch if sorted
Next up: Two-Dimensional Arrays — rows and columns