Home > Java > JavaBase > How to define array in java?

How to define array in java?

Release: 2019-11-20 14:27:31
Original
19543 people have browsed it

How to define array in java?

Array definition method one

Dynamic method (specify the length of the array)

Format:

Data type stored in the array [] Array name = new Data type stored in the array [length];

[]: Represents an array.

Array name: Give the defined array a variable name that meets the identifier specification. You can use the name to operate the array.

new: keyword, keyword used to create an array.

Data type stored in the array: See what data type the created array is used to store.

[Length]: The length of the array, indicating how many elements can be stored in the array container.

Example:

Define an array container that can store 3 integers. The code is as follows:

int[] arr = new int[3];
Copy after login

Array definition method two

Static mode (specify the elements of the array)

Format:

Data type [] Array name = new data type []{Element 1, Element 2, Element 3...};

Define an array container that stores integers 1, 2, 3, 4, and 5.

int[] arr = new int[]{1,2,3,4,5};
Copy after login

Or omit the format: (You cannot declare first and then assign a value, you can only declare and assign a value at the same time)

Data type [] Array name = {Element 1, Element 2, Element 3... };

Define an array container that stores integers 1, 2, 3, 4, and 5.

int[] arr = {1,2,3,4,5};
Copy after login

Note:

1. If you use the static method to create an array, the system will automatically calculate the length of the array based on the number of elements

2. Create the right side of the array statically The length cannot be written in the square brackets

3. When creating an array in the static omitted format, you cannot declare it first and then assign it. You can only declare it and assign it directly at the same time.

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

The above is the detailed content of How to define array in java?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template