Java Array Declaration Without Initialization

In Java, you can define an uninitialized array as follows:

// 定义一个整数数组
int[] myArray;

// 定义一个字符串数组
String[] myArray2;

// 定义一个自定义对象数组
MyObject[] myArray3;

Please note, this only defines an array variable without allocating memory space for it, so the array variable remains null. If you need to allocate memory space for the array, you can use the new keyword to create an array object.

// 创建一个长度为10的整数数组
myArray = new int[10];

// 创建一个长度为5的字符串数组
myArray2 = new String[5];

// 创建一个长度为3的自定义对象数组
myArray3 = new MyObject[3];

When defining arrays, values can also be assigned directly.

// 定义并初始化整数数组
int[] myArray4 = {1, 2, 3, 4, 5};

// 定义并初始化字符串数组
String[] myArray5 = {"Hello", "World"};

// 定义并初始化自定义对象数组
MyObject[] myArray6 = {new MyObject(), new MyObject()};

It is important to note that the length of an array cannot be changed. Once the length of an array is defined, it cannot be altered.

bannerAds