Home  >  Article  >  Java  >  How to initialize an array in java

How to initialize an array in java

angryTom
angryTomOriginal
2019-11-11 14:13:096066browse

How to initialize an array in java

How to initialize an array in java

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

Note: After the array is initialized, there is a default value for each element of the array in the memory space:

Integertype of the basic data type (byte, short, int, long) the default value is 0;

Floating point type (float, double) of the basic data type (float, double) the default value is 0.0;

Basic The character type (char) of the data type has a default value of '\u0000'; the

basic data type of the Boolean type (boolean) has a default value of false ;

## type reference

type (class, array, interface, String) default value is null. (Recommended tutorial: java tutorial)

Initialization method:

1.

Static initialization: The programmer explicitly specifies the initial value of each array element during initialization. , there is a system to determine the length of the array; 1.arrayName = new type[]{element1,element2,element3...}

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

2. Simplified static initialization method type[] arrayName = {element1,element2,element3...};

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

2. Dynamic initialization

: During initialization, the programmer specifies the length of the array, and the system initializes the default value of each array element. . arrayName = new type[length];

Example:

int[] price = new int[4];

Note: Do not use static initialization and dynamic initialization at the same time, that is, do not use it when initializing an array , which both specifies the length of the array and 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.

The above is the detailed content of How to initialize an array in java. 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