Home > Java > javaTutorial > How to define java integer array

How to define java integer array

(*-*)浩
Release: 2020-09-18 10:13:44
Original
12802 people have browsed it

How to define java integer array

There are two syntaxes for defining arrays in Java:

type arrayName[];
type[] arrayName;
Copy after login

type is any data type in Java, including basic types and combined types, arrayName is the array name, [must be a legal identifier, [] indicates that the variable is an array type variable. For example:

int demoArray[];
int[] demoArray;
Copy after login

There is no difference between these two forms, and the usage effect is exactly the same. Readers can choose according to their own programming habits.

Java does not allocate memory for array elements when defining an array, so there is no need to specify the number of array elements, that is, the array length, in [ ]. Moreover, for an array defined above, we cannot access any of its elements. We must allocate memory space for it. At this time, we need to use the operator new, The format is as follows:

arrayName=new type[arraySize];
Copy after login

Among them, arraySize is the length of the array, and type is the type of the array.

For example:

demoArray=new int[3];
Copy after login

Allocate the memory space occupied by 3 int-type integers for an integer array.

Usually, you can allocate space while defining, the syntax is:

type arrayName[] = new type[arraySize];
Copy after login

For example:

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

Initialization of arrays

You can initialize the array while declaring it (static initialization), or you can initialize it after the declaration (dynamic initialization). For example:

// 静态初始化
// 静态初始化的同时就为数组元素分配空间并赋值
int intArray[] = {1,2,3,4};
String stringArray[] = {"Java", "http://www.java.com", "一切编程语言都是纸老虎"};
// 动态初始化
float floatArray[] = new float[3];
floatArray[0] = 1.0f;
floatArray[1] = 132.63f;
floatArray[2] = 100F;
Copy after login

Related learning recommendations: java basic tutorial

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