How can an array of any length be defined in Java?

In Java, you can define arrays of any length using dynamic or static initialization.

Initialize dynamically.

int[] arr = new int[n]; // n为数组的长度

This method first defines the length of the array, then creates an array object based on that length.

Static initialization:

int[] arr = {1, 2, 3, 4}; // 直接初始化数组元素

This method directly initializes the elements of the array when defining the array, and the length of the array will be determined by the number of initialized elements.

bannerAds