๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Arrays Class in Java  


Introduction

  • Definition:
    • Arrays is the predefined class which is present in java.util package.
    • It provides static methods to dynamically manipulate arrays, such as sorting, searching and copying arrays.
  • Use / Need:
      Arrays in Java are fixed in size once created.
      The Arrays class provides utility methods to perform common operations efficiently without writing custom code.
  • Syntax:
    • public final class Arrays
      {
          // static methods
      }
    • We don't create an object of Array class. Instead, you use its **static methods** like:
      • Arrays.methodName(arguments);
  • Characteristics:
    • Arrays is a final class, so it cannot be extended.
    • All methods are static, hence called using the class name directly.
    • Works with both primitive arrays and object arrays.
  • Advantages:
    • Reduces the need to write boilerplate code for array operations.
    • Provides optimized and tested methods from the JDK.
    • Makes code more readable and maintainable.

Important Methods of Arrays Class
Method Description Example
sort(array) Sorts the specified array in ascending order. Arrays.sort(arr);
binarySearch(array, key) Searches for a key in a sorted array and returns its index; returns negative if not found. int index = Arrays.binarySearch(arr, 50);
copyOf(original, newLength) Copies the original array to a new array of specified length. int[] newArr = Arrays.copyOf(arr, 10);
copyOfRange(original, from, to) Copies a specified range from the original array into a new array. int[] part = Arrays.copyOfRange(arr, 2, 5);
equals(array1, array2) Checks if two arrays are equal (same length and same elements). boolean isEqual = Arrays.equals(arr1, arr2);
fill(array, value) Assigns the specified value to all elements of the array. Arrays.fill(arr, 0);
toString(array) Returns a string representation of the array. System.out.println(Arrays.toString(arr));
deepToString(array) Returns a string representation of a multidimensional array. System.out.println(Arrays.deepToString(arr2D));
hashCode(array) Returns the hash code of the array. int code = Arrays.hashCode(arr);
deepEquals(array1, array2) Checks equality for multidimensional arrays. boolean isEqual = Arrays.deepEquals(arr2D1, arr2D2);
  • Note :
    • All methods of Arrays class are static, so you can call them directly using Arrays.methodName().
    • Import Statement: Before using, import the class: import java.util.Arrays;