Fiveable

💻AP Computer Science A Unit 4 Review

QR code for AP Computer Science A practice questions

4.14 Searching

4.14 Searching

Written by the Fiveable Content Team • Last updated June 2026
Verified for the 2027 exam
Verified for the 2027 examWritten by the Fiveable Content Team • Last updated June 2026
💻AP Computer Science A
Unit & Topic Study Guides

Frequently Asked Questions

Previous Exam Prep

Study Tools

Exam Skills

AP Cram Sessions 2021

Pep mascot

TLDR

Linear search checks each element of an array or ArrayList one at a time until it finds the target value or runs out of elements to check. In AP Computer Science A, linear search is the search algorithm you write and trace inside Unit 4 collections, and it works on any data whether or not it is sorted. You can start a linear search from either end, and for a 2D array you apply linear search to each row.

Why This Matters for the AP Computer Science A Exam

Searching shows up in both the multiple-choice and free-response sections, often hidden inside a larger array, ArrayList, or 2D array problem. You need to write a loop that checks each element, decide what to return when you find a match, and describe the behavior of a search loop step by step.

This topic supports common exam skills:

  • Writing code that traverses a collection and reacts when a target is found
  • Tracing a search loop to predict its result or output
  • Describing what a search method does and what it returns when the target is missing

For this topic, focus on linear search. Binary search comes later in the course alongside recursion, so you do not need it to write a correct linear search here.

Key Takeaways

  • Linear search checks elements in order until the target is found or every element has been checked.
  • A linear search can start from the front or the back of an array or ArrayList.
  • A common convention is to return the index when the target is found and return -1 when it is not.
  • For object elements, compare with .equals() instead of == so you compare contents, not references.
  • To linear search a 2D array, visit each row and run a linear search across that row.
  • If the target appears more than once, decide whether you want the first match, the last match, or a count.

Linear Search Basics

Linear search, sometimes called sequential search, walks through a collection one element at a time. At each position you compare the current element to the target. If they match, you found it. If you reach the end without a match, the target is not in the collection.

The big advantage is that linear search works on any array or ArrayList, sorted or not. You do not need to prepare the data in any way before searching.

The tradeoff is speed. In the worst case you check every element, so the number of comparisons grows with the size of the collection. For small collections this is not a problem, and on the exam linear search is exactly what you are expected to write and trace.

Linear Search on an ArrayList

</>Java
import java.util.ArrayList;

public class LinearSearchDemo {
    // Returns the index of the first occurrence, or -1 if not found
    public static int linearSearch(ArrayList<Integer> list, int target) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) == target) {
                return i;   // found it, return position
            }
        }
        return -1;          // checked everything, not found
    }

    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        numbers.add(15);
        numbers.add(8);
        numbers.add(23);
        numbers.add(8);
        numbers.add(42);

        System.out.println("Numbers: " + numbers);
        System.out.println("Find 23: index " + linearSearch(numbers, 23));
        System.out.println("Find 8: index " + linearSearch(numbers, 8)); // first occurrence
    }
}

The return i inside the loop stops the search as soon as a match is found, so this method returns the index of the first occurrence. The return -1 after the loop signals "not found."

Searching for Objects with equals

When the elements are objects such as String, compare with .equals() instead of ==. The == operator compares whether two references point to the same object, while .equals() compares the actual contents.

</>Java
import java.util.ArrayList;

public class WordSearch {
    // Counts how many times target appears
    public static int countOccurrences(ArrayList<String> words, String target) {
        int count = 0;
        for (String word : words) {
            if (word.equals(target)) {
                count++;
            }
        }
        return count;
    }
}

This version uses an enhanced for loop and keeps a counter, which is handy when the target can appear more than once and you want the total.

Starting From Either End

A linear search does not have to start at index 0. You can start at the last index and move toward the front. This is useful when you want the last occurrence of a value instead of the first.

</>Java
// Returns the index of the LAST occurrence, or -1 if not found
public static int lastIndexOf(ArrayList<Integer> list, int target) {
    for (int i = list.size() - 1; i >= 0; i--) {
        if (list.get(i) == target) {
            return i;
        }
    }
    return -1;
}

The logic is identical; only the direction of the loop changes.

Linear Search on a 2D Array

To search a 2D array, traverse it one row at a time and run a linear search across each row. This usually means nested loops: the outer loop picks a row, and the inner loop checks each element in that row.

</>Java
// Returns true if target is found anywhere in the 2D array
public static boolean contains2D(int[][] grid, int target) {
    for (int row = 0; row < grid.length; row++) {
        for (int col = 0; col < grid[row].length; col++) {
            if (grid[row][col] == target) {
                return true;
            }
        }
    }
    return false;
}

This visits elements in row-major order, meaning it finishes one full row before moving to the next. You could also return the row and column where the value was found by storing those indices before returning.

How to Use This on the AP Computer Science A Exam

Free Response

When a free-response prompt asks you to find or count something in a collection, a linear search loop is often the core of your answer. Read the specification carefully to decide what to return: an index, a boolean, a count, or the element itself. Then return -1 or the agreed value when nothing matches.

For a method that searches an ArrayList and might remove matches, be careful with the loop counter so you do not skip elements after a removal.

Code Tracing

For multiple-choice questions, you often trace a search loop with a small sample collection. Track the loop index and the current element at each step, and watch for the exact moment the condition becomes true. The method usually stops and returns right then, so later elements never get checked.

Common Trap

  • Comparing objects with == instead of .equals() can make a search miss a match that is really there.
  • Returning too early or too late: make sure return -1 is after the loop, not inside it, so you do not report "not found" before checking every element.

Common Misconceptions

  • Linear search does not require sorted data. It works on any array or ArrayList in any order.
  • Returning -1 is a convention, not a rule. A method could instead return a boolean or the element itself, depending on the specification.
  • A match does not always mean index 0 onward. Linear search can start from the back, which is how you find a last occurrence.
  • == and .equals() are not interchangeable for objects. Use .equals() to compare contents when searching for objects like strings.
  • Searching a 2D array is not one single loop. You need to reach each row and then search across that row, usually with nested loops.
  • Finding one match is not always the goal. If duplicates exist, you may need to keep scanning to count them or to find the last one.

Vocabulary

The following words are mentioned explicitly in the College Board Course and Exam Description for this topic.

Term

Definition

2D array

A two-dimensional data structure consisting of rows and columns used to store and organize data in a grid format.

array

A data structure that stores a fixed-size collection of elements of the same type in contiguous memory locations, accessed by index.

ArrayList

A resizable array implementation in Java that can dynamically grow or shrink to store a collection of objects.

linear search algorithms

Standard algorithms that check each element in a collection in order until the desired value is found or all elements have been checked.

Frequently Asked Questions

What is linear search in AP CSA?

Linear search checks each element in order until the target is found or the entire array or ArrayList has been checked.

Does linear search require sorted data?

No. Linear search works on arrays and ArrayLists whether or not the data are sorted, because it checks elements one at a time.

What should a linear search return if the target is not found?

It depends on the method specification, but a common convention is to return -1 for an index search or false for a boolean search.

How do you search for objects like Strings in Java?

Use .equals() to compare object contents, such as strings. The == operator compares references, which can miss matching values.

How do you linear search a 2D array?

Search a 2D array by visiting each row and applying linear search across that row, usually with nested loops.

Can a linear search start from the end?

Yes. Linear search can start from either end of an array or ArrayList. Searching from the end is useful when you want the last occurrence of a value.

Pep mascot
Upgrade your Fiveable account to print any study guide

Download study guides as beautiful PDFs See example

Print or share PDFs with your students

Always prints our latest, updated content

Mark up and annotate as you study

Click below to go to billing portal → update your plan → choose Yearly→ and select "Fiveable Share Plan". Only pay the difference

Plan is open to all students, teachers, parents, etc
Pep mascot
Upgrade your Fiveable account to export vocabulary

Download study guides as beautiful PDFs See example

Print or share PDFs with your students

Always prints our latest, updated content

Mark up and annotate as you study

Plan is open to all students, teachers, parents, etc
report an error
description

screenshots help us find and fix the issue faster (optional)

add screenshot