Java for-each loop

 Java for-each loop

Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-each loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is given below.

  1. for(data_type var : array_name/collection_name){    
  2. //statements    
  3. }    

Consider the following example to understand the functioning of the for-each loop in Java.

ForEachTest.java

  1. public class ForEachTest{    
  2. public static void main(String[] args) {    
  3. String[] names = {"Rahul","Nirmal","Siva","Deepak","Rani"};    
  4. System.out.println("Printing the content of the array names:\n");    
  5. for(String name:names) {    
  6. System.out.println(name);    
  7. }    
  8. }    
  9. }    

Output:

Printing the content of the array names:

Rahul
Nirmal
Siva
Deepak
Rani


Comments

Popular Topics

What is JSP. How to create one JSP application in Eclipse

How to develop a RESTful webservice in java ?

Data Types in PL/SQL

What is JDBC ?

What is Hibernate in java ?

If you have any query or suggestions, Please feel free to write us

Name

Email *

Message *