- Java Programming Basics
- Java Tutorial
- Java Overview
- Java Environment Setup
- Java Program Structure
- Java Basic Syntax
- Java First Program
- Java Constants
- Java Separators
- Java Keywords
- Java Data Types
- Java Data Types
- Java Integers
- Java Floating Point
- Java Characters
- Java Booleans
- Java Numbers
- Java Programming Variables
- Java Variables
- Java Variable Types
- Java Variable Scope
- Java Type Conversion
- Java Type Casting
- Java Auto Type Promotion
- Java Type Promotion Rules
- Java Programming Arrays
- Java Arrays
- Java One Dimensional Array
- Java Multidimensional Array
- Java Programming Operators
- Java Operators
- Java Arithmetic Operators
- Java Increment Decrement
- Java Bitwise Operators
- Java Left Shift
- Java Right Shift
- Java Relational Operators
- Java Boolean Logical Operators
- Java Ternary(?) Operator
- Java Operator Precedence
- Java Control Statements
- Java Decision Making
- Java if if-else if-else-if
- Java switch Statement
- Java Loops
- Java while Loop
- Java do-while Loop
- Java for Loop
- Java for-each Loop
- Java Nested Loops
- Java break Statement
- Java continue Statement
- Java Class Object Method
- Java Classes and Objects
- Java Class
- Java Object
- Java new Operator
- Java Methods
- Java Constructors
- Java this Keyword
- Java Stack
- Java Overloading Recursion
- Java Method Overloading
- Java Constructor Overloading
- Java Object as Parameter
- Java Call by Value Reference
- Java Returning Objects
- Java Recursion
- Java Modifier Types
- Java Encapsulate Poly String
- Java Encapsulation
- Java Polymorphism
- Java Nested Inner Class
- Java Strings
- Java Command Line Arguments
- Java Variable Length Arguments
- Java Inheritance Abstraction
- Java Inheritance
- Java super Superclass
- Java Multilevel Hierarchy
- Java Method Overriding
- Java Abstraction
- Java Packages Interfaces
- Java Packages
- Java Access Protection
- Java Import Statement
- Java Interfaces
- Java Programming Exceptions
- Java Exception Handling
- Java try catch
- Java throw throws
- Java finally Block
- Java Built In Exceptions
- Java Exception Subclasses
- Java Chained Exceptions
- Java Multithreading
- Java Multithreading
- Java Thread Model
- Java Main Thread
- Java Create Thread
- Java Thread Priorities
- Java Synchronization
- Java Inter Thread Communication
- Java Suspend Resume Stop Thread
- Java Get Thread State
- Java Enum Autobox Annotation
- Java Enumerations
- Java Type Wrappers
- Java Autoboxing
- Java Annotation
- Java Marker Annotations
- Java Single Member Annotation
- Java Built In Annotations
- Java Type Annotations
- Java Repeating Annotations
- Java Data File Handling
- Java Files I/O
- Java Streams
- Java Read Console Input
- Java Write Console Output
- Java PrintWriter Class
- Java Read Write Files
- Java Automatically Close File
- Java Programming Advance
- Java Date and Time
- Java Regular Expressions
- Java Collections Framework
- Java Generics
- Java Data Structures
- Java Network Programming
- Java Serialization
- Java Send Email
- Java Applet Basics
- Java Documentation
- Java Programming Examples
- Java Programming Examples
Java For-each or Enhanced for Loop
Beginning with the JDK 5, a second form of the for loop was defined which implements a "for-each" style loop.
The for-each style of for loop is designed to cycle by a collection of objects, such as an array, in strictly sequential fashion, from the start to end.
Unlike some other computer languages like C#, that implements a for-each loop by using the foreach keyword, Java adds for-each capability by enhancing the for loop. The advantage of this approach is that there is no new keyword required, and also no pre-existing code is broken.
The for-each style of the for loop is also referred to as enhanced for loop.
Java for-each for Loop Syntax
The general form of for-each version of the for loop is shown below :
for(type itr-var: collection) statement-block
Here, type specifies the data type and itr-var specifies the name of an iteration variable that will receive the elements from a collection, one at a time, from the beginning to end. The collection being cycled through is specified by collection. There are several types of collections that can be used with the for, but the only type used in this tutorial is the array.
With each iteration of the loop, the next elements in the collection is retrieved and stored in itr-var. The loop repeats before all the elements in the collection have been obtained.
Because the iteration variable gets values from the collection, type must be the same as (or compatible with) the elements stored in the collection. Therefore, when iterating over arrays, type must be compatible with the element type of the array.
To realize the motivation behind a for-each style loop, look at the type of the for loop that it is designed to replace. Here this code fragment uses a traditional for loop to compute the sum of the values in an array :
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = 0; for(int i=0; i<10; i++) { sum = sum + nums[i]; }
To calculate the sum each element present in nums is read from the start to finish. Therefore, the entire array is read purely in sequential order. This is achieved by manually indexing the nums array by the loop control variable i.
The for-each style for automates the previous loop. Specifically, it eliminates the need to establish a loop counter, specify the starting and the ending value, and manually index the array. Instead, it automatically cycles through the entire array, getting one element at a time, in sequence, from the beginning to end. For example, following is the preceding code fragment rewritten by using the for-each version of the for loop:
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = 0; for(int x: nums) { sum = sum + x; }
With each pass through the loop, x is automatically given a value equal to the next element in the variable nums. Therefore, in the first iteration, x contains 1, in the second iteration, x holds 2, and so on. Not only is the syntax efficient, but it also prevents the boundary errors.
Java for-each for Loop Example
Following is an entire program that illustrates the for-each version of the for loop just described :
/* Java Program Example - Java for-each Loop * This program uses a for-each style for loop */ public class JavaProgram { public static void main(String args[]) { int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = 0; // use the for-each style for loop to display and sum the values for(int x : nums) { System.out.println("Value is " + x); sum = sum + x; } System.out.println("\nSummation is " + sum); } }
When the above Java program is compile and executed, it will produce the following output:
As the above output shows, the for-each style of the for loop automatically cycles through an array in sequence from the lowest index to highest.
Even though the for-each for loop iterates until all the elements in an array have been examined, it is also possible to terminate the loop early by using a break statement. For example, the following program sums only starting five elements of nums :
/* Java Program Example - Java for-each Loop * Use a break with a for-each style for */ public class JavaProgram { public static void main(String args[]) { int sum = 0; int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // use for-each for loop to display and sum the values for(int x : nums) { System.out.println("Value is " + x); sum = sum + x; if(x == 5) // stop the loop break; // when 5 is obtained } System.out.println("Summation of first 5 elements is " + sum); } }
When the above Java program is compile and executed, it will produce the following output:
Here, the for loop stops after the fifth element has been obtained. The break statement can also be used with other loops. You will learn about break statement in separate chapter.
« Previous Tutorial Next Tutorial »