Arrays

Java Array – java.util.Arrays Example (with Video)

In this example, we will explain the array definition and we will show the range of functionality provided by the Java arrays class: java.util.Arrays. This class of the java.util package contains several static methods that you can use to compare, sort, and search in arrays. In addition, you can use this class to assign a value to one or more elements of an array. This class is a member of the Collections Framework.

An array of integers (int[]) will be used as our base array in the following example to illustrate most of the methods provided by the java.util.Arrays class. But before diving into the practical examples, let us understand the different types that are available in the Java programming language.

You can also check this tutorial in the following video:

Java Array Example How to use Arrays in Java – Video
  • One-Dimensional Arrays: The type that consists of the array type and name. The array type will determine the type of array and the elements will determine the type of element inside the array. Let us understand the declaration of One-D arrays with an example.
    1
    2
    3
    4
    5
    int[] arr1  // A one-dimensional array of integer elements.
    String[] arr2   // A one-dimensional array of string elements.
    float[] arr3    // A one-dimensional array of floating-point elements.
     
    Object[] arr4   // A one-dimensional array of object elements. This array can either consist of mixture of primitive type elements or secondary elements.

  • Multi-Dimensional Arrays: It is an array of arrays where each element holds a reference of another array. These types of arrays are also called Jagged Arrays and are defined in the following manner. Let us understand the declaration of Two-D arrays with an example.
    1
    2
    int[][] arry1 = new int[10][20];    //a 2D array or matrix
    int[][][] arr2 = new int[10][20][10];   //a 3D array

    Please note, these days the IT industry has obsolete the use of multi-dimensional arrays due to the extensive use of collections.

  • Array Literals: These are used in a situation where the array size and variables are known. Let us understand the declaration of Array Literals with an example.
    1
    int[] intArray = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };   // Declaring array literal

    In this, the array length is automatically determined by the number of elements.

But let’s examine the array definition, by using the following examples.

1. Example of Java Arrays methods

Now let us start with an example to understand the basic declaration and different methods in Arrays. But before digging deep let us look at different methods we will be using in this example.

Java Array

1.1 Arrays.toString() method

This method returns the String representation of the array enclosed in the square brackets ([]). Adjacent elements are separated by the comma character (i.e. a comma followed by a space). Let us understand this with a simple example.

Snippet

1
2
Integer[] integerArray = { 2, 4, 3, 7, 21, 9, 98, 76, 74 };
System.out.printf("integerArray elements: %s\n", Arrays.toString(integerArray));

1.2 Arrays.asList() method

This method returns a list backed by a given array. In other words, both the list and array refer to the same location. Let us understand this with a simple example.

Snippet

1
List integerList = Arrays.asList(integerArray);     // Returns a fixed-size list backed by the specified array.

1.3 Arrays.sort() method

This method sorts the specified array into ascending numerical order. Let us understand this with a simple example.

Snippet

1
Arrays.sort(baseArray);

1.4 Arrays.binarySearch() method

This method returns an integer value for the index of the specified key in the specified array. Return a negative number if the key is not found and for this method to work properly, the array must be sorted. Let us understand this with a simple example.

Snippet

1
int idx = Arrays.binarySearch(baseArray, 21);       // Searches the specified array of ints for the specified value using the binary search algorithm.

1.5 Arrays.copyOf() method

This method copies the specified array, truncates or pads with zeros (if necessary) so the copy has the specified length. Let us understand this with a simple example.

Snippet

1
int[] copyOfArray = Arrays.copyOf(baseArray, 11);       // Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.

1.6 Arrays.copyOfRange() method

This method copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. Let us understand this with a simple example.

Snippet

1
int[] copyOfRangeArray = Arrays.copyOfRange(baseArray, 5, 8);       // Copies the specified range of the specified array into a new array.

1.7 Arrays.fill() method

This method fills all elements of the specified array with the specified value. Let us understand this with a simple example.

Snippet

1
2
3
4
int[] fillArray = new int[5];       // Assigns the specified int value to each element of the specified array of ints.
System.out.printf("fillArray (before): %s\n", Arrays.toString(fillArray));
Arrays.fill(fillArray, 1);
System.out.printf("fillArray (after): %s", Arrays.toString(fillArray));

1.8 Complete Example

Let us consider the below example where we will illustrate all the methods explained above.

JavaUtilArraysExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.javacodegeeks.examples;
 
import java.util.Arrays;
import java.util.List;
 
public class JavaUtilArraysExample {
 
    public static void main(String[] args) {
 
        Integer[] integerArray = { 2, 4, 3, 7, 21, 9, 98, 76, 74 };     // Base array for the example. It contains 9 elements.
        System.out.printf("integerArray size: %d\n", integerArray.length);
        System.out.printf("integerArray elements: %s\n", Arrays.toString(integerArray));
 
        List<Integer> integerList = Arrays.asList(integerArray);      // Returns a fixed-size list backed by the specified array.
        System.out.printf("integerList size: %d\n", integerList.size());
        System.out.printf("integerList elements: ");
        for (Integer i : integerList) {
            System.out.printf("%d ", i);
        }
        System.out.printf("\n\n");
 
        int[] baseArray = { 2, 4, 3, 7, 21, 9, 98, 76, 74 };
        System.out.printf("Unsorted baseArray: %s\n", Arrays.toString(baseArray));
 
        Arrays.sort(baseArray);
        System.out.printf("Sorted baseArray: %s\n", Arrays.toString(baseArray));
 
        int idx = Arrays.binarySearch(baseArray, 21);       // Searches the specified array of ints for the specified value using the binary search algorithm.
        System.out.printf("Value \"21\" found at index: %d\n\n", idx);
 
        System.out.printf("baseArray size: %d\n", baseArray.length);
        System.out.printf("baseArray elements: %s\n", Arrays.toString(baseArray));
 
        int[] copyOfArray = Arrays.copyOf(baseArray, 11);       // Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
        System.out.printf("copyOfArray size: %d\n", copyOfArray.length);
        System.out.printf("copyOfArray elements: %s\n\n", Arrays.toString(copyOfArray));
 
        System.out.printf("baseArray: %s\n", Arrays.toString(baseArray));      
        int[] copyOfRangeArray = Arrays.copyOfRange(baseArray, 5, 8);       // Copies the specified range of the specified array into a new array.
        System.out.printf("copyOfRangeArray: %s\n\n", Arrays.toString(copyOfRangeArray));
 
        int[] fillArray = new int[5];       // Assigns the specified int value to each element of the specified array of ints.
        System.out.printf("fillArray (before): %s\n", Arrays.toString(fillArray));
        Arrays.fill(fillArray, 1);
        System.out.printf("fillArray (after): %s", Arrays.toString(fillArray));
    }
}

If everything goes well, we will get the following results in the console.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
integerArray size: 9
integerArray elements: [2, 4, 3, 7, 21, 9, 98, 76, 74]
integerList size: 9
integerList elements: 2 4 3 7 21 9 98 76 74
Unsorted baseArray: [2, 4, 3, 7, 21, 9, 98, 76, 74]
Sorted baseArray: [2, 3, 4, 7, 9, 21, 74, 76, 98]
Value "21" found at index: 5
baseArray size: 9
baseArray elements: [2, 3, 4, 7, 9, 21, 74, 76, 98]
copyOfArray size: 11
copyOfArray elements: [2, 3, 4, 7, 9, 21, 74, 76, 98, 0, 0]
baseArray: [2, 3, 4, 7, 9, 21, 74, 76, 98]
copyOfRangeArray: [21, 74, 76]
fillArray (before): [0, 0, 0, 0, 0]
fillArray (after): [1, 1, 1, 1, 1]

2. Some more methods of the Java Array class

Java Arrays add some interesting method arguments to the existing sort() and fill() method i.e.

  • Arrays.sort(int[] a, int fromIndex, int endIndex): Sorts the specified range of the array into ascending order. The range to be sorted extends from the index fromIndex, inclusive, to the index toIndex, exclusive. If fromIndex == toIndex, the range to be sorted is empty
  • Arrays.fill(int[] a, int fromIndex, int endIndex): Fills elements of the specified array with the specified value from the fromIndex element, but not including the toIndex element

Let us understand these modifications with an example.

JavaUtilArraysMoreMethodsExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.javacodegeeks.examples;
import java.util.Arrays;
public class JavaUtilArraysMoreMethodsExample {
    public static void main(String[] args) {
        // Base array for the example. It contains 9 elements.
        int[] baseArray = { 2, 4, 3, 7, 21, 9, 98, 76, 74 };
        
        // Sorts the specified range of the array into ascending order.
        System.out.printf("Unsorted baseArray: %s\n", Arrays.toString(baseArray));
        
        Arrays.sort(baseArray, 1, 6);
        
        System.out.printf("Sorted baseArray: %s\n\n", Arrays.toString(baseArray));
        
        // Assigns the specified int value to each element of the
        // specified range of the specified array of ints.
        int[] fillArray = new int[10];     
        
        System.out.printf("fillArray (before): %s\n", Arrays.toString(fillArray));     
        
        Arrays.fill(fillArray, 1, 7, 3);
        
        System.out.printf("fillArray (after): %s", Arrays.toString(fillArray));
    }
}

If everything goes well, we will get the following results in the console.

1
2
3
4
Unsorted baseArray: [2, 4, 3, 7, 21, 9, 98, 76, 74]
Sorted baseArray: [2, 3, 4, 7, 9, 21, 98, 76, 74]
fillArray (before): [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
fillArray (after): [0, 3, 3, 3, 3, 3, 3, 0, 0, 0]

4. Download the Source Code

That was an article explaining the array definition in Java through examples.

Download
You can download the source code of this example from here: Java Array – java.util.Arrays Example

Last updated on Jan. 25th, 2022

Armando Flores

Armando graduated from from Electronics Engineer in the The Public University Of Puebla (BUAP). He also has a Masters degree in Computer Sciences from CINVESTAV. He has been using the Java language for Web Development for over a decade. He has been involved in a large number of projects focused on "ad-hoc" Web Application based on Java EE and Spring Framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button