Java Study Notes 3 (array), java Study Notes 3 Array
1. array definition:
First:
Public class ArrayDemo {
Public static void main (String [] args ){
// Define an array
Int [] arr = new int [3];
// The default value of the element in the array is 0.
System. out. println (arr [0]);
System. out. println (arr. length );
}
}
Here the length is the length of the array.
Method 2:
Public class ArrayDemo {
Public static void main (String [] args ){
// Define an array. Note that numbers cannot be written in brackets behind new.
Int [] arr = new int [] {1, 2, 4, 3, 6, 5 };
System. out. println (arr [4]);
System. out. println (arr. length );
}
}
Third (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 shown below:
2. array assignment:
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]);
}
}
}
Result:
4. obtain the maximum value (the principle of the minimum value is the same ):
Public class ArrayDemo {
Public static void main (String [] args ){
Int [] arr = {5,-,-, 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:
Definition:
Int [] [] arr = new int [3] [4];
Int [] [] arr = {1, 2}, {3, 4, 5}, {6, 7, 8, 9 }};
Memory method: three one-dimensional arrays are stored in the heap. Each one-dimensional array has four locations. The first address of the three one-dimensional arrays is stored in a new array. The new array also has the first address, the arr in the stack points to this address.
Two-dimensional array access is similar to one-dimensional array access.
Traversal:
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 ();
}
}
}