Arrays class of the java.util package contains several static methods that we can use to fill, sort, search, etc in arrays. Commonly uses API of this class :-

  • public static String toString(int[] a) : String representation consists of a list of the array’s elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters a comma followed by a space. Elements are converted to strings as by String.valueOf(int). Returns “null” if a is null.
    int ar[] = {4, 6, 1, 8, 3, 9, 7, 4, 2};  
    // To print the elements in one line
    Output: [4, 6, 1, 8, 3, 9, 7, 4, 2]
  • static void sort(int[] a, int fromIndex, int toIndex) : Sort a specified range of the array into ascending order. The range to be sorted extends from the index fromIndex, inclusive, to the index toIndex, exclusive.
  • static void sort(int[] a) : Sorts the specified array into ascending numerical order.
  • static int binarySearch(int[] a, int key) : Returns an int value for the index of the specified key in the specified array. Returns a negative number if the specified key is not found in the array. For this method to work properly, the array must first be sorted by the sort method.
  • static int binarySearch(Object[] a, int fromIndex, int toIndex, Object key): Searches a range of the specified array for the specified object using the binary search algorithm.
  • static int[] copyOf(int[] original, int newLength) : Copies the specified array and length. It truncates the array if provided length is smaller and pads if provided .
  • static int[] copyOfRange(int[] original, int from, int to)  :Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive.
  • static void fill(int[] a, int fromIndex, int toIndex, int val) : Fills elements of the specified array with the specified value from the fromIndex element, but not including the toIndex element.
  • static void fill(int[] a, int val): Assigns the specified int value to each element of the specified array of ints.
  • static List asList(T… a) : It takes an array and creates a wrapper that implements List, which makes the original array available as a list. If you shuffle the list wrapper, the original array is shuffled as well, if you overwrite an element, it gets overwritten in the original array, etc.
    Integer ar[] = {4, 6, 1, 8, 3, 9, 7, 4, 2};
    // Creates a wrapper list over ar[]
    List<Integer> l1 = Arrays.asList(ar);
  • static boolean equals(Object[] a, Object[] a2) : Returns true if the two specified arrays of Objects are equal to one another. The two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal.