Clean β’ Professional
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.
When you have multiple elements stored in an array, searching helps you determine:
Java provides both manual searching techniques and built-in search utilities for efficient lookups.
There are two primary types of search operations in arrays:

Letβs explore both step-by-step
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:
Binary Search is a faster and more efficient searching algorithm β but it only works on sorted arrays.
It follows the Divide and Conquer approach:
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
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
| Feature | Linear Search | Binary Search |
|---|---|---|
| Array Requirement | Works on unsorted arrays | Requires sorted array |
| Approach | Sequential check | Divide and conquer |
| Time Complexity | O(n) | O(log n) |
| Performance | Slower | Faster |
| Use Case | Small or random datasets | Large, sorted datasets |
Imagine a student database: