Open In App

Arrays.binarySearch() in Java with Examples | Set 1

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
45 Likes
Like
Report

In Java, the Arrays.binarySearch() method searches the specified array of the given data type for the specified value using the binary search algorithm. The array must be sorted by the Arrays.sort() method before making this call. If it is not sorted, the results are undefined.

Example:

Below is a simple example that demonstrates how the binarySearch() method efficiently locates an element in a sorted array.


Output
Searching for 20 in arr: 1
Searching for 40 in arr: 3

Explanation: This example searches for the values 20 and 40 in the sorted array and prints their respective indices.

Syntax of Arrays.binarySearch() in Java

public static int binarySearch(data_type array, data_type key)

Note: Here datatype can be any of the primitive data types such as byte, char, double, int, float, short, long, and even object as well.

Parameters: 

  • array: The array to be searched.
  • key: The value to be searched for.

Return Type:

  • It returns the index of the key, if the index is found.
  • If the index not found, it returns - (insertion point) - 1, where the insertion point is where the key would fit in a sorted array.

Important Points:

  • Array must be sorted; otherwise, results are undefined.
  • If duplicates exist, it is uncertain which index will be returned.

Java Program to Use Arrays.binarySearch() on Different Data Types

The below example demonstrates the use of Arrays.binarySearch() to locate elements in sorted arrays of various primitive data types, where the positive results indicates the index of the element found and the negative results indicate the insertion point for elements not present.


Output
35 found at index: -4
g found at index: 1
22 found at index: 3
1.5 found at index: -1
35.0 found at index: -5
5 found at index: -1

Next Article

Similar Reads