Arrays: The same type, encapsulated together with an identifier name, is an object sequence or a sequence of basic types of data.
Statement of one-dimensional array: 1 int[] A1; 2 int a1[]
Two formats are the same, the second is in line with C and C + + programmers ' habits. The first might be more reasonable, indicating that the type is "an int array".
The compiler does not allow the size of the array to be specified. Cannot specify its length (number of elements) such as int a[5] when declaring an array; Illegal. The size can be specified when initializing.
Arrays in Java must be initialized before they can be used. Initialization is allocating memory for array elements of arrays and assigning values to each array element; it is now just a reference to the array (the storage space has been allocated for that reference), and no space is allocated to the object itself, and initialization creates the appropriate storage space.
Two ways to initialize:
Static initialization: When initializing, we specify the initial value of each array element by ourselves, and the system determines the length of the array required;
Format: Array name = new array type []{element 1, Element 2, Element 3 ... Element n}; A1 = new int{1,2,3,4,5};
Simplified Syntax: array name = {element 1, element 2, Element 3 ... Element n}; A1 = {1,2,3,4,5};
Dynamic initialization: We specify the length of the array when initialized, and the initial value is allocated by the system array element;
Format: Array name = new array type [array length]; A1 = new int[8];
Note: You cannot use both static and dynamic initialization, that is, you cannot specify the length and elements of an array at the same time; Once the length of the array is determined, it cannot be changed, and the array is fixed-length;
All arrays have an intrinsic member, length, to get the number of array members by the array name. length. The Java array subscript starts at 0, and the largest subscript is the array name. Length-1. Beyond this boundary, an exception array is marked with a foot-bounds exception (arrayindexoutofboundsexception).
Memory Analysis:
Example:
public class arrayinit{public
static void Main (string[] args) {
int[] A1 ={1,2,3,4,5};
int[] A2;
A2 =a1;
for (int i =0;i<a2.length;i++)
a2[i]=a2[i]+1;
for (int i =0;i<a1.length;i++)
System.out.println ("a1[" + i + "] =" + a1[i]);
}
Output:
a1[0]=2
a1[1]=3
a1[2]=4
a1[3]=5
a1[4]=6
The initial value of the A1 is given, but the A2 is assigned to the A1 array and the two arrays point to the same heap address, so the value of the A2 array changes and the A1 changes accordingly.