Array Methods in Java
Java provides various methods in the java.util.Arrays class for performing operations on arrays.
Let's explore some of these methods in-depth.
1. Sorting Arrays:
The sort method is used to sort elements of an array in ascending order.
int[] numbers = {5, 2, 8, 1, 7};
// Sorting the array
Arrays.sort(numbers);
// Result: [1, 2, 5, 7, 8]
2. Searching Arrays:
The binarySearch method is used to search for an element in a sorted array. It returns the index
of the element if found; otherwise, it returns a negative value.
int[] numbers = {1, 2, 5, 7, 8};
// Searching for the element 5
int index = Arrays.binarySearch(numbers, 5);
// Result: 2 (index of 5 in the sorted array)
3. Filling Arrays:
The fill method is used to fill an array with a specific value.
int[] array = new int[5];
// Filling the array with the value 42
Arrays.fill(array, 42);
// Result: [42, 42, 42, 42, 42]
4. Copying Arrays:
The copyOf method is used to create a copy of an array with a specified length. The copyOfRange
method copies a specific range of elements.
int[] sourceArray = {1, 2, 3, 4, 5};
// Copying the entire array
int[] copyArray = Arrays.copyOf(sourceArray, sourceArray.length);
// Copying a range of elements
int[] partialCopy = Arrays.copyOfRange(sourceArray, 1, 4);
// Result (copyArray): [1, 2, 3, 4, 5]
// Result (partialCopy): [2, 3, 4]
5. Checking Equality:
The equals method is used to check if two arrays are equal.
int[] array1 = {1, 2, 3};
int[] array2 = {1, 2, 3};
boolean isEqual = Arrays.equals(array1, array2);
// Result: true (arrays are equal)
Note:
These are just a few examples of array methods in Java. The Arrays class provides several other
useful methods for working with arrays, including asList, toString, and more.