Home> Java> JavaBase> body text

How to initialize arrays in Java

王林
Release: 2019-11-12 11:17:05
Original
5388 people have browsed it

How to initialize arrays in Java

Array initialization method:

1. Static initialization

Explicitly specify the initial value of each array element during initialization , the length of the array is determined by the system.

Format:

arrayName = new type[]{element1,element2,element3...}
Copy after login

Example:

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

2. Simplified static initialization method

Format:

type[] arrayName = {element1,element2,element3...};
Copy after login

Example:

String[] strArr = {"张三","李四","王二麻"};
Copy after login

3. Dynamic initialization

During initialization, the programmer specifies the length of the array, and the system initializes the default value of each array element.

Format:

arrayName = new type[length];
Copy after login

Example:

int[] price = new int[4];
Copy after login

Note: Do not use static initialization and dynamic initialization at the same time, that is, do not perform array initialization , not only specifies the length of the array, but also assigns an initial value to each array element. Once the array is initialized, the space occupied by the array in memory will be fixed, so the length of the array cannot be changed.

Recommended tutorial:Java tutorial

The above is the detailed content of How to initialize arrays 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