How to assign values to java arrays _how to assign values to java arrays

ca6af356cf9aee41ee6e2e8126442586.png

Arrays in the Java language must be initialized before they can be used. The so-called initialization is to allocate memory space for the array elements of the array, and assign an initial value to each array element.

There are three ways to initialize an array:

1) Use new to specify the size of the array and initialize it

Arrays are created using the new keyword, specifying the size of the array at creation time. The syntax is as follows: type[] arrayName = new int[size];

Example: int[] number = new int[5];

number[0] = 1;

number[1] = 2;

number[2] = 3;

number[3] = 5;

number[4] = 8;

2) Use new to specify the value of the array element

When an array is initialized in the above manner, the value is only determined when an element is assigned a value. Instead of using the above method, the value has been determined during initialization. The syntax is as follows: type[] arrayName = new type[]{value1,value2,value3,value4,•••,valuen};

3) Directly specify the value of the array element

In the syntax of the above two methods, type can be omitted. If an array variable has been declared, then use these two methods to initialize directly. If you don't want to use the above two methods, you can directly specify the value of the array element without using new. The syntax is as follows: type[] arrayName = {value1,value2,value3,...,valuen};

For more java knowledge, please pay attention to the java basic tutorial.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324121185&siteId=291194637