Definition and use of Java arrays

Source: Internet
Author: User
Tags array length

If you want to save a set of data with the same type, you can use an array.

Definition of arrays and memory allocation

There are two types of syntax for defining arrays in Java:

Type arrayname[];

Type[] Arrayname;

Type is any data type in Java, including the base type and combination type, Arrayname is an array name and must be a valid identifier, [] indicating that the variable is a variable of type. For example:

1. int demoarray[];

2. int[] Demoarray;

There is no difference between the two forms, the use of the same effect, readers can choose according to their own programming habits.

Unlike C and C + +, Java does not allocate memory for array elements when defining arrays, so there is no need to specify the number of array elements, that is, the array length. And for an array defined above that cannot access any of its elements, we have to allocate memory space for it, and the operator new is used in the following format:

Arrayname=new Type[arraysize];

Where arraySize is the length of the array, the type of the array. Such as:

Copy Plain Text New window

1. Demoarray=new int[3];

Allocates a memory space occupied by 3 int integers for an integer array.

Typically, you can allocate space at the same time as you define, with the syntax:

Type arrayname[] = new Type[arraysize];

For example:

1. int demoarray[] = new INT[3];

Initialization of the array

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

1.//Static initialization

2.//static initialization while allocating space and assigning values to an array element

3. int intarray[] = {1,2,3,4};

4. String stringarray[] = {"Micro school", "Http://www.weixueyuan.net", "all programming languages are paper tigers"};

5.

6.//Dynamic initialization

7. Float floatarray[] = new FLOAT[3];

8. floatarray[0] = 1.0f;

9. floatarray[1] = 132.63f;

Ten. Floatarray[2] = 100F;

Array reference

You can refer to an array by subscript:

Arrayname[index];

Unlike C, C + +, Java array elements are checked for cross-border checks to ensure security.

Each array has a length property to indicate its lengths, for example intarray.length indicates the length of the array intarray.

"Example" writes a piece of code that requires the input of any 5 integers and outputs their and.

1. Import java.util.*;

2. public class Demo {

3. public static void Main (string[] args) {

4. int intarray[] = new INT[5];

5. Long total = 0;

6. int len = intarray.length;

7.

8.//Assigning values to array elements

9. System.out.print ("Please enter" + len + "integer, separated by a space:");

Scanner sc = new Scanner (system.in);

One. for (int i=0; i<len; p= "" i++) {<= "" >

Intarray = Sc.nextint ();

13.}

14.

15.//Calculate the and of the array elements

. for (int i=0; i<len; p= "" i++) {<= "" >

Total + = Intarray;

18.}

19.

System.out.println ("The and of all array elements is:" + total);

21.}

22.}

Operation Result:

Please enter 5 integers, separated by a space: 10 20 15 25 50

The and of all array elements are: 120

Traversal of an array

In real-world development, it is often necessary to iterate through an array to get each element in the array. The easiest way to think of is a for loop, for example:

1. int arraydemo[] = {1, 2, 4, 7, 9, 192, 100};

2. for (int i=0,len=arraydemo.length; i<len; p= "" i++) {<= "" >

3. SYSTEM.OUT.PRINTLN (Arraydemo + ",");

4.}

Output Result:

1, 2, 4, 7, 9, 192, 100,

However, Java provides an "enhanced" for loop that is designed to iterate through an array with the following syntax:

1. for (arraytype varname:arrayname) {

2.//Some Code

3.}

ArrayType is an array type (which is also the type of the element); VarName is the variable that holds the current element, and the value of each loop changes; Arrayname is an array name.

Once per loop, the value of the next element in the array is taken and saved to the VarName variable until the end of the array. That is, the value of the first loop varName is the No. 0 element, the second loop is the 1th element ... For example:

1. int arraydemo[] = {1, 2, 4, 7, 9, 192, 100};

2. for (int x:arraydemo) {

3. SYSTEM.OUT.PRINTLN (x + ",");

4.}

The output is the same as above.

This enhanced for loop is also known as the Foreach Loop, which is a special simplified version of the normal for loop statement. All foreach loops can be rewritten as a for loop.

However, if you want to use the index of an array, then the enhanced for loop cannot.

Two-dimensional arrays

Declaring, initializing, and referencing a two-dimensional array is similar to a one-dimensional array:

1. int intarray[[] = {{"}, {2,3}, {4,5}};

2. int a[] [] = new INT[2][3];

3. a[0][0] = 12;

4. a[0][1] = 34;

5.//...

6. a[1][2] = 93;

In the Java language, because the two-dimensional array is considered an array of arrays, the array space is not continuously allocated, so the size of each dimension of the two-dimensional array is not required. For example:

1. int intarray[[] = {{"}, {2,3}, {3,4,5}};

2. int a[] [] = new int[2][];

3. a[0] = new INT[3];

4. a[1] = new INT[5];

The example calculates the product of two matrices through a two-dimensional array.

1. public class Demo {

2. public static void Main (string[] args) {

3.//First matrix (dynamic initialization of a two-dimensional array)

4. int a[][] = new INT[2][3];

5.//second matrix (static initialization of a two-dimensional array)

6. int b[][] = {{1,5,2,8}, {5,9,10,-3}, {2,7,-5,-18}};

7.//Result Matrix

8. int c[][] = new INT[2][4];

9.

10.//Initialize First matrix

One. for (int i=0; i<2; i++)

for (int j=0; j<3; j + +)

A[J] = (i+1) * (j+2);

14.

15.//Compute Matrix PRODUCT

. for (int i=0; i<2; i++) {

. for (int j=0; j<4; J + +) {

c[j]=0;

. for (int k=0; k<3; k++)

C[J] + = a[k] * B[k][j];

21.}

22.}

23.

24.//Output settlement result

for (int i=0; i<2; i++) {

. for (int j=0; j<4; j + +)

System.out.printf ("%-5d", C[j]);

System.out.println ();

29.}

30.}

31.}

Operation Result:

25 65 14-65

50 130 28-130

A few notes:

· The above is a static array. Once a static array is declared, its capacity is fixed and cannot be changed. So when declaring an array, be sure to consider the maximum capacity of the array to prevent the lack of capacity.

· If you want to change the capacity when you run the program, you need to use the array list (ArrayList, also known as a dynamic array) or vector (vectors).

· It is due to the shortcomings of static array capacity fixed, the actual development of the use of frequency is not high, by ArrayList or Vector substitution, because the actual development often need to add or remove elements to the array, and its capacity is not good estimate. (Edit: Lelinpeng Source: Network)

Definition and use of Java arrays

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.