×

Java Enhanced For Loop (For-each Loop)

JAVA ENHANCED FOR LOOP

The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through a collection of objects, sequentially from start to finish. It provides a more readable and less error-prone way to iterate through collections and arrays compared to traditional for loops, as it eliminates the need for explicit indexing and bounds checking.

The general form of the for-each version of the for loop is like:

for(type count_var : collection) statement-block

The type specifies the type of the variable count_var. It receives the elements from a collection one at a time and iterates from beginning to end. With each iteration of the loop, the next component of the collection is retrieved and stored in count_var. The loop repeats until all elements in the collection have been obtained. Because the iteration variable receives values from the collection, the type must be the same as(or compatible with) the elements stored in the collection. Thus, when iterating over arrays, the type must be compatible with the element type of the array.

We can also easily iterate through nested collections using the enhanced for loop.

Example:

Filename: Myclass.java

import java.util.ArrayList;

public class Myclass {

public static void main(String[] args) {

ArrayList<String> myList = new ArrayList<String>();

myList.add("Java");

myList.add("Loop");

myList.add("for-each");

for (String val : myList) {

System.out.println(val);

}

}

}

Output

Java

Loop

for-each

One thing we should consider here is, what will happen if we try to modify the loop variable in enhanced for loop?.

The answer lies in the fact that, if we are traversing through the object or primitive type. If we’re iterating through an array of primitive values, manipulation of the loop variable will never change the value of the array being iterated because the primitive values are passed by value to the loop variable in an enhanced for loop. This means that even if we modify the loop variable inside the loop, it does not affect the original array values.

When we iterate through a collection of objects, the value of the collection is passed by reference to the loop variable. Therefore, if the value of the loop variable is manipulated by executing methods on it, the modified value will be reflected in the collection of objects being iterated.

Limitation of enhanced for loop

  • It can’t be used to delete or remove the elements from a collection: The enhanced for loop hides the iterator used to iterate through the elements of a collection, we can’t use it to remove or delete the existing collection values because we can’t call the remove method.
  • We cannot iterate over multiple collection arrays in the same loop: Since the enhanced for loop is designed to work on a single collection at a time, iterating over multiple collections simultaneously is not possible within the same loop structure.
  • The enhanced for loop can’t be used to initialize an array and modify its elements: Since the loop variable holds only a copy of primitive values from an array, any modification to the loop variable inside the loop does not affect the original array.

Multiple Choice Questions

1. What is the main advantage of using the enhanced for loop over a traditional for loop?

A) It allows modifying elements in an array directly.

B) It eliminates the need for explicit indexing and bounds checking.

C) It can iterate over multiple collections simultaneously.

D) It can remove elements from a collection.

Answer: B) It eliminates the need for explicit indexing and bounds checking.

2. What is the correct syntax for an enhanced for loop?

A) for (int i = 0; i < array.length; i++) { }

B) for (int val in array) { }

C) for (type count_var : collection) { }

D) foreach (int val in array) { }

Answer: C) for (type count_var : collection) { }

3. What happens if we modify the loop variable while iterating over an array of primitive types in an enhanced for loop?

A) The original array is modified.

B) The modification applies only to the loop variable, not the original array.

C) It throws a compilation error.

D) It results in a runtime exception.

Answer: B) The modification applies only to the loop variable, not the original array.

4. Which of the following is NOT a limitation of the enhanced for loop?

A) It cannot iterate over multiple collections in a single loop.

B) It does not provide access to element indexes.

C) It allows modifying objects inside a collection.

D) It allows removing elements from a collection.

Answer: C) It allows modifying objects inside a collection.

5. What happens when we iterate over an array of objects in an enhanced for loop and modify object properties?

A) The changes do not reflect in the original array.

B) The changes reflect in the original array since objects are passed by reference.

C) It throws a compilation error.

D) It results in an infinite loop.

Answer: B) The changes reflect in the original array since objects are passed by reference.


Related Topics

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Automatic Resource Management

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources. There are two ways of management of resources: The computer program itself...

2 minutes read.

Difference between Abstract Class and Interface

There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s...

2 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.

How to handle NullPointerException in Java

Introduction: Throwable class is the super or root class of the java exception hierarchy which contains two sub-classes. The classes’ are- ExceptionError Exception: If you are doing any wrong things in a...

3 minutes read.

Pattern Programs in Java

Pattern Programs in Java In Java, pattern programs are the most important from the perspective of interviews. The pattern programs improve thinking and coding skills. It also helps us to develop a...

27 minutes read.

public static void main string args meaning in java

In java main() method is the initial point for execution of the program. If a program doesn’t contain the main method, the program will not execute. JVM(java virtual machine) starts...

3 minutes read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

How many ways to create object in Java?

In this article, you will be acknowledged about the different ways to create an object in java. So far you construct an object from a class, as is common knowledge,...

6 minutes read.

How to compare dates in Java

Introduction: In Java, dates can be compared using a similar interface's compareTo() technique. This method returns 'zero' if each date is the same, returns a rate "more than 0" if...

6 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Java Integer min() method

The min()  method of Integer class returns the smaller of two int values. It returns the same result as by calling Math.min.  Syntax public static int min(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

Java HashMap

Java HashMap extends AbstractMap and implements Map interface. It is the collection of multiple entries where an entry consists of key and value pair. The HashMap can contain only one...

7 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.