1. Definition of the array:
The first type:
public class arraydemo{
public static void Main (string[] args) {
Defining arrays
int [] arr = new INT[3];
The default value for an element in an array is 0
System.out.println (Arr[0]);
System.out.println (arr.length);
}
}
The length here is the size of the array
The second method of definition:
public class arraydemo{
public static void Main (string[] args) {
Define the array, note that the brackets behind the new cannot write numbers
int [] arr = new int[]{1,2,4,3,6,5};
System.out.println (Arr[4]);
System.out.println (arr.length);
}
}
The third type (most commonly used):
public class arraydemo{
public static void Main (string[] args) {
int [] arr = {1,2,4,3,6,5};
System.out.println (Arr[4]);
System.out.println (arr.length);
}
}
The two results are the same, as follows:
2. Assigning values to arrays:
ARR[1] = 3
3. Traverse
public class arraydemo{
public static void Main (string[] args) {
int [] arr = {2,1,3,5,7,0,4};
for (int i = 0; i < arr.length; i++) {
System.out.println (Arr[i]);
}
}
}
Results:
4. Get maximum value (the minimum principle is the same):
public class arraydemo{
public static void Main (string[] args) {
int [] arr = {5,-1,2,-4,6,0,8,3};
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (Max < arr[i]) {
max = Arr[i];
}
}
SYSTEM.OUT.PRINTLN (max);
}
}
5. Two-dimensional array:
Defined:
int [] arr = new int [3][4];
int [] arr = {{1,2},{3,4,5},{6,7,8,9}};
Memory method: Three one-dimensional arrays in the heap, each one-dimensional array has four positions, three one-dimensional array of the first address into a new array, the new array also has the first address, the stack of arr points to this address
Two-dimensional array access is similar to a one-dimensional array
Traverse:
public class arraydemo{
public static void Main (string[] args) {
int [] arr = {{1,2,3},{4,5},{6,7,8,9},{0}};
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j<arr[i].length; j + +) {
System.out.print (Arr[i][j]);
}
System.out.println ();
}
}
}
Java Learning Note 3 (array)