×

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

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called...

3 minutes read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

How to write basic Java Programs

Java Basic Programs In this section, we will learn how to write basic Java programs. But first we need to take care of the following requirement list. To execute a Java program,...

4 minutes read.

Java Garbage Collection Interview Questions

One of the key areas of Java is garbage collection. Garbage collection enables apps to manage memory automatically. Interviewers frequently ask inquiries about garbage collection. Q1: What is the purpose of...

6 minutes read.

Difference between this and super in Java

In this article, you will be very well equipped with the knowledge of this keyword and super keyword in java. You will be able to understand where to implement this...

3 minutes read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

Session Tracking in Java

When a series of requests from the same User (i.e., requests coming from the same browser) occurs over an extended period of time, servlets employ a mechanism known as session...

3 minutes read.

How to convert float to String in Java

How to convert float to String in java There are following methods to convert float to String: Convert using Float.toString(float) Convert using String.valueOf(float) Convert using Float.toString(float) The Float class has a static method that returns...

2 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Java Primitive Data Types

Primitive data types are the simplest data types in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that...

2 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.