
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Verify Element Existence in Array using Java
Given an array and one of its element as an input, write a Java program to check whether that element exists in given array or not. You can find any element from an array using search algorithms. In this article, we will use linear search and binary search algorithms.
Using Linear Search Algorithm
In this approach, follow the steps below to verify whether a given element exists in an array ?
- Iterate through the array using for loop.
- Compare each element with the required element.
- If found return the index.
Example
The following Java program shows how to check whether a given element exists in an array using linear search algorithm.
import java.util.*; public class ArraySearch { public static void main(String[] args) { int[] myArray = {23, 93, 56, 92, 39}; System.out.println("Elements of the given array: " + Arrays.toString(myArray)); int searchVal = 39; System.out.println("The value to be searched: " + searchVal); // checking if the element is present for (int i =0 ; i < myArray.length; i++) { if (myArray[i] == searchVal) { System.out.println("The index of element " + searchVal + " is : " + i); } } } }
When you execute this code, following output will be displayed ?
Elements of the given array: [23, 93, 56, 92, 39] The value to be searched: 39 The index of element 39 is : 4
Using Arrays.binarySearch() method
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
In this example, we use the binarySearch() method to verify whether a given element exists in an array.
import java.util.Arrays; import java.util.Scanner; public class ArraySearch { public static void main(String[] args) { int[] myArray = {23, 93, 56, 92, 39}; System.out.println("Elements of the given array: " + Arrays.toString(myArray)); int searchVal = 39; System.out.println("The value to be searched: " + searchVal); //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(" "); int retVal = Arrays.binarySearch(myArray,searchVal); System.out.println("Element found"); System.out.println("The index of element in the sorted array: " + retVal); } }
On running the above code, it will show the following result ?
Elements of the given array: [23, 93, 56, 92, 39] The value to be searched: 39 The sorted int array is: 23 39 56 92 93 Element found The index of element in the sorted array: 1