An array is a very basic and commonly used data structure in Java that can store multiple elements of the same type. Imagine an array as a “container” holding multiple elements, where each element has a unique “position number”—the index—allowing us to quickly locate the corresponding element using this number.
一、Array Definition¶
In Java, defining an array requires declaring an array variable and allocating memory space. There are several common ways to declare and initialize an array:
1. Declaring an Array Variable¶
The syntax for declaring an array variable is:
Data type[] arrayName; (recommended; the alternative Data type arrayName[]; is also valid but less clear).
Example:
int[] scores; // Declare an int array variable named scores
String[] names; // Declare a String array variable named names
2. Allocating Space and Initializing¶
After declaring an array, you need to allocate memory (determine its length) and optionally initialize its elements.
(1) Dynamic Initialization (Specify Length First, Then Assign Values)¶
Specify the array length first, then assign values to each element:
// Declare and dynamically initialize an int array with length 5
int[] numbers = new int[5];
// Assign values to array elements (indexes start at 0)
numbers[0] = 10; // First element
numbers[1] = 20; // Second element
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
Note: The array length is fixed once initialized. numbers.length returns the array length (e.g., 5).
(2) Static Initialization (Assign Values Directly, No Length Specified)¶
Directly provide element values; the compiler infers the length:
// Declare and statically initialize an int array
int[] ages = {18, 20, 22, 25};
// Equivalent explicit initialization
int[] heights = new int[]{170, 175, 180};
Warning: Static initialization cannot specify both length and values simultaneously. The following code is invalid:
int[] arr = new int[3]{1,2,3}; (Error: must omit length or assign values directly).
二、Array Traversal¶
Traversal refers to accessing each element in the array one by one. The two most common methods are:
1. For Loop Traversal (Index-Based)¶
Access elements using the array’s index (starting at 0) with a for loop:
int[] arr = {1, 2, 3, 4, 5};
// Traverse the array
for (int i = 0; i < arr.length; i++) {
System.out.println("Element " + (i+1) + ": " + arr[i]);
}
arr.length: The array length property (no parentheses), used to control the loop count.- Index Out-of-Bounds: Array indices range from
0tolength-1. Accessingarr[length]throwsArrayIndexOutOfBoundsException.
2. Enhanced For Loop (For-Each Loop, No Index Needed)¶
A more concise method to access elements directly without using indices:
int[] arr = {1, 2, 3, 4, 5};
for (int num : arr) { // num is a temporary variable representing each element
System.out.println(num);
}
- Use Case: Ideal when only element values need to be accessed (no index modification required).
三、Common Precautions¶
- Uniform Element Type: All elements in an array must be of the same type. For example, an
int[]array cannot store strings. - Zero-Based Index: The first element uses index
0(not1), a common source of errors for beginners. - Fixed Length: The array length is immutable once initialized; elements cannot be added or removed dynamically.
- Avoid Null Pointer Exceptions: Uninitialized array variables (e.g.,
int[] arr;) cause errors if used directly. Always initialize (allocate memory) first.
四、Complete Example Code¶
public class ArrayDemo {
public static void main(String[] args) {
// 1. Dynamically initialize an array of length 3
int[] scores = new int[3];
scores[0] = 90; // Assign first element
scores[1] = 85;
scores[2] = 95;
// 2. Statically initialize an array
String[] names = {"张三", "李四", "王五"};
// 3. Traverse scores with a for loop
System.out.println("Scores array traversal:");
for (int i = 0; i < scores.length; i++) {
System.out.println("scores[" + i + "] = " + scores[i]);
}
// 4. Traverse names with an enhanced for loop
System.out.println("\nNames array traversal:");
for (String name : names) {
System.out.println(name);
}
}
}
With the above content, you should now understand the basics of Java arrays: definition, initialization, and traversal. Arrays are core tools for handling bulk data, and mastering array operations will help you solve problems more efficiently. Next, try exercises like calculating the sum of array elements or finding the maximum value to reinforce your learning.