Home >Java >javaTutorial >How to use foreach statement in Java to traverse all elements
The foreach statement is one of the new features of the Java5 version. It is designed to provide programmers with great convenience when traversing arrays and collections. However, the foreach statement cannot completely replace the for loop. statement.
System.out.println("(foreach)学生信息:"); for (Object obj:students) { Student s=(Student) obj; System.out.println("编号:" + s.ID + "\t\t\t姓名:" + s.name + "\t\t\t年龄:" + s.age + "\t\t\t性别:" + s.gender); } }
From the code point of view, the foreach statement is obviously much simpler and clearer than the for loop statement. There is no need to define an initial value, no need to determine the judgment range, and no need to increment or decrement. But these do not mean that the foreach statement can replace the for loop statement. Obviously, what foreach can do, for loop can do; what for loop can do, foreach may not be able to do.
The above is the detailed content of How to use foreach statement in Java to traverse all elements. For more information, please follow other related articles on the PHP Chinese website!