Home >Java >JavaBase >How to assign value to java array

How to assign value to java array

尚
Original
2019-11-22 16:21:3819325browse

How to assign value to java array

Arrays in 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 array size and then initialize it

Use the new keyword to create an array. Specify the size of the array when creating it. 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 initializing the array using the above method, The value is determined only when the element is assigned a value. You can not use the above method, but determine the value during initialization. The syntax is as follows:

type[] arrayName = new type[]{值 1,值 2,值 3,值 4,• • •,值 n};

3) Directly specify the value of the array element

In the syntax of the above two methods, type can be omitted. If the array variable has been declared, then Use these two methods directly for initialization. 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 = {值 1,值 2,值 3,...,值 n};

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

The above is the detailed content of How to assign value to java array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn