Java Array
# Java Arrays
Arrays are one of the most important data structures in every programming language, and of course, different languages implement and handle arrays differently.
The arrays provided in the Java language are used to store fixed-size elements of the same type.
You can declare an array variable, such as `numbers`, instead of directly declaring 100 individual variables `number0`, `number1`, ..., `number99`.
This tutorial will introduce the declaration, creation, and initialization of Java arrays, along with their corresponding code.
* * *
## Declaring Array Variables
You must first declare an array variable before you can use arrays in a program. Here is the syntax for declaring an array variable:
```java
dataType[] arrayRefVar; // Preferred way
or
```java
dataType arrayRefVar[]; // Works but not preferred way
**Note:** It is recommended to use the `dataType[] arrayRefVar` style to declare array variables. The `dataType arrayRefVar[]` style comes from the C/C++ language and is adopted in Java to allow C/C++ programmers to quickly understand the Java language.
### Example
Here are code examples for both syntaxes:
```java
double[] myList; // Preferred way
or
```java
double myList[]; // Works but not preferred way
* * *
## Creating Arrays
The Java language uses the `new` operator to create arrays. The syntax is as follows:
```java
arrayRefVar = new dataType;
The above syntax statement does two things:
* It creates an array using `dataType`.
* 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:
```java
dataType[] arrayRefVar = new dataType;
Alternatively, you can create arrays using the following way:
```java
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The elements of an array are accessed through their index. 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 `double` type elements, and assigns its reference to the `myList` variable.
## TestArray.java File Code:
```java
public class TestArray {
public static void main(String[] args) {
// Array size
int size = 10;
// Define array
double[] myList = new double;
myList = 5.6;
myList = 4.5;
myList = 3.3;
myList = 13.2;
myList = 4.0;
myList = 34.33;
myList = 34.0;
myList = 45.45;
myList = 99.993;
myList = 11123;
// Calculate the sum of all elements
double total = 0;
for (int i = 0; i < size; i++) {
total += myList;
}
System.out.println("Total is " + total);
}
}
The output of the above example is:
Total is 11367.373
The following diagram illustrates the array `myList`. Here, the `myList` array contains 10 `double` elements, with indices ranging from 0 to 9.

* * *
## Processing Arrays
The element type and size of an array are fixed, so when processing array elements, we typically use basic loops or For-Each loops.
### Example
This example fully demonstrates how to create, initialize, and manipulate arrays:
## TestArray.java File Code:
```java
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 + " ");
}
// Calculate the sum of all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList;
}
System.out.println("Total is " + total);
// Find the maximum element
double max = myList;
for (int i = 1; i max)
max = myList;
}
System.out.println("Max is " + max);
}
}
The compiled and running result of the above example is as follows:
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 loop type called the For-Each loop or enhanced loop, which can traverse arrays without using an index.
The syntax format is as follows:
```java
for (type element : array) {
System.out.println(element);
}
### Example
This example displays all elements in the array `myList`:
## TestArray.java File Code:
```java
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 compiled and running result of the above example is as follows:
1.9
2.9
3.4
3.5
* * *
## Arrays as Function Parameters
Arrays can be passed as parameters to methods.
For example, the following example is a method that prints elements in an `int` array:
```java
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array + " ");
}
}
The following example calls the `printArray` method to print out 3, 1, 2, 6, 4, and 2:
```java
printArray(new int[]{3, 1, 2, 6, 4, 2});
* * *
## Arrays as Function Return Values
```java
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 = list;
}
return result;
}
In the above example, the `result` array is the return value of the function.
* * *
## Multidimensional Arrays
Multidimensional arrays can be thought of as arrays of arrays. For example, a two-dimensional array is a special one-dimensional array where each element is a one-dimensional array. For example:
```java
String[][] str = new String;
### Dynamic Initialization of Multidimensional Arrays (Taking a Two-Dimensional Array as an Example)
1. Allocate space directly for each dimension, in the following format:
```java
type[][] typeName = new type;
`type` can be a primitive 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:
```java
int[][] a = new int;
Analysis:
The two-dimensional array `a` can be seen as an array with two rows and three columns.
2. Allocate space for each dimension starting from the highest dimension. For example:
```java
String[][] s = new String[];
s = new String;
s = new String;
s = new String("Good");
s = new String("Luck");
s = new String("to");
s = new String("you");
s = new String("!");
Analysis:
**`s=new String`** and **`s=new String`** allocate reference space for the highest dimension, which means limiting the maximum length of data it can hold for the highest dimension. Then, space is allocated individually for each array element, such as the operation **`s=new String("Good")`**.
### Referencing Multidimensional Arrays (Taking a Two-Dimensional Array as an Example)
For each element in a two-dimensional array, the reference format is **`arrayName`**, for example:
```java
num;
* * *
## Arrays Class
The `java.util.Arrays` class provides convenient methods for manipulating arrays. All methods provided are static.
It has the following functions:
* Assigning values to arrays: via the `fill` method.
* Sorting arrays: via the `sort` method, in ascending order.
* Comparing arrays: via the `equals` method to compare if the element values in arrays are equal.
* Searching for array elements: via the `binarySearch` method to perform binary search on a sorted array.
For specific details, please refer to the following table:
| No. | Method and Description |
| --- | --- |
| 1 | **public static int binarySearch(Object[] a, Object key)** Searches for the given value object (Byte, Int, double, etc.) in the given array using the binary search algorithm. The array must be sorted before calling this method. If the search value is contained in the array, the index of the search key is returned; otherwise, it returns (-(_insertion point_) - 1). |
| 2 | **public static boolean equals(long[] a, long[] a2)** Returns true if the two specified `long` arrays are _equal_ to each other. Two arrays are considered equal if they contain the same number of elements and all corresponding element pairs are equal. In other words, two arrays are equal if they contain the same elements in the same order. The same method applies to all other primitive data types (Byte, short, Int, etc.). |
| 3 | **public static void fill(int[] a, int val)** Assigns the specified `int` value to each element in the specified range of the specified `int` array. The same method applies to all other primitive data types (Byte, short, Int, etc.). |
| 4 | **public static void sort(Object[] a)** Sorts the specified object array according to the natural ordering of its elements in ascending order. The same method applies to all other primitive data types (Byte, short, Int, etc.). |
YouTip