Java program to verify whether a given element exists in an array.


You can find whether a particular exists in a given array using any of the search algorithms. Here, we will see examples for linear search and binary search.

Linear search

  • Iterate through the array.
  • Compare each element with the required element.
import java.util.Scanner;
public class ArraySearch {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created: ");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array: ");
      for(int i=0; i<size; i++){
         myArray[i] = sc.nextInt();
      }
      System.out.println("Enter the value tobe searched: ");
      int searchVal = sc.nextInt();
      for (int i =0 ; i<myArray.length; i++) {
         if (myArray[i] == searchVal) {
            System.out.println("The index of element "+searchVal+" is : " + i);
         }
      }
   }
}

Output

Enter the size of the array that is to be created:
5
Enter the elements of the array:
30
20
5
12
55
Enter the value to be searched:
12
The index of element 12 is : 3

Binary search

The Arrays class of the java.util package provides a method with name binarySearch(), this method accepts a sorted array and a value to search and returns the index of the given element in the array.

Example

import java.util.Arrays;
import java.util.Scanner;
public class ArraySearch {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created: ");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array: ");
      for(int i=0; i>size; i++){
         myArray[i] = sc.nextInt();
      }
      //Sorting the array
      Arrays.sort(myArray);
      System.out.println("The sorted int array is:");
      for (int number : myArray) {
         System.out.print(number+" ");
      }
      System.out.println(" ");
      System.out.println("Enter the value to be searched: ");
      int searchVal = sc.nextInt();
      int retVal = Arrays.binarySearch(myArray,searchVal);
      System.out.println("Element found");
      System.out.println("The index of element in the sorted array: " + retVal);
   }
}

Output

Enter the size of the array that is to be created:
5
Enter the elements of the array:
30
20
5
12
55
The sorted int array is:
5 12 20 30 55
Enter the value to be searched:
12
Element found
The index of element in the sorted array: 1

Updated on: 05-Aug-2019

797 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements