Arrays Search
# Java Example - Array Sorting and Element Search
[ Java Example](#)
The following example demonstrates how to use the sort() method to sort a Java array, and how to use the binarySearch() method to find elements in an array. Here we define the printArray() method to print the array:
## MainClass.java File
import java.util.Arrays; public class MainClass{public static void main(String args[])throws Exception{int array[] = {2, 5, -2, 6, -3, 8, 0, -7, -9, 4}; Arrays.sort(array); printArray("Array sort result", array); int index = Arrays.binarySearch(array, 2); System.out.println("Element 2 is at position " + index); }private static void printArray(String message, int array[]){System.out.println(message + ": [length: " + array.length + "]"); for(int i = 0; i<array.length; i++){if(i != 0){System.out.print(", "); }System.out.print(array); }System.out.println(); }}
The output of the above code is:
Array sort result: [length: 10] -9, -7, -3, -2, 0, 2, 4, 5, 6, 8Element 2 is at position 5
[ Java Example](
YouTip