Home> Java> JavaBase> body text

How to assign value to java array

Release: 2019-11-22 16:21:38
Original
19232 people have browsed it

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];
Copy after login

Example:

int[] number = new int[5]; number[0] = 1; number[1] = 2; number[2] = 3; number[3] = 5; number[4] = 8;
Copy after login

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};
Copy after login

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};
Copy after login

For more java knowledge, please pay attention tojava 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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!