1. A for loop to traverse an
array is a very common method to traverse an array with a for loop. The length of the array can be obtained through the length property of the array in the Java language.
package demo;
public class test {
public static void main(String[] args) {
int [] array = {
1,2,3,4,5};
for(int i = 0;i < array.length;i++) {
System.out.print(array[i] + " ");
}
}
}
2. Traversal based on loop statement
JDK1.5 expands and enhances the function of for statement to facilitate better traversal of arrays;
syntax format:
for(声明循环变量:数组的名字){
//注意:这里的“声明循环变量”一定是声明变量,不可以使用已经被声明的变量
....
}
example:
package demo;
public class test {
public static void main(String[] args) {
int [] array = {
1,2,3,4,5};
for(int in:array) {
System.out.print(in + " ");
}
}
}
3. Use the toString() method to traverse the array.
This method is a simple way to output the value of an array element provided by JDK1.5. Use the Arrays class to call the public static String toString(int[] a) method to get the string representation of the specified one-dimensional array a in the following format.
[a[0],a[1]…a[a.lenth-1]]
package demo;
import java.util.Arrays;
public class test {
public static void main(String[] args) {
int [] array = {
1,2,3,4,5};
System.out.print(Arrays.toString(array));
}
}