0% found this document useful (0 votes)
18 views

Aha 1

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Aha 1

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

Skip to content

geeksforgeeks
Courses 90% Refund
Tutorials
Java
Practice
Contests

Sign In

Java Arrays
Java Strings
Java OOPs
Java Collection
Java 8 Tutorial
Java Multithreading
Java Exception Handling
Java Programs
Java Project
Java Collections Interview
Java Interview Questions
Java MCQs
Spring
Spring MVC
Spring Boot
Hibernate

Content Improvement Event


Share Your Experiences
Java Tutorial
Overview of Java
Basics of Java
Input/Output in Java
Flow Control in Java
Decision Making in Java (if, if-else, switch, break, continue, jump)
Java if statement with Examples
Java if-else
Java if-else-if ladder with Examples
Loops in Java
For Loop in Java
Java while loop with Examples
Java do-while loop with Examples
For-each loop in Java
Continue Statement in Java
Break statement in Java
Usage of Break keyword in Java
return keyword in Java
Operators in Java
Strings in Java
Arrays in Java
OOPS in Java
Inheritance in Java
Abstraction in Java
Encapsulation in Java
Polymorphism in Java
Constructors in Java
Methods in Java
Interfaces in Java
Wrapper Classes in Java
Keywords in Java
Access Modifiers in Java
Memory Allocation in Java
Classes of Java
Packages in Java
Java Collection Tutorial
Exception Handling in Java
Multithreading in Java
Synchronization in Java
File Handling in Java
Java Regex
Java IO
Java Networking
JDBC - Java Database Connectivity
Java 8 Features - Complete Tutorial
Java Backend DevelopmentCourse
For-each loop in Java
Last Updated : 16 Feb, 2023

Prerequisite: Decision making in Java


For-each is another array traversing technique like for loop, while loop, do-while
loop introduced in Java5.

It starts with the keyword for like a normal for-loop.


Instead of declaring and initializing a loop counter variable, you declare a
variable that is the same type as the base type of the array, followed by a colon,
which is then followed by the array name.
In the loop body, you can use the loop variable you created rather than using an
indexed array element.

It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)
Syntax:

for (type var : array)


{
statements using var;
}
Simple program with for each loop:

/*package whatever //do not write package name here */

import java.io.*;

class Easy

public static void main(String[] args)

// array declaration

int ar[] = { 10, 50, 60, 80, 90 };

for (int element : ar)


System.out.print(element + " ");
}
}
Output
10 50 60 80 90
The above syntax is equivalent to:

for (int i=0; i<arr.length; i++)


{
type var = arr[i];
statements using var;
}

// Java program to illustrate


// for-each loop
class For_Each
{
public static void main(String[] arg)
{
{
int[] marks = { 125, 132, 95, 116, 110 };

int highest_marks = maximum(marks);


System.out.println("The highest score is " + highest_marks);
}
}
public static int maximum(int[] numbers)
{
int maxSoFar = numbers[0];

// for each loop


for (int num : numbers)
{
if (num > maxSoFar)
{
maxSoFar = num;
}
}
return maxSoFar;
}
}
Output
The highest score is 132
Limitations of for-each loop
decision-making

For-each loops are not appropriate when you want to modify the array:

for (int num : marks)


{
// only changes num, not the array element
num = num*2;
}
2. For-each loops do not keep track of index. So we can not obtain array
index using For-Each loop

for (int num : numbers)


{
if (num == target)
{
return ???; // do not know the index of num
}
}
3. For-each only iterates forward over the array in single steps

// cannot be converted to a for-each loop


for (int i=numbers.length-1; i>0; i--)
{
System.out.println(numbers[i]);
}
4. For-each cannot process two decision making statements at once

// cannot be easily converted to a for-each loop


for (int i=0; i<numbers.length; i++)
{
if (numbers[i] == arr[i])
{ ...
}
}
5. For-each also has some performance overhead over simple iteration:

/*package whatever //do not write package name here */

import java.io.*;
import java.util.*;

class GFG {
public static void main (String[] args) {
List<Integer> list = new ArrayList<>();
long startTime;
long endTime;
for (int i = 0; i < 1000000; i++) {
list.add(i);
}
// Type 1
startTime = Calendar.getInstance().getTimeInMillis();
for (int i : list) {
int a = i;
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("For each loop :: " + (endTime - startTime) + " ms");

// Type 2
startTime = Calendar.getInstance().getTimeInMillis();
for (int j = 0; j < list.size(); j++) {
int a = list.get(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("Using collection.size() :: " + (endTime - startTime) +
" ms");

// Type 3
startTime = Calendar.getInstance().getTimeInMillis();
int size = list.size();
for (int j = 0; j < size; j++) {
int a = list.get(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("By calculating collection.size() first :: " + (endTime
- startTime) + " ms");

// Type 4
startTime = Calendar.getInstance().getTimeInMillis();
for(int j = list.size()-1; j >= 0; j--) {
int a = list.get(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("Using [int j = list.size(); j > size ; j--] :: " +
(endTime - startTime) + " ms");
}
}

// This code is contributed by Ayush Choudhary @gfg(code_ayush)


Output
For each loop :: 45 ms
Using collection.size() :: 11 ms
By calculating collection.size() first :: 13 ms
Using [int j = list.size(); j > size ; j--] :: 15 ms
Related Articles:
For-each in C++ vs Java
Iterator vs For-each in Java

Three 90 Challenge is back on popular demand! After processing refunds worth INR
1CR+, we are back with the offer if you missed it the first time. Get 90% course
fee refund in 90 days. Avail now!
Want to be a master in Backend Development with Java for building robust and
scalable applications? Enroll in Java Backend and Development Live Course by
GeeksforGeeks to get your hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or want to be a
Java Pro? This course equips you with all you need for building high-performance,
heavy-loaded backend systems in Java. Ready to take your Java Backend skills to the
next level? Enroll now and take your development career to sky highs.

Abhishek Verma

242
Previous Article
Java do-while loop with Examples
Next Article
Continue Statement in Java
Read More
Down Arrow
Similar Reads
Difference Between for loop and Enhanced for loop in Java
Java for-loop is a control flow statement that iterates a part of the program
multiple times. For-loop is the most commonly used loop in java. If we know the
number of iteration in advance then for-loop is the best choice. Syntax:
for( initializationsection ; conditional check ; increment/decrement section) { //
Code to be executed } Curly braces i
5 min read
Flatten a Stream of Lists in Java using forEach loop
Given a Stream of Lists in Java, the task is to Flatten the Stream using forEach()
method. Examples: Input: lists = [ [1, 2], [3, 4, 5, 6], [8, 9] ] Output: [1, 2, 3,
4, 5, 6, 7, 8, 9] Input: lists = [ ['G', 'e', 'e', 'k', 's'], ['F', 'o', 'r'] ]
Output: [G, e, e, k, s, F, o, r] Approach: Get the Lists in the form of 2D list.
Create an empty list t
3 min read
Flatten a Stream of Arrays in Java using forEach loop
Given a Stream of Arrays in Java, the task is to Flatten the Stream using forEach()
method. Examples: Input: arr[][] = {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }} Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9] Input: arr[][] = {{'G', 'e', 'e', 'k', 's'}, {'F', 'o',
'r'}} Output: [G, e, e, k, s, F, o, r] Approach: Get the Arrays in the form of 2D
array. Create an
3 min read
Flatten a Stream of Map in Java using forEach loop
Given a Stream of Map in Java, the task is to Flatten the Stream using forEach()
method. Examples: Input: map = {1=[1, 2], 2=[3, 4, 5, 6], 3=[7, 8, 9]} Output: [1,
2, 3, 4, 5, 6, 7, 8, 9] Input: map = {1=[G, e, e, k, s], 2=[F, o, r], 3=[G, e, e,
k, s]} Output: [G, e, e, k, s, F, o, r] Approach: Get the Map to be flattened.
Create an empty list to c
3 min read
Java do-while loop with Examples
Loops in Java come into use when we need to repeatedly execute a block of
statements. Java do-while loop is an Exit control loop. Therefore, unlike for or
while loop, a do-while check for the condition after executing the statements of
the loop body. Syntax: do { // Loop Body Update_expression } // Condition check
while (test_expression); Note: The
5 min read
Break Any Outer Nested Loop by Referencing its Name in Java
A nested loop is a loop within a loop, an inner loop within the body of an outer
one. Working: The first pass of the outer loop triggers the inner loop, which
executes to completion. Then the second pass of the outer loop triggers the inner
loop again. This repeats until the outer loop finishes. A break within either the
inner or outer loop would i
2 min read
Generic For Loop in Java
When we know that we have to iterate over a whole set or list, then we can use
Generic For Loop. Java's Generic has a new loop called for-each loop. It is also
called enhanced for loop. This for-each loop makes it easier to iterate over array
or generic Collection classes. In normal for loop, we write three statements : for(
statement1; statement 2
4 min read
String Array with Enhanced For Loop in Java
Enhanced for loop(for-each loop) was introduced in java version 1.5 and it is also
a control flow statement that iterates a part of the program multiple times. This
for-loop provides another way for traversing the array or collections and hence it
is mainly used for traversing arrays or collections. This loop also makes the code
more readable and r
1 min read
For Loop in Java
Loops in Java come into use when we need to repeatedly execute a block of
statements. Java for loop provides a concise way of writing the loop structure. The
for statement consumes the initialization, condition, and increment/decrement in
one line thereby providing a shorter, easy-to-debug structure of looping. Let us
understand Java for loop with
7 min read
Java while loop with Examples
Java while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition. The while loop can be thought of as
a repeating if statement. While loop in Java comes into use when we need to
repeatedly execute a block of statements. The while loop is considered as a
repeating if statement. If the number o
4 min read
Article Tags :
Java
Practice Tags :
Java
three90RightbarBannerImg
course-img
214k+ interested Geeks
JAVA Backend Development - Live
Explore
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Explore
course-img
216k+ interested Geeks
Java Programming Online Course [Complete Beginner to Advanced]
Explore
geeksforgeeks-footer-logo
Corporate & Communications Address:- A-143, 9th Floor, Sovereign Corporate Tower,
Sector- 136, Noida, Uttar Pradesh (201305) | Registered Address:- K 061, Tower K,
Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh,
201305
GFG App on Play Store
GFG App on App Store
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By
using our site, you acknowledge that you have read and understood our Cookie Policy
& Privacy Policy
Got It !
Lightbox

You might also like