Popular Tutorials
Start Learning JavaCertification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Java binarySearch()
In Java, the binarySearch() method of the collections framework can be used to search a specified element in a collection.
The binarySearch() method implements the binary search algorithm to search the element passed as an argument. If you want to learn about how binary search works, visit Binary search algorithm.
Note: If we need to implement the binary search algorithm in Java, it is better to use the binarySearch() method rather than implementing the algorithm on our own.
Example: Java binarySearch()
import java.util.ArrayList;
import java.util.Collections;
class Main {
public static void main(String[] args) {
// Creating an array list
ArrayList<Integer> numbers = new ArrayList<>();
// Add elements
numbers.add(4);
numbers.add(2);
numbers.add(3);
Collections.sort(numbers);
System.out.println("ArrayList: " + numbers);
// Using the binarySearch() method
int position = Collections.binarySearch(numbers, 3);
System.out.println("Position of 3: " + position);
}
}
Output
ArrayList: [2, 3, 4] Position of 3: 1
Did you find this article helpful?