Linear Search in Java
Java Program to implement Linear Search algorithm.
Last updated: 11 January 2026
Method 1: Standard Implementation
Check every element.
Main.javaRun in Compiler →
public class LinearSearch {
public static int search(int arr[], int x) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == x) return i;
}
return -1;
}
public static void main(String args[]) {
int arr[] = {2, 3, 4, 10, 40};
int x = 10;
int result = search(arr, x);
if (result == -1)
System.out.print("Element is not present in array");
else
System.out.print("Element is present at index " + result);
}
}Output:
Element is present at index 3
Explanation
Iterate through the array and compare each element with the target.
Frequently Asked Questions
Try This Program
Copy this code and run it in our free online Java compiler.
Open Java Compiler