Arrays.binarySearch
Search sorted arrays.
Arrays.binarySearch is a free Java Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Searching Sorted Arrays
Arrays.binarySearch finds an element in a sorted array in O(log n) time. It repeatedly halves the search range, which is far faster than scanning every element.
The Sorted Precondition
The array must already be sorted in ascending order. If it is not, the result is undefined. Always Arrays.sort first if you are unsure.
A Basic Search
When the value is found, binarySearch returns its index.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {2, 4, 6, 8, 10};
int index = Arrays.binarySearch(nums, 8);
System.out.println("Found at index " + index);
}
}When the Value Is Missing
If the value is not present, the return value is negative: it equals -(insertionPoint) - 1. The insertion point is where the value would go to keep the array sorted.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {2, 4, 6, 8, 10};
int result = Arrays.binarySearch(nums, 5);
System.out.println("Raw result: " + result);
}
}Recovering the Insertion Point
To turn a negative result into the insertion index, compute -(result) - 1. This tells you where to insert the missing value.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {2, 4, 6, 8, 10};
int result = Arrays.binarySearch(nums, 5);
if (result < 0) {
int insertionPoint = -(result) - 1;
System.out.println("Would insert at index " + insertionPoint);
}
}
}Searching Object Arrays
binarySearch also works on object arrays using natural ordering. The array must be sorted the same way the search compares.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] names = {"Alice", "Bob", "Charlie", "Dave"};
int index = Arrays.binarySearch(names, "Charlie");
System.out.println("Charlie at index " + index);
}
}Searching with a Comparator
If the array was sorted with a custom Comparator, you must pass the same Comparator to binarySearch, otherwise results are meaningless.
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
String[] names = {"Dave", "Charlie", "Bob", "Alice"};
Comparator<String> desc = Comparator.reverseOrder();
Arrays.sort(names, desc);
int index = Arrays.binarySearch(names, "Charlie", desc);
System.out.println("Index: " + index);
}
}Searching a Range
You can limit the search to part of the array with binarySearch(array, fromIndex, toIndex, key). The range bounds follow the same inclusive-exclusive rule as sort.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {2, 4, 6, 8, 10, 12};
int index = Arrays.binarySearch(nums, 1, 5, 8);
System.out.println("Index: " + index);
}
}Duplicates Are Unspecified
If the array contains duplicate values, there is no guarantee which matching index is returned. Binary search is best used on arrays with unique keys.
Why Not Just Loop?
A linear scan is O(n) and works on unsorted data. Binary search is O(log n) but requires sorted data. For repeated lookups on large datasets, sorting once and binary-searching many times is a big win.
Putting It Together
Sort, then search, and interpret the result safely.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] ids = {40, 10, 30, 20};
Arrays.sort(ids);
int r = Arrays.binarySearch(ids, 30);
if (r >= 0) {
System.out.println("Found 30 at index " + r);
} else {
System.out.println("Not found; insert at " + (-(r) - 1));
}
}
}Quick Check
Test your understanding of binarySearch.
Recap
You learned fast searching with Arrays.binarySearch.
- The array must be sorted first.
- A non-negative result is the found index.
- A negative result encodes the insertion point as
-(result) - 1. - Use the same Comparator for sorting and searching.
Frequently asked questions
Is the “Arrays.binarySearch” lesson free?
Yes — the full text of “Arrays.binarySearch” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Arrays.binarySearch”?
Search sorted arrays. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Arrays.binarySearch” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Arrays.sort and Sorting
- Arrays.binarySearch
- Arrays.fill and copyOf
- Arrays.equals and toString