Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to search an element in an array .

Java Code Example — Array Programs

ADVERTISEMENT

Java Program to search an element in an array .

Objective

Write a Java program to search for a specific element in an array (Linear Search).

Algorithm / Approach

  1. Initialize a hardcoded array of integers.
  2. Prompt the user to enter the element x to search for.
  3. Set a boolean flag variable (flag) to 0.
  4. Start a for loop to iterate through the array.
  5. If a[i] == x, set flag = 1, record the position, and immediately break out of the loop.
  6. After the loop, check the flag. If it's 0, print "Element not found". Otherwise, print the position.
Test.java
import java.util.Scanner;
class Test {
 void search(int x) {
  int a[]={1,10,20,30,40};
  int i,flag = 0;
  for(i=0; i< a.length; i++){
   if(a[i]==x){
    flag = 1;
    break;
   }
  }
  if(flag==0) {
   System.out.print("Element not Found");
  }
  else {
   System.out.print("Found at "+(i+1));
  }
 }
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Element: ");
  int x = s.nextInt();
  Test t = new Test();
  t.search(x);
 }
}

Expected Output

Enter Element: 30
Found at 3

Explanation of the Program

  • This algorithm is called Linear Search. It scans the array sequentially from the first element to the last.
  • The flag variable acts as a memory marker to remember if we succeeded during the loop.
  • The break statement is an important optimization: once the element is found, there is no need to check the rest of the array, saving processing time.

Complexity

Time Complexity O(n) - In the worst-case scenario, the element is at the very end or doesn't exist.
Space Complexity O(1)
ADVERTISEMENT