Array Class and Methods
Java provides an Arrays class in the java.util package, which contains various methods for manipulating arrays, such as sorting, searching, and comparing arrays.
Commonly Used Array Methods:
Arrays.sort(array): Sorts the array in ascending order.
Arrays.toString(array): Converts the array to a String for easy printing.
Arrays.fill(array, value): Fills the array with the specified value.
Arrays.equals(array1, array2): Checks if two arrays are equal.
Arrays.binarySearch(array, key): Searches for a specific value within a sorted array. Returns the index of the key if found, otherwise returns a negative value.
Arrays.copyOf(array, newLength): Copies the original array into a new array with the specified length.
array.length: Returns the length (number of elements) of the array.
Example:
import java.util.Arrays;
public class ArrayMethodsExample {
public static void main(String[] args) {
int[] numbers = {5, 3, 8, 1, 2};
// Sorting the array
Arrays.sort(numbers);
System.out.println("Sorted array: " + Arrays.toString(numbers));
// Filling the array with a single value
Arrays.fill(numbers, 7);
System.out.println("Array after fill: " + Arrays.toString(numbers));
// Searching for a value in the sorted array
int index = Arrays.binarySearch(numbers, 7);
System.out.println("Index of 7 in the array: " + index);
// Copying the array
int[] newArray = Arrays.copyOf(numbers, 10);
System.out.println("New array after copy: " + Arrays.toString(newArray));
// Checking if two arrays are equal
int[] otherArray = {7, 7, 7, 7, 7};
boolean isEqual = Arrays.equals(numbers, otherArray);
System.out.println("Are the two arrays equal? " + isEqual);
// Getting the length of the array
System.out.println("Length of the array: " + numbers.length);
}
}
Practice Exercise
Create an array of 6 integers. Use the Arrays.fill() method to initialize all elements with the value 10. Then, sort the array, perform a binary search for the number 10, and print the index. Check the length of the array using the length property and print it. Finally, compare this array to another array with identical elements and print the result.