BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Difference between for loop and for-each loop in Java

Last Updated: June 2, 2024 by Chaitanya Singh | Filed Under: java

In Java, both for loop and for-each loop are used for iterating over arrays or collections, however they have different syntax and their usage is also different. In this guide, we will discuss the difference between for loop and for-each loop with the help of examples. I have covered these loops separately here: for loop and for-each loop.

for Loop

Syntax:

for (initialization; condition; increment/decrement) {
// code that needs to be executed repeatedly
}

Characteristics:

There are three main parts of a traditional for loop, these are:

  1. Initialization: This part executes once when the loop starts. It usually initialises the loop counter variable.
  2. Condition: This part of the loop is evaluated for each iteration, if it returns true, the loop continues else the loop stops.
  3. Increment/Decrement: This part of the loop executes at the end of the iteration, it usually updates the counter variable. This is important as it ensures how many time a loop has to run, if it doesn’t update the counter variable the condition remains true for infinite times.

Use Cases:

  • The traditional for loop is suitable when you need to iterate over a specific number of times.
  • Useful when you need to access the loop counter variable.

Example:

Let’s see the examples to understand how a for loop is used to iterate over arrays and collections.

Iterating Over an Array using for Loop

public class ForLoopArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};

// Using a for loop to iterate over the array
for (int i = 0; i < numbers.length; i++) {
System.out.println("Item at index " + i + ": " + numbers[i]);
}
}
}

Iterating Over a List using for Loop

import java.util.ArrayList;
import java.util.List;

public class ForLoopListExample {
public static void main(String[] args) {
// A list of names
List<String> names = new ArrayList<>();
names.add("Chaitanya");
names.add("Rahul");
names.add("Aditya");

// Using a for loop to iterate over the list
for (int i = 0; i < names.size(); i++) {
System.out.println("Item at index " + i + ": " + names.get(i));
}
}
}

for-each Loop (Enhanced for Loop)

Syntax:

for (Type element : collection) {
// code that needs to be executed
}

Characteristics:

  1. The for-each loop is easier to write and more readable than traditional for loop.
  2. It doesn’t require loop counter variables.
  3. It provides read-only access to the array or collection during iteration.
  4. The loop variable element represents the current element directly, which makes the code type safe and more readable.

Use Cases:

  • It is suitable when you do not need to know the loop counter variable value during each iteration.
  • Always advisable to use for-each loop, when you need to iterate over all elements of a collection or array.

Example:

Iterating Over an Array using for-each Loop

public class ForEachLoopArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};

// Using a for-each loop to iterate over the array
for (int number : numbers) {
System.out.println("Item: " + number);
}
}
}

Iterating Over a List using for-each Loop

import java.util.ArrayList;
import java.util.List;

public class ForEachLoopListExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Chaitanya");
names.add("Rahul");
names.add("Aditya");

// Using a for-each loop to iterate over a list
for (String name : names) {
System.out.println("Item: " + name);
}
}
}

Comparison between for and for-each

  1. Flexibility:
    • for loop: More flexible as it gives you access to loop counter.
    • for-each loop: Less flexible, suitable when you need to iterate all the elements.
  2. Access to Index:
    • for loop: You can access loop index, which is nothing but the loop counter variable value during each iteration.
    • for-each loop: Doesn’t give you access to loop index as it doesn’t have any.
  3. Modifying the Collection or Array:
    • for loop: You can modify the element during iteration.
    • for-each loop: You cannot modify array or collection during iteration.
  4. Performance:
    • Both loops give almost similar performance.
  5. Less prone to error:
    • The syntax of for-each is simple and more readable, thus it is less prone to human error compared to traditional for loop.

Top Related Articles:

  1. ValueOf() Method in Java
  2. Java Scanner class with examples
  3. How to Compile and Run your First Java Program
  4. How to sort Hashtable in java
  5. Constructor Overloading in Java with examples

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap