SoFunction
Updated on 2025-04-20

Five ways to initialize Java arrays

1. Static initialization: concise but fixed

Code Example

// Simplified writingint[] arr1 = {1, 2, 3}; 
// Complete writing method (applicable to method parameters)String[] arr2 = new String[]{"a", "b", "c"};

Core features

  • Direct assignment when declaring: All elements are determined at initialization.
  • No need to specify length: The compiler automatically infers the length.
  • Not split: Declaration and initialization must be completed at the same time.

Applicable scenarios

  • A fixed set of all elements (such as configuration items, enumeration values) is known.
  • A small array needs to be initialized quickly.

Things to note

  • Mixed writing is prohibitednew int[3]{1,2,3}Will compile errors.
  • Non-reusability: The number of elements cannot be directly modified after initialization.

2. Dynamic initialization: flexible but requires manual management

Code Example

int[] arr = new int[5]; // Initialize an array with length 5arr[0] = 10; // Assign values ​​one by onearr[1] = 20;

// Loop assignment (such as generating sequences)for (int i = 0; i < ; i++) {
    arr[i] = i * 2;
}

Core features

  • Allocation of memory and then assignment: Specify the array length explicitly.
  • Default value mechanism: Elements that are not explicitly assigned are initialized by type (e.g.intis 0, the object isnull)。

Applicable scenarios

  • The array length is determined at runtime (such as user input, file reading).
  • Preallocated memory is required to process large amounts of data.

Things to note

  • Default value trap: Forgot to assign may lead to logical errors (for example, if the unassigned element isnull)。
  • Memory waste risk: Preallocated too large arrays may occupy excess memory.

3. Anonymous array: temporary delivery tool

Code Example

// Direct initialization when callingprintArray(new int[]{1, 2, 3}); 

// Return value scenariopublic static int[] getNumbers() {
    return new int[]{10, 20, 30};
}

Core features

  • No variable name: Use directly in method calls or return.
  • Short life cycle: Usually only used for single operation.

Applicable scenarios

  • Temporary array passing (such as parameter construction in unit tests).
  • Avoid creating redundant variables.

4. Tool class filling: efficient batch operation

Code Example

import ;

int[] arr = new int[5];
(arr, 100); // All elements are filled to 100
// Partial fill(arr, 1, 3, 200); // Index 1 to 2 (left closed and right open) fills 200

Core features

  • Quick unified assignment: Suitable for initializing default values ​​or resetting arrays.
  • Supports scope operation: You can specify the start and end index.

Applicable scenarios

  • Initialize an all-zero array (replace loop assignment).
  • Reset the cache or configure the array.

5. Multidimensional array: structured data container

Code Example

// Static initializationint[][] matrix1 = {
    {1, 2, 3},
    {4, 5, 6}
};

// Dynamic initialization (jagged array)int[][] matrix2 = new int[2][]; 
matrix2[0] = new int[3]; // First row 3 columnsmatrix2[1] = new int[5]; // Second row 5 columns

Core features

  • Array of arrays: Each dimension is initialized independently.
  • Supports unequal eldest child arrays(i.e. "Serrated Array").

Things to note

  • Null pointer risk: The uninitialized subarray isnull
  • Memory overhead: Multidimensional arrays may take up more memory.

Comparative summary: How to choose the initialization method?

Way advantage shortcoming Typical scenarios
Static initialization Concise code and type-safe Fixed length Configuration items, enumeration values
Dynamic initialization Flexible control of memory and assignment logic Default values ​​need to be managed manually File reading, dynamic data generation
Anonymous array Avoid redundant variables Cannot be reused Temporary method parameters
Tool class fill Efficient batch operation Only single value is supported Initialize the default value or reset the array
Multidimensional array Structured storage Complex initialization, easy to leak memory Matrix operations, tabular data

Four core points to note

  1. Immutable length
    The length of the Java array is fixed after initialization. To expand the capacity, you need to create a new array and copy the data (you can use the help ofor)。

  2. Default value trap

boolean[] flags = new boolean[3];
(flags[0]); // Output false (default value)
  • When the object array is not explicitly initialized, the element isnull, direct operation may causeNullPointerException

  • Visit across the border
    Always check index ranges to avoidArrayIndexOutOfBoundsException. It is recommended to use an enhanced for loop:

for (int num : arr) { 
    (num);
}
  • Multidimensional array initialization order
    The outer layer array must be initialized first, and then the inner layer array one by one:
int[][] arr = new int[3][]; 
arr[0] = new int[2]; // Must be explicitly initialized

Best Practices

  • Small-scale data: Prioritize static initialization to improve readability.
  • Large-scale data: Dynamic initialization combined with tool-like methods (such asgenerate sequence).
  • High frequency access scenarios: Preallocate enough memory to avoid frequent expansion.
  • High safety requirements:useWrap array (need to be converted to List).

By rationally choosing the initialization method, you can write more efficient and easier to maintain Java code. It is recommended to flexibly combine different methods according to actual needs, and pay attention to JVM memory management and performance tuning.

This is the end of this article about five ways to initialize Java arrays. For more related Java arrays, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!