Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

For-Each Loop in Java [With Coding Examples]

Updated on 03 July, 2023

7.31K+ views
8 min read

Every programming language uses loops to execute the same block of code iteratively. Java has different types of loop statements, viz. for loop, while loop, do-while loop. Another kind of loop introduced in the Java 5.0 version is the for-each loop, also called enhanced for loop.

It uses the same keyword ‘for’ as in for loop to iterate in collecting items, such as an array. In a for-each loop, there is no need to initialize the loop counter variable. Instead, a variable is declared along with the array name. To get more understanding of its usage, check the syntax of the for-each loop in Java.

Check out our free courses to get an edge over the competition

Everything You Need to Know About the For-Each Loop in Java

The for each loop in Java is also called the enhanced for loop. It has been in operation since JS2E 5.0. The for-each loop ensures that you have an alternative approach toward traversing a collection or array in Java. The name for-each loop stems from its ability to traverse elements one after the other.

The for-each loop is crucial for eliminating bugs and making code more readable. But unfortunately, you cannot skip elements or traverse them in reverse order while using the for-each loop. Additionally, you cannot use the for-each loop for traversing only the odd or even elements. 

Syntax of For-Each Loop in Java

for(data_type variable_name : array_name) {
           Statements;
}

Here, data_type is the data type of the variable declared with the name variable_name. array_name is the array in which the variable will iterate to execute the statements inside the loop block.

Check out upGrad’s Advanced Certification in Blockchain

How Does For-Each Loop Work?

For-each loop in Java works like any other loop. The loop traverses for each element of the array till last. The value of the array element is stored in the variable declared with the loop, and execution of the statement occurs for each iteration.

Read: Java Developer Salary in India

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

Features of the For-Each Loop

Some common characteristics of the for-each loop in Java are as follows:

  • The first keyword in the for-each loop is “for,” similar to a regular for loop. 
  • While using the for-each loop, you don’t declare and initialize a loop counter variable. Instead, you will have to declare a variable similar to the base type of the array. It is then succeeded by a colon and the array name. 
  • In the loop body, you are not required to use the indexed array element. Instead, you will be able to leverage the loop variable you made. 
  • The for-each loop in Java is used for iterating over an array or a Collections class like an ArrayList. 

Examples of the For-Each Loop in Java

Example 1: Consider the below example that adds the elements of the array and prints the result.

Class Example1 {
Public static void main(String args[]) {
int count[] = {1, 3, 5, 7, 9};
int sum=0;
for(int var : count) {
                            sum = sum + var;
}
System.out.println(“Sum of the array elements “ + sum);
}
}

Check out upGrad’s Advanced Certification in DevOps 

Output: Sum of the array elements 25

Explanation: In the above program, for each iteration, the array element gets assigned to var and gets added to the variable called sum.

For the first iteration, var = 1, and the sum, which was initially 0, gets added to var, i.e., 1. Therefore, the sum becomes 1 after the first iteration.

For second iteration, var = 3 and sum = sum + var = 1 + 3 = 4

For the third iteration, var = 5 and sum = 4 + 5 = 9.

In this way, the sum gets updated after each iteration and gives the sum of all elements of the array.

Example 2: The below code snippet prints the elements of the string collection.

Class Example2 {
Public static void main(String args[]) {
String firstName[] = {“Peter”, “John”, “Mary”};
for(int name : firstName) {
                            System.out.println(“Name is “ + name);
}
}
}

Output:

Peter
John
Mary

Explanation: In this example, the variable declared as the name takes the value of firstName from the collection of strings and prints it.

How is the For-Each Loop Different from For Loop?

If we write the above code using for loop, it will be as below:

Class Example1 {
Public static void main(String args[]) {
int count[] = {1, 3, 5, 7, 9};
int sum=0;
for(int var=0; var < count.length; var++) {
                            sum = sum + var;
}
System.out.println(“Sum of the array elements “ + sum);
}
}

By comparing the code of for loop and for-each loop, it is clear that it is easy to write the code using the for-each loop. There is no need to initialize the counter variable and increment or decrement in the for-each loop as the loop automatically moves to the next element in the array.

Understanding the Difference Between For Loop and For-Each Loop from the Same Example 

Suppose you want the following output:

a
e
i
o
u

Now, let us glance at the code using the for loop to get this outcome:

class Main {
 public static void main(String[] args) {
   char[] vowels = {'a', 'e', 'i', 'o', 'u'};
   // iterating through an array using a for loop
   for (int i = 0; i < vowels.length; ++ i) {
     System.out.println(vowels[i]);
   }
 }
}

Now, let us look at a Java for-each loop example for the same outcome:

class Main {
 public static void main(String[] args) {
   char[] vowels = {'a', 'e', 'i', 'o', 'u'};
   // iterating through an array using the for-each loop
   for (char item: vowels) {
     System.out.println(item);
   }
 }
}

By looking carefully at the two codes, you will understand that the for-each loop makes it easy to read and write. That’s why the for-each loop gets preferred over the for loop.

Advantages of For-Each Loop in Java

  • The use of the for-each loop is easy and makes the code readable.
  • The for-each loop does not use the index of the array to traverse in the loop.
  • This loop reduces the chance of programming error.
  • The for-each loop works faster than the for loop.

Disadvantages of For-Each Loop in Java

There are certain disadvantages of using the for-each loop as discussed below:

  • It is impossible to traverse in the reverse order in the for-each loop as is done in for loop or while by decrementing the counter variable.
  • There is no way to skip the array element while using the for-each loop.
  • It is impossible to refer to the odd or even elements in the array as possible in for loop where the counter variable can be incremented or decremented by two or even more.

Checkout: Java Project Ideas & Topics

Limitations of the For-Each Loop

A few limitations of the for-each loop in Java are as follows:

  • They are not useful for modifying the array.
  • The for-each loop cannot be used for obtaining the array index because they don’t keep track of the index.
  • They are useful for iterating forward over the array only in single steps. 
  • The for-each loop cannot be used for processing two decision-making statements at once. 
  • It will show some performance overhead even over a simple iteration.

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Conclusion

The use of the for-each loop in Java makes the code more readable and easy to understand. Therefore, it is recommended to use the for-each loop instead of for loop. However, it has the disadvantage that elements cannot be traversed in reverse order or cannot skip the array elements. But the use of ‘break’ and ‘continue’ can let the coders modify the code as per the need. Java is a popular language for software development. You can learn software development from upGrad by applying for Masters in Computer Science.

If you’re interested to learn more about PHP, Full-stack software development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Frequently Asked Questions (FAQs)

1. What are loops in programming?

A loop is a way to repeat one or more lines of code a specified number of times. This is extremely useful when you have instructions that you want to repeat over and over. Without loops, you would have to write every step of the instructions every time that you run the program. Breaking a program down into smaller pieces allows you to focus on each piece separately. The code inside the loop will be executed a number of times equal to the number of times the loop iterates. The loop will execute line by line and once the loop iterates for the last time, the program will continue with the next statement after the loop.

2. What are the different types of loops in Java?

There are several types of loops in Java. The first one and probably, the most frequently used loop is the for loop. In case of a for loop, you define a structure such as for (int i = 0; i <= 20; i++) {}. Here, the statements inside the curly braces will be executed 21 times. This means that as long as the value of i starting from 0 is less than or equal to 20, the statements will get executed provided it does not encounter a break statement. The next loop is the while loop. The while loop will continue to execute until it satisfies the condition mentioned or if it encounters a break statement in which case it will come out of the loop. Another version of the while loop is the do while loop. The difference is that the do while loop executes at least once because the condition is specified at the end of the curly braces. Yet another type of loop is the foreach loop which is a simplified version of the for loop. This loop allows you to traverse an array and loop through each element of it.

3. What are the uses of loops in programming?

Loops are a fundamental programming construct that allow us to do repetitive tasks. The use of loops is probably the most common in a standard computer application. Loops are used for tasks such as reading and writing files or arrays, searching or sorting through items or data, and many other common tasks.

RELATED PROGRAMS