Core Java

Java Arrays Tutorial

1. Introduction

In computer programming, an array is a collection of items stored in contiguous memory locations. In Java, an array is a data structure that stores multiple values of the same data type in a single variable. It is useful for handling a collection of data efficiently and commonly used for repetitive operations on a set of items. The java.util.Arrays class is a part of the Java Collection Framework. It provides utility functions for arrays of primitive types and reference objects. These utility functions include sorting, searching, copying, filling, and comparing. I will outline Array tutorial with the following examples:

  • Declare, create, and initialize array objects.
  • Convert Array to List via the Arrays.toList method.
  • Sort arrays via Arrays.sort and Arrays.parallelSort methods.
  • Search element with binarySearch method in a sorted array.

2. Set up a Maven Project

In this step, I will create a simple maven project with only Junit dependency as arrays tutorial.

pom.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.zheng.demo</groupId>
    <artifactId>ArraysDemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <!--
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.10.2</version>
            <scope>test</scope>
        </dependency>
 
    </dependencies>
</project>

3. Basic Array Operations

To use arrays in Java, you need to declare a variable to hold the array, create the array, and then initialize its elements. In this step, I will create a TestArraysBasic Junit class with test methods which show how to declare, create, and initialize an array, how to access array elements, how to convert array to a list, how to copy an array, and how to fill array elements.

  • setup – create and initialize array objects.
  • test_asList – use the asList method to convert an array to a list.
  • test_compare – use the compare method to compare two arrays.
  • test_copyOf – use the copyOf method to copy an array to a new array with different size.
  • test_fill – use the fill method to populate the array elements based on the index range.
  • test_mismatch – use the mismatch method to find the first mismatched element’s index between two arrays.
  • test_toString – use the toString method to print out the string version of an array object.

TestArraysBasic.java

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package org.zheng.demo;
 
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
 
import java.util.Arrays;
import java.util.List;
 
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
 
/*
 * Covers Declaration, Creation, Initialization, Accessing, Conversation, comparison, copy, fill, etc
 */
 
class TestArraysBasic {
 
    // Array Declaration,
    // declare an array by specifying the type of its elements followed by square
    // brackets
    private String[] stringArray;
    private Integer[] intArray;
    private boolean[] booleanArray;
 
    // Declaration, Creation, Initialization
    boolean[] booleanArray2 = { true, false, true };
 
    @BeforeEach
    void setup() {
        // Array Creation
        // create an array using the new keyword followed by the type of elements and
        // the number of elements
        stringArray = new String[] { "Mary", "John", "Bob" };
        booleanArray = new boolean[] { true, false, true };
        intArray = new Integer[] { 1, 3, 5 };
 
    }
 
    @Test
    void test_asList() {
        List<String> stringList = Arrays.asList(stringArray);
 
        assertEquals("Mary", stringList.get(0), "the first List is Mary");
        assertEquals("John", stringList.get(1), "the second List is John");
        assertEquals("Bob", stringList.get(2), "the third List is Bob");
 
        // changes made to array is cascaded to the list
        stringArray[0] = "Zheng";
        assertEquals("Zheng", stringList.get(0), "the first List is Changed to Zheng");
 
        // changes made to list is cascaded to the array as well
        stringList.set(2, "Terry");
        assertEquals("Terry", stringArray[2], "the third Array is Change to Terry");
 
    }
 
    @Test
    void test_compare() {
        int return0 = Arrays.compare(booleanArray, booleanArray2);
        assertEquals(0, return0, "both array should be same");
 
        // Accessing Array Elements
        booleanArray2[2] = false;
        booleanArray2[1] = true;
        int return1 = Arrays.compare(booleanArray2, booleanArray);
        assertEquals(1, return1, "both array should NOT be same after swapped order");
    }
 
    @Test
    void test_copyOf() {
        boolean[] newArray = Arrays.copyOf(booleanArray, 5);
        assertEquals(5, newArray.length);
        assertFalse(newArray[4], "extra elements use default false value");
 
        newArray[3] = true;
        assertTrue(newArray[3], "updated element to true");
    }
 
    @Test
    void test_fill() {
        String[] newArray = Arrays.copyOf(stringArray, 20);
 
        Arrays.fill(newArray, 0, 19, "NA");
 
        List<String> tt = Arrays.asList(newArray);
 
        tt.stream().limit(19).forEach(boo -> assertTrue(boo.equalsIgnoreCase("NA")));
        assertNull(newArray[19]);
    }
 
    @Test
    void test_mismatch() {
        String[] newArray = Arrays.copyOf(stringArray, 4);
 
        int mismatchIndex = Arrays.mismatch(stringArray, newArray);
        assertEquals(3, mismatchIndex, "this first mismatch index is 3");
    }
 
    @Test
    void test_toString() {
        String booleanArrayString = Arrays.toString(booleanArray);
        assertEquals("[true, false, true]", booleanArrayString, "the boolean [] toString");
        System.out.println("booleanArrayString: " + booleanArrayString.toString());
 
        String intArrayString = Arrays.toString(intArray);
        assertEquals("[1, 3, 5]", intArrayString, "the Integer [] toString");
        System.out.println("intArrayString: " + intArrayString.toString());
 
        // but ToString on String is the memory address
        assertTrue(stringArray.toString().contains("java.lang.String"));
        System.out.println("stringArray: " + stringArray.toString());
 
    }
}
  • Line 23, 24, 25: declares three arrays.
  • Line 28: declare and initialize an array.
  • Line 35, 36, 37: create and initialize arrays.
  • Line 42: convert an array to a list and verify that converted list and array are in-sync on the element value. Changes made to the array will be visible in the returned list, and changes made to the list will be visible in the array.
  • Line 60: compare two arrays lexicographically.
  • Line 72: create a new array with Arrays.copyOf method.
  • Line 82: populate the array elements with the fill method and verify with Stream.forEach method.
  • Line 94: find out the first mismatched element index position between two arrays.
  • Line 102: print out the array data via toString. please note that the String type prints out the memory address not the string content.

Execute Junit test and all passed.

TestArraysBasic output

1
2
3
booleanArrayString: [true, false, true]
intArrayString: [1, 3, 5]
stringArray: [Ljava.lang.String;@6771beb3

4. Sort and Search Array

In this step, I will create a TestSearchArray Junit class to demonstrate how to sort and search array via Arrays.sort and Arrays.binarySearch methods.

  • test_binarySearch – use the binarySearch method to find the element in a sorted array
  • test_parallelSort – use parallelSort method to sort an array

TestSearchArray.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
package org.zheng.demo;
 
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
 
import java.util.Arrays;
 
import org.junit.jupiter.api.Test;
 
public class TestSearchArray {
 
    @Test
    void test_binarySearch() {
        String[] stringArray = new String[] { "terry", "Mary", "John", "Bob" };
        Arrays.sort(stringArray, (s1, s2) -> s1.compareTo(s2));
        int foundIdx = Arrays.binarySearch(stringArray, 0, 3, "Bob", (s1, s2) -> s1.compareTo(s2));
        assertEquals(0, foundIdx, "should find \"Bob\" at the first element");
 
    }
 
    @Test
    void test_parallelSort() {
        int[] intArray = new int[2000];
        for (int i = 0; i < 2000; i++) {
            intArray[i] = (int) (Math.random() * 1000);
        }
 
        Arrays.parallelSort(intArray);
        for (int j = 0; j < 2000 - 1; j++) {
            assertTrue(intArray[j] <= intArray[j + 1]);
        }
 
        int found520 = Arrays.binarySearch(intArray, 520);
        System.out.println("the 520 is found at the intArray at position:" + found520);
    }
 
}
  • Line 13: sort the array, then use the binarySearch to find an element.
  • Line 22: parallelSort the array before using binarySearch to find an element.

Executed the junit tests and all passed.

5. Loop Array

In this step, I will create a TestLoopArray Junit class to loop the array with 4 ways.

  • loop_via_do_while – execute at least once with the do..while clause.
  • loop_via_for – repeat with fixed times via the for keyword.
  • loop_via_stream – use the Stream.forEach method to loop the elements in a sorted array.
  • loop_via_while – use the while keyword. similar to do..while but it may execute 0 times.

TestLoopArray.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 org.zheng.demo;
 
import java.util.Arrays;
 
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
 
public class TestLoopArray {
 
    private String[] stringArray;
 
    @Test
    void loop_via_do_while() {
        int idx = 0;
        do {
            System.out.println(stringArray[idx]);
            idx++;
        } while (idx < stringArray.length);
    }
 
    @Test
    void loop_via_for() {
        for (String str : stringArray) {
            System.out.println(str);
        }
    }
 
    @Test
    void loop_via_stream() {
        Arrays.asList(stringArray).stream().forEach(s -> System.out.println(s));
    }
 
    @Test
    void loop_via_while() {
        int idx = 0;
        while (idx < stringArray.length) {
            System.out.println(stringArray[idx]);
            idx++;
        }
    }
 
    @BeforeEach
    void setup() {
        stringArray = new String[] { "terry", "Mary", "John", "Bob" };
 
    }
}
  • Line 13: use the do ... while loop.
  • Line 22: use the for loop with fixed repeation.
  • Line 29: use the Stream.forEach method.
  • Line 34: use the while loop.

Executed the junit tests and captured the output.

TestLoopArray output

1
2
3
4
terry
Mary
John
Bob

6. Conclusion

In this tutorial, I created three Junit test classes. The TestArraysBasic class at step 3 demonstrated basic array operations: declaration, creation, initialization, and accessing the elements as well as static methods from java.util.Arrays class to compare, convert, fill, and search an element in an Array. The TestSearchArray class at step 4 demonstrated how to sort and search an element in an Array. Step 5 demonstrated four ways to loop an Array. As you see in this arrays tutorial, there are three key characteristics of arrays:

  • Fixed Size: once an array is created, its size is fixed and cannot be changed. The size must be specified at the time of creation.
  • Indexed Access: elements in an array can be accessed using an index. The index is zero-based, meaning the first element is at index 0, the second at index 1, and so on.
  • Homogeneous Elements: all elements in an array must be of the same data type. This can be a primitive type, e.g., int, float, char or a reference type. e.g., objects of a class.

7. Download

This was an example of a java maven project to demonstrate arrays tutorial with examples.

Download
You can download the full source code of this example here: Java Arrays Tutorial

Mary Zheng

Mary graduated from the Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She worked as a lead Software Engineer where she led and worked with others to design, implement, and monitor the software solution.
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