Java Arrays
Arrays are an important data structure in every programming language, although the implementation and handling of arrays can vary between different languages.
In Java, arrays are provided to store elements of the same type with a fixed size.
You can declare an array variable, such as numbers[100]
, instead of directly declaring 100 individual variables like number0
, number1
, ..., number99
.
This tutorial will introduce the declaration, creation, and initialization of Java arrays, along with their corresponding code examples.
Declaring Array Variables
You must declare an array variable before you can use it in your program. Below is the syntax for declaring an array variable:
dataType[] arrayRefVar; // Preferred method
or
dataType arrayRefVar[]; // Works the same, but not the preferred method
Note: It is recommended to use the dataType[] arrayRefVar
style for declaring array variables. The dataType arrayRefVar[]
style comes from C/C++ languages and is adopted in Java to help C/C++ programmers quickly understand Java.
Example
Here are examples of both syntaxes:
double[] myList; // Preferred method
or
double myList[]; // Works the same, but not the preferred method
Creating Arrays
Java uses the new
operator to create arrays, with the following syntax:
arrayRefVar = new dataType[arraySize];
The above syntax does two things:
- One, it creates an array using
dataType[arraySize]
. - Two, it assigns the reference of the newly created array to the variable
arrayRefVar
.
The declaration of an array variable and the creation of an array can be done in one statement, as shown below:
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively, you can create an array as follows:
dataType[] arrayRefVar = {value0, value1, ..., valuek};
Array elements are accessed through indices. Array indices start from 0, so the index values range from 0 to arrayRefVar.length-1
.
Example
The following statement first declares an array variable myList
, then creates an array containing 10 elements of type double
, and assigns its reference to the myList
variable.
TestArray.java File Code:
public class TestArray {
public static void main(String[] args) {
// Array size
int size = 10;
// Define array
double[] myList = new double[size];
myList[0] = 5.6;
myList[1] = 4.5;
myList[2] = 3.3;
myList[3] = 13.2;
myList[4] = 4.0;
myList[5] = 34.33;
myList[6] = 34.0;
myList[7] = 45.45;
myList[8] = 99.993;
myList[9] = 11123;
// Calculate the sum of all elements
double total = 0;
for (int i = 0; i < size; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
}
}
The output of the above example is:
Total is 11367.373
The following image depicts the array myList
. Here, myList
contains 10 double
elements, with indices ranging from 0 to 9.
Processing Arrays
Since both the element type and the size of an array are fixed, basic loops or For-Each loops are commonly used when processing array elements.
Example
This example fully demonstrates how to create, initialize, and manipulate arrays:
TestArray.java File Code:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
This example will output the elements of the array, their total sum, and the largest element.
System.out.println(myList[i] + " ");
}
// Calculate the sum of all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Find the maximum element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
The above example compiles and runs with the following results:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
For-Each Loop
JDK 1.5 introduced a new type of loop called the For-Each loop or enhanced loop, which allows you to traverse arrays without using an index.
The syntax is as follows:
for(type element: array)
{
System.out.println(element);
}
Example
This example is used to display all elements in the array myList:
TestArray.java File Code:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all array elements
for (double element: myList) {
System.out.println(element);
}
}
}
The above example compiles and runs with the following results:
1.9
2.9
3.4
3.5
Array as Function Parameter
Arrays can be passed as parameters to methods.
For example, the following method prints the elements of an int array:
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
The following example calls the printArray method to print 3, 1, 2, 6, 4, and 2:
printArray(new int[]{3, 1, 2, 6, 4, 2});
Array as Function Return Value
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
In the above example, the result array is returned as the function's return value.
Multidimensional Arrays
Multidimensional arrays can be thought of as arrays of arrays. For example, a two-dimensional array is a special type of one-dimensional array, where each element is a one-dimensional array, such as:
String[][] str = new String[3][4];
Dynamic Initialization of Multidimensional Arrays (Taking Two-Dimensional Arrays as an Example)
- Directly allocate space for each dimension, with the following format:
type[][] typeName = new type[typeLength1][typeLength2];
type can be a basic data type or a composite data type, typeLength1 and typeLength2 must be positive integers, typeLength1 is the number of rows, and typeLength2 is the number of columns.
For example:
int[][] a = new int[2][3];
Explanation:
The two-dimensional array a can be seen as an array with two rows and three columns.
- Start from the highest dimension and allocate space for each dimension, for example:
String[][] s = new String[2][]; s[0] = new String[2]; s[1] = new String[3]; s[0][0] = new String("Good"); s[0][1] = new String("Luck"); s[1][0] = new String("to"); s[1][1] = new String("you");
s[1][2] = new String("!");
s[0] = new String[2];
s[1] = new String[3];
s[0] = new String("Good");
Multidimensional Array Reference (Example with 2D Array)
To reference each element in a 2D array, use the format arrayName[index1][index2], for example:
num[1][0];
Arrays Class
The java.util.Arrays class provides convenient methods for manipulating arrays and all its methods are static.
It includes the following functionalities:
- Assigning values to arrays: using the fill method.
- Sorting arrays: using the sort method in ascending order.
- Comparing arrays: using the equals method to check if the elements in two arrays are equal.
- Searching array elements: using the binarySearch method for sorted arrays to perform a binary search.
Detailed descriptions are as follows:
No. | Method and Description |
---|---|
1 | public static int binarySearch(Object[] a, Object key) <br> Searches the specified array for the specified value using the binary search algorithm. The array must be sorted prior to making this call. If the value is contained in the array, it returns the index of the search key; otherwise, it returns (-(insertion point) - 1). |
2 | public static boolean equals(long[] a, long[] a2) <br> Returns true if the two specified long arrays are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. This method also applies to all other primitive data types (Byte, short, Int, etc.). |
3 | public static void fill(int[] a, int val) <br> Assigns the specified int value to each element of the specified range of the specified int array. This method also applies to all other primitive data types (Byte, short, Int, etc.). |
4 | public static void sort(Object[] a) <br> Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. This method also applies to all other primitive data types (Byte, short, Int, etc.). |