Check if a value is present in an Array in Java



At first sort the array −

int intArr[] = {55, 20, 10, 60, 12, 90, 59}; // sorting array Arrays.sort(intArr);

Now, set the value to be searched in an int variable −

int searchVal = 12;

Check for the presence of a value in an array −

int retVal = Arrays.binarySearch(intArr,searchVal); boolean res = retVal > 0 ? true : false;

Following is an example to check if a value is present in an array −

Example

import java.util.Arrays; public class Main {    public static void main(String[] args) {       // initializing unsorted int array       int intArr[] = {55, 20, 10, 60, 12, 90, 59};       // sorting array       Arrays.sort(intArr);       // let us print all the elements available in list       System.out.println("The sorted int array is:");       for (int number : intArr) {          System.out.println("Number = " + number);       }       // entering the value to be searched       int searchVal = 12;       int retVal = Arrays.binarySearch(intArr,searchVal);       boolean res = retVal > 0 ? true : false;       System.out.println("Is element 12 in the array? = " + res);       System.out.println("The index of element 12 is : " + retVal);    } }

Output

The sorted int array is: Number = 10 Number = 12 Number = 20 Number = 55 Number = 59 Number = 60 Number = 90 Is element 12 in the array? = true The index of element 12 is : 1
Updated on: 2019-09-20T10:57:19+05:30

840 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements