When manipulating arrays, it is often necessary to sequentially access each element in the array, which is called an array traversal
1 Public classArrayDemo04 {2 Public Static voidMain (string[] args) {3 int[] arr = {1, 2, 3, 4, 5};//Defining Arrays4 //iterating through the elements of an array using a For loop5 for(inti = 0; i < arr.length; i++) {6System.out.println (Arr[i]);//accessing elements by index7 }8 }9}
FAQ for Arrays
The traversal of an array, the acquisition of a maximum value, the ordering of an array
Array Maximum Value
When manipulating arrays, it is often necessary to get the maximum value of the elements in the array
Cases:
1 Public classArrayDemo05 {2 Public Static voidMain (string[] args) {3 int[] arr = {4, 1, 6, 3, 9, 8};//define an array4 intmax = arr[0];//define variables Max is used to remember the maximum number, first of all assuming the first element is the maximum value5 //the following iterates through the elements in the array through a for loop6 for(intx = 1; x < arr.length; X + +) {7 if(Arr[x] > Max) {//Compare Arr[x] value is greater than Max8max = arr[x];//conditional, assign the value of Arr[x] to Max9 }Ten } OneSystem.out.println ("max=" + max);//Print Maximum value A } - } -Result: The maximum value is 9
Array exception array out of bounds exception
when accessing the elements of an array, the index cannot exceed this Array of range, or the program will error
Null pointer exception
When you use a variable to reference an array, the variable must point to a valid array object, and if the value of the variable is null, it means that there is no pointer to any array, at which point a null pointer exception appears for the element accessing the array through that variable .
Cases:
1 Public classArrayDemo07 {2 Public Static voidMain (string[] args) {3 int[] arr =New int[3];//defines an array of length 34Arr[0] = 5;//assign a value to the first element of an array5System.out.println ("arr[0]=" + arr[0]);//accessing elements of an array6arr =NULL;//Set Variable arr to null7System.out.println ("arr[0]=" + arr[0]);//accessing elements of an array8 }9 }TenResults: Arr[0] =5; One........ Abnormal
Traversal exceptions for Java arrays