Java Array Class

Profile picture for user arilio666

The Java Array Class is a built-in Java class that provides methods and features for working with arrays. Arrays hold a group of related data kinds in a single memory block. The Array Class contains numerous array manipulation methods, including sorting, searching, and copying.

Declaration of class

The declaration for Java.util is as follows.

public class Arrays extends Object

Here are some of the commonly used Array Class methods:

  1. sort(): ascendingly arranges the elements of an array.
  2. binarySearch(): uses the binary search technique to find an entry in a sorted array.
  3. copyOf(): returns a new array of the specified length that contains elements copied from the original array.
  4. fill(): This function assigns a value to each element of an array.
  5. toString(): returns a string representation of an array's contents.
  6. equals(): compares the equality of two arrays.
  7. asList(): creates a fixed-size list from the provided array.

These methods, coupled with those offered by the Array Class, make interacting with arrays in Java easier and more efficient.

Here are some examples of how to use the Java Array Class's methods:

sort()

int[] numbers = {4, 2, 6, 8, 1};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));

Output: [1, 2, 4, 6, 8]

binarySearch()

int[] numbers = {1, 2, 4, 6, 8};
int index = Arrays.binarySearch(numbers, 4);
System.out.println(index);

Output: 2

copyOf()

int[] numbers = {1, 2, 3};
int[] copiedNumbers = Arrays.copyOf(numbers, 5);
System.out.println(Arrays.toString(copiedNumbers));

Output: [1, 2, 3, 0, 0]

fill()

int[] numbers = new int[5];
Arrays.fill(numbers, 10);
System.out.println(Arrays.toString(numbers));

Output: [10, 10, 10, 10, 10]

toString()

int[] numbers = {1, 2, 3};
System.out.println(Arrays.toString(numbers));

Output: [1, 2, 3]

equals()

int[] numbers1 = {1, 2, 3};
int[] numbers2 = {1, 2, 3};
boolean equalArrays = Arrays.equals(numbers1, numbers2);
System.out.println(equalArrays);

Output: true

asList()

String[] words = {"hello", "world"};
List<String> wordList = Arrays.asList(words);
System.out.println(wordList);

Output: [hello, world]

Tags