Home > Java > javaTutorial > How to use arrays

How to use arrays

(*-*)浩
Release: 2020-09-16 10:02:59
Original
5884 people have browsed it

How to use arrays

There are two syntaxes for defining arrays in Java:

type arrayName[];

type[] arrayName;

  • type is any data type in Java, including basic types and combined types

  • arrayName is the array name and must be a legal identifier

  • [ ] indicates that the variable is an array type variable

For example:

int demoArray[];

int[] demoArray;

There is no difference between these two forms, and the usage effect is exactly the same. Readers can use it according to their own Programming habits selection.

Unlike C and C, 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 [ ].

And for an array defined above, we cannot access any of its elements. We must allocate memory space for it. In this case, we need to use 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

Related learning recommendations: java basic tutorial

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