Java array definition and use

array

Array concept
An array is a container that stores data with a fixed length, ensuring that the data types of multiple data must be consistent.

Array initialization
There are two common ways to initialize arrays:

Dynamic initialization (specified length)
Static initialization (specified content)
Method 1: Dynamic initialization

Format:
data type of array storage [] array name = new data type of array storage [array length];
data type of array storage array name [] = new data type of array storage [array length];

Detailed explanation of the array definition format:
the data type stored in the array: what data type can be stored in the created array container.

[] : Indicates an array.

Array name: Give a variable name to the defined array, satisfy the identifier specification, and use the name to operate the array.

new: keyword, the keyword used to create an array.

Data type of array storage: What data type can be stored in the created array container.

Length: The length of the array, indicating how many elements can be stored in the array container.

Note: The array has a fixed-length feature, once the length is specified, it cannot be changed.
Example: Define an array that can store 3 integers

int[] arr = new int[3];
int arr[] = new int[3];
// can split
int[] arr;
arr = new int[3];

Method 2: Static initialization

Format: data type [] array name = new data type [] {element 1, element 2, element 3...};

Example: Define an array container for storing 1, 2, 3, 4, 5 integers.

int[] arr = new int[]{1,2,3,4,5};
// can split
int[] arr;
arr = new int[]{1,2,3,4,5};

Method 3: Static initialization omits the format (cannot be split)

Format: data type [] array name = {element 1, element 2, element 3...};

Example: define an array container for storing integers 1, 2, 3, 4, 5 int[] arr = {1,2,3,4,5};

Guess you like

Origin blog.csdn.net/weixin_52340450/article/details/125754086