Linear Search in Java: Program and Logic
Return the first index of a target in an array, or -1 if it is missing.
- Time
O(n) - Space
O(1) - Hints3
- Read3 min
Linear search in Java checks array elements one by one from index 0. If an element equals the target, return its index at once. If the loop ends with no match, return -1. It works on sorted and unsorted arrays, takes O(n) time in the worst case and uses O(1) extra space.
Problem statement
Write a program for linear search in Java. Given an int array and a target,
return the index of the first match, or -1 if the target is not present.
The array can be in any order. That is the main advantage over binary search, which needs sorted data.
An integer array arr of length n and an integer target.
The first index of target, or -1.
Examples
arr = [12, 45, 7, 30, 9], target = 30330 is at index 3.
arr = [12, 45, 7, 30, 9], target = 8-1All five elements are checked and none equals 8.
Constraints
- 0 <= n <= 10^6
- Elements may repeat and may be in any order
Think before you code
Reveal the questions to ask yourself first
- How do you visit every element with its index?
- Can you stop early?
- At what point are you sure the target is missing?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
- Start at index 0.
- Compare
arr[i]with the target. - If they are equal, return
i. - If not, move to the next index.
- After the loop, return
-1.
| Case | When | Checks |
|---|---|---|
| Best | Target is first | 1, so O(1) |
| Worst | Target is last or missing | n, so O(n) |
| Average | Target equally likely at each index | About n / 2, so O(n) |
Dry run
Walk through the example step by step
Target 30 in [12, 45, 7, 30, 9]:
i | arr[i] | equal to 30? | action
--+--------+--------------+---------
0 | 12 | no | continue
1 | 45 | no | continue
2 | 7 | no | continue
3 | 30 | yes | return 3
Index 4 is never checked.
Solution
Reveal the full Java solution
public class LinearSearch {
static int search(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {12, 45, 7, 30, 9};
System.out.println(search(arr, 30));
System.out.println(search(arr, 8));
}
}Output of this linear search in Java code:
3
-1
Linear search in Java using Scanner
The user types the size, the elements, and then the value to find.
import java.util.Scanner;
public class LinearSearchInput {
// Sample input: 5 12 45 7 30 9 7
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int target = sc.nextInt();
int pos = -1;
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
pos = i;
break;
}
}
if (pos == -1) {
System.out.println(target + " not found");
} else {
System.out.println(target + " found at index " + pos);
}
}
}
Output for the sample input:
7 found at index 2
For a linear search in Java with user input, you can also print a message before each
nextInt() so that the user knows what to type.
Find every match, and search strings
import java.util.ArrayList;
import java.util.List;
public class LinearSearchMore {
static List<Integer> allIndexes(int[] arr, int target) {
List<Integer> result = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
result.add(i);
}
}
return result;
}
static int searchName(String[] names, String target) {
for (int i = 0; i < names.length; i++) {
if (target.equals(names[i])) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(allIndexes(new int[]{4, 2, 4, 9, 4}, 4));
String[] names = {"Ravi", "Anu", "Kiran"};
System.out.println(searchName(names, "Anu"));
}
}
[0, 2, 4]
1
Use equals for text. == on strings checks if both names point to the same object.
Read strings in Java for the reason.
Linear search or binary search?
| Point | Linear search | Binary search |
|---|---|---|
| Needs sorted data | No | Yes |
| Worst time | O(n) | O(log n) |
| Good for | Small or unsorted data | Large sorted data, many searches |
Linear search in Java: practice tasks
- Return the last index of the target.
- Count how many times the target appears.
- Search a 2D array and print the row and column.
- Find the largest element with one loop, which is the same walk with a different test.
More tasks are in the core Java practice problems. For guided learning, see the Java full stack course.
O(n)O(1)Review before the interview
Common mistakes
- Returning -1 in an else inside the loop, so that only the first element is checked.
- Looping to i <= arr.length, which throws ArrayIndexOutOfBoundsException when there is no match.
- Comparing strings with == instead of equals.
- Forgetting break when storing the position, which returns the last match.
Edge cases to test
- Empty array returns -1.
- Target at the first or last index.
- Repeated target: return the first index.
- Null array: decide whether to throw an error or return -1.
Interview follow-ups
- How do you search for the last match?
- When is linear search a better choice than binary search?
- How would you search a list of objects by one field?
Keep practising
Binary Search in Java: Program and Logic
Hints · Dry run · SolutionSolve Similar problemFind the Largest Element in an Array
Hints · Dry run · SolutionSolve Similar problemCount the Frequency of Each Element in an Array
Hints · Dry run · SolutionSolve Related learningArrays
TutorialLearn Related learningLoops
TutorialLearn Related learningCoding Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising for Java interviews?
CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
