Home> Java> javaTutorial> body text

How to use foreach statement in Java to traverse all elements

王林
Release: 2023-05-04 09:43:06
forward
1157 people have browsed it

foreach statement

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); } }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!