×

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

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Enterprise Java Beans

One of the many Java APIs for the common development of corporate software is Enterprise Java Beans (EJB). An EJB, a server-side software component, contains the business logic of an...

4 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute read.

Java Xml Parser

In this article, we acknowledge you about what is a XML parser in Java, how is it going to work and what is the purpose of it. Also, the article discusses...

6 minutes read.

Trimorphic numbers in Java

Wondered what the Trimorphic number is!! In this article, you can learn about what a Trimorphic number is referred to as and how to find whether a number is trimorphic...

3 minutes read.

Matrix Multiplication Program in Java

Matrix Multiplication Program in Java The matrix multiplication program in Java is the continuation of the matrix program in Java that we have already discussed earlier. In this section, we will...

3 minutes read.

Awesome explanation of Strings in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax: public int compareTo(String anotherString) Parameters: anotherString: the...

2 minutes read.

Composition in Java

Composition Java uses the composition method to implement a has-a connection. Composition allows us to reuse code in the same way that Java inheritance does. The "is-a" relationship is implemented using the...

3 minutes read.

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Java calculate age

In this section, we will create a Java program that calculates age from the given date of birth or current date. In order to get the date of birth from the current...

6 minutes read.