Discuss the various methods provided by the Array class in Java. Illustrate the usage of these methods with a suitable example program.
Answer:-
Arrays Class in Java
The Arrays
class belongs to the java.util
package and provides utility methods to work with arrays (like sorting, searching, copying, etc.).
Common Methods of Arrays
Class
Method | Description |
---|---|
sort(array) | Sorts the array in ascending order |
sort(array, Collections.reverseOrder()) | Sorts in descending order (for object arrays) |
binarySearch(array, key) | Searches the array (must be sorted first) |
copyOf(array, newLength) | Copies array to a new array of specified length |
copyOfRange(array, from, to) | Copies a specific range from the array |
equals(array1, array2) | Checks if two arrays are equal |
fill(array, value) | Fills entire array with a specified value |
toString(array) | Converts array to string (for printing) |
Example Program Using Arrays Class Methods
import java.util.Arrays; public class ArraysClassDemo { public static void main(String[] args) { int[] numbers = {5, 2, 8, 1, 9}; // Print original array System.out.println("Original Array: " + Arrays.toString(numbers)); // Sort array Arrays.sort(numbers); System.out.println("Sorted Array: " + Arrays.toString(numbers)); // Binary Search for 8 int index = Arrays.binarySearch(numbers, 8); System.out.println("Index of 8: " + index); // Copy array int[] copy = Arrays.copyOf(numbers, 7); // length more than original System.out.println("Copied Array: " + Arrays.toString(copy)); // Fill an array with 0 Arrays.fill(copy, 5, 7, 0); System.out.println("After fill(): " + Arrays.toString(copy)); // Check equality boolean isEqual = Arrays.equals(numbers, copy); System.out.println("Arrays equal: " + isEqual); } }
Output
Original Array: [5, 2, 8, 1, 9] Sorted Array: [1, 2, 5, 8, 9] Index of 8: 3 Copied Array: [1, 2, 5, 8, 9, 0, 0] After fill(): [1, 2, 5, 8, 9, 0, 0] Arrays equal: false