Java – Arrays Class

Arrays class:

  • Java library class belongs to java.util package.
  • Arrays class providing set of method to process array elements.
  • Some of the methods as follows.
static void sort(int[] a)Sorts the specified array into ascending numerical order.
static String     toString(int[] a)Returns a string representation of the contents of the specified array.
static <T> List<T>       asList(T… a)  Returns a fixed-size list backed by the specified array.
static int binarySearch(int[] a, int key)Searches the specified array of ints for the specified value using the binary search algorithm
static int[] copyOfRange(int[] original, int from, int to)Copies the specified range of the specified array into a new array.
static boolean equals(int[] a, int[] a2)Returns true if the two specified arrays of ints are equal to one another.
static void fill(int[] a, int val)  Assigns the specified int value to each element of the specified array of ints.

Sort array elements and display as String:

import java.util.Random;
import java.util.Arrays;
class SortArray
{
            public static void main(String[] args)
            {
                        Random rand = new Random();
                        int arr[] = new int[5];
                        for(int i=0 ; i<5 ; i++){
                                    arr[i] = rand.nextInt(100);
                        }
                        System.out.println(“Before sort : ” + Arrays.toString(arr));
 
                        Arrays.sort(arr);
                        System.out.println(“After sort : ” + Arrays.toString(arr));
            }
}

Search element using Arrays.binarySearch():

import java.util.Scanner ;
import java.util.Arrays ;
class Search
{
            public static void main(String[] args)
            {
                        Scanner scan = new Scanner(System.in);
                        System.out.print(“Enter array size : “);
                        int n = scan.nextInt();
                        int arr[ ] = new int[n];
 
                        System.out.println(“Enter ” + n + ” values : “);
                        for (int i=0 ; i<n ; i++){
                                    arr[i] = scan.nextInt();
                        }
                                   
                        System.out.print(“Enter element to be searched : “);
                        int key = scan.nextInt();
 
                        int result = Arrays.binarySearch(arr,key); 
                         if (result < 0) 
                                                System.out.println(“Element is not found!”); 
                        else 
                                                System.out.println(“Element is found at index : ” + result); 
            }
}
Scroll to Top