Java Arrays: Useful Functions

Java is a powerful programming language that offers a wide range of built-in functions and modules to help developers efficiently perform various tasks. One such module is the Java Arrays module, which provides a variety of functions for manipulating arrays. In this blog post, we will explore some of the most useful functions in the Java Arrays module.

Arrays.sort()

The Arrays.sort() function is used to sort arrays in ascending order. This function takes an array as an argument and returns a sorted array. The sort function uses the natural ordering of the elements in the array to sort them.

Example:

int[] arr = {5, 2, 8, 1, 9};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));

Output:

[1, 2, 5, 8, 9]

Arrays.binarySearch()

The Arrays.binarySearch() function is used to search for an element in a sorted array. This function takes two arguments: the sorted array and the element to search for. If the element is found in the array, the function returns the index of the element. If the element is not found, the function returns a negative number.

Example:

int[] arr = {1, 2, 5, 8, 9};
int index = Arrays.binarySearch(arr, 5);
System.out.println(index);

Output:

2

Arrays.copyOf()

The Arrays.copyOf() function is used to create a new array that is a copy of an existing array. This function takes two arguments: the array to copy and the length of the new array. If the length argument is greater than the length of the original array, the new array is padded with zeros.

Example:

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

Output:

[1, 2, 3]

Arrays.fill()

The Arrays.fill() function is used to fill an array with a specified value. This function takes two arguments: the array to fill and the value to fill it with.

Example:

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

Output:

[0, 0, 0, 0, 0]

Arrays.stream()

The Arrays.stream() function is used to create a stream from an array. This function takes an array as an argument and returns a stream that contains the elements of the array.

Example:

int[] arr = {1, 2, 3, 4, 5};
int sum = Arrays.stream(arr).sum();
System.out.println(sum);

Output:

15

In conclusion, the Java Arrays module provides a variety of functions for manipulating arrays. These functions can help developers efficiently perform tasks such as sorting, searching, copying, filling, and streaming arrays. By mastering these functions, developers can write more efficient and effective code in Java.

Did you find this article valuable?

Support Samara Simha Reddy Yasani by becoming a sponsor. Any amount is appreciated!