C

Core Java tutorial for beginners

Clean • Professional

Core Java Arrays – Searching Arrays in Java (Linear & Binary Search)

4 minute

Searching Arrays in Java

Searching is the process of finding the position or existence of a specific element within an array.

It’s one of the most common operations you’ll perform when working with data in Java — whether you’re checking for a student ID, searching a product code, or finding a value in a list.


What Is Searching in Java?

When you have multiple elements stored in an array, searching helps you determine:

  • Whether a specific element exists in the array
  • The index (position) of that element
  • Or, if not found — that the element doesn’t exist

Java provides both manual searching techniques and built-in search utilities for efficient lookups.


Types of Searching in Java

There are two primary types of search operations in arrays:

learn code with durgesh images

Let’s explore both step-by-step


1. Linear Search (Sequential Search)

Linear Search is the simplest search technique — it checks each element one by one until it finds the target value.

Example: Linear Search in Java

public class LinearSearchExample {
    public static void main(String[] args) {
        int[] numbers = {10, 25, 30, 45, 50};
        int key = 30;
        boolean found = false;

        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == key) {
                System.out.println("Element found at index: " + i);
                found = true;
                break;
            }
        }

        if (!found)
            System.out.println("Element not found!");
    }
}

Output:

Element found at index: 2

Points to Remember:

  • Works on unsorted arrays.
  • Simple to implement but slow for large datasets.
  • Time Complexity: O(n)
  • Best Case: When element found early.
  • Worst Case: When element not present.

2. Binary Search

Binary Search is a faster and more efficient searching algorithm — but it only works on sorted arrays.

It follows the Divide and Conquer approach:

  1. Compare the target value with the middle element.
  2. If equal → found.
  3. If smaller → search left half.
  4. If larger → search right half.

Example: Binary Search in Java

import java.util.Arrays;

public class BinarySearchExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        int key = 40;

        int result = Arrays.binarySearch(numbers, key);

        if (result >= 0)
            System.out.println("Element found at index: " + result);
        else
            System.out.println("Element not found!");
    }
}

Output:

Element found at index: 3

Using Built-in Method: Arrays.binarySearch()

Java provides a ready-made method in the java.util.Arrays class.

Example:

import java.util.Arrays;

public class BuiltInBinarySearch {
    public static void main(String[] args) {
        int[] numbers = {3, 6, 9, 12, 15};
        int key = 12;

        int index = Arrays.binarySearch(numbers, key);

        if (index >= 0)
            System.out.println("Element found at index: " + index);
        else
            System.out.println("Element not found!");
    }
}

Output:

Element found at index: 3

Key Differences Between Linear and Binary Search

FeatureLinear SearchBinary Search
Array RequirementWorks on unsorted arraysRequires sorted array
ApproachSequential checkDivide and conquer
Time ComplexityO(n)O(log n)
PerformanceSlowerFaster
Use CaseSmall or random datasetsLarge, sorted datasets

Real-World Example

Imagine a student database:

  • Linear Search: Find a student by scanning every record.
  • Binary Search: If roll numbers are sorted, directly jump to middle values to find faster.

🏆 Top 5 Interview Questions – Searching Arrays in Java


1. What is the difference between Linear Search and Binary Search?

Answer:

FeatureLinear SearchBinary Search
Array RequirementWorks on unsorted arraysRequires a sorted array
ApproachChecks each element one by oneDivides the array and searches halves
Time ComplexityO(n)O(log n)
SpeedSlowerMuch faster
Use CaseSmall or random dataLarge, sorted data

2. Why must an array be sorted before performing a binary search?

Answer: Binary Search works by comparing the middle element and discarding half of the remaining elements.

This logic only works when the array is sorted, otherwise it may skip the target value and return incorrect results.


3. What does Arrays.binarySearch() return if the element is not found?

Answer: If the element is not found, Arrays.binarySearch() returns a negative value

specifically, -(insertion point) - 1,

where insertion point is the index where the element would fit to keep the array sorted.

Example:

int[] arr = {10, 20, 30, 40, 50};
System.out.println(Arrays.binarySearch(arr, 25)); // Output: -3

Explanation:

25 would fit at index 2 → insertion point = 2 → -(2) - 1 = -3.


4. What is the time complexity of Linear Search and Binary Search?

Answer:

AlgorithmBest CaseAverage CaseWorst Case
Linear SearchO(1)O(n/2)O(n)
Binary SearchO(1)O(log n)O(log n)

Binary Search is significantly faster for large sorted datasets.


5. Can you perform a binary search on a String array in Java?

Answer: Yes, Java allows binary search on a sorted String[] array using Arrays.binarySearch().

Example:

String[] names = {"Aman", "Neha", "Ravi", "Zoya"};
Arrays.sort(names); // Must be sorted
int index = Arrays.binarySearch(names, "Ravi");
System.out.println("Found at index: " + index);

Output:

Found at index: 2

 

Article 0 of 0