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
toList
via theArrays.toList
method. - Sort arrays via
Arrays.sort
andArrays.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
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.zheng.demo</groupId> <artifactId>ArraysDemo</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api --> <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 theasList
method to convert an array to a list.test_compare
– use thecompare
method to compare two arrays.test_copyOf
– use thecopyOf
method to copy an array to a new array with different size.test_fill
– use thefill
method to populate the array elements based on the index range.test_mismatch
– use themismatch
method to find the first mismatched element’s index between two arrays.test_toString
– use thetoString
method to print out the string version of an array object.
TestArraysBasic.java
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 withStream.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 theString
type prints out the memory address not the string content.
Execute Junit test and all passed.
TestArraysBasic output
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 thebinarySearch
method to find the element in a sorted arraytest_parallelSort
– useparallelSort
method to sort an array
TestSearchArray.java
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 usingbinarySearch
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 thedo..while
clause.loop_via_for
– repeat with fixed times via thefor
keyword.loop_via_stream
– use theStream.forEach
method to loop the elements in a sorted array.loop_via_while
– use thewhile
keyword. similar to do..while but it may execute 0 times.
TestLoopArray.java
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
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.
You can download the full source code of this example here: Java Arrays Tutorial