{"id":5212,"date":"2021-03-23T12:33:56","date_gmt":"2021-03-23T12:33:56","guid":{"rendered":"https:\/\/ded9.com\/?p=5212"},"modified":"2025-12-10T12:09:30","modified_gmt":"2025-12-10T12:09:30","slug":"tutorial-for-each-loop-in-java-in-very-simple-language","status":"publish","type":"post","link":"https:\/\/ded9.com\/tr\/tutorial-for-each-loop-in-java-in-very-simple-language\/","title":{"rendered":"Understanding the Java for-each Loop \u2014 Simple Guide for Beginners"},"content":{"rendered":"<p><span style=\"font-size: 18pt;\"><span style=\"font-size: 12pt;\">In Java, there is another form of loop (in addition to the standard for loop) for working with arrays and sets. <\/span><span id=\"more-50081\"><\/span><\/span><span style=\"font-size: 12pt;\">If you are working with <a href=\"https:\/\/ded9.com\/how-to-copy-java-arrays-in-very-simple-language\/\">arrays<\/a> and sets, you can duplicate their items using another for loop structure (advanced for loop form). <\/span>This loop type is called a for-each loop because it iterates over each element of the array\/set.<\/p>\n<p>Here is an example of repeating elements of an array using the standard for loop in <a href=\"https:\/\/en.wikipedia.org\/wiki\/Java\" target=\"_blank\" rel=\"noopener\">Java<\/a>:<\/p>\n<blockquote>\n<ol>\n<li dir=\"ltr\">class ForLoop {<\/li>\n<li dir=\"ltr\">public static void main (String [] args) {<\/li>\n<li dir=\"ltr\"><\/li>\n<li dir=\"ltr\">char [] vowels = {&#8216;a&#8217;, &#8216;e&#8217;, \u200b\u200b&#8217;i&#8217;, &#8216;o&#8217;, &#8216;u&#8217;};<\/li>\n<li dir=\"ltr\">for (int i = 0; i &lt;vowels.length; ++ i) {<\/li>\n<li dir=\"ltr\">System.out.println (vowels [i]);<\/li>\n<li dir=\"ltr\">}<\/li>\n<li dir=\"ltr\">}<\/li>\n<li dir=\"ltr\">}<\/li>\n<\/ol>\n<\/blockquote>\n<p><strong>You can also write the above code using the for-each loop:<\/strong><\/p>\n<blockquote>\n<ol>\n<li dir=\"ltr\">class AssignmentOperator {<\/li>\n<li dir=\"ltr\">public static void main (String [] args) {<\/li>\n<li dir=\"ltr\"><\/li>\n<li dir=\"ltr\">char [] vowels = {&#8216;a&#8217;, &#8216;e&#8217;, \u200b\u200b&#8217;i&#8217;, &#8216;o&#8217;, &#8216;u&#8217;};<\/li>\n<li dir=\"ltr\">\/\/ foreach loop<\/li>\n<li dir=\"ltr\">for (char item: vowels) {<\/li>\n<li dir=\"ltr\">System.out.println (item);<\/li>\n<li dir=\"ltr\">}<\/li>\n<li dir=\"ltr\">}<\/li>\n<li dir=\"ltr\">}<\/li>\n<\/ol>\n<\/blockquote>\n<p><strong>The output of both codes is similar and equal to:<\/strong><\/p>\n<blockquote>\n<ol>\n<li dir=\"ltr\">a<\/li>\n<li dir=\"ltr\">e<\/li>\n<li dir=\"ltr\">i<\/li>\n<li dir=\"ltr\">o<\/li>\n<li dir=\"ltr\">u<\/li>\n<\/ol>\n<\/blockquote>\n<p>The advanced for loop makes the code easier to write and more readable. Hence, it is usually recommended more than the standard form.<\/p>\n<h2><span style=\"font-size: 18pt;\">For each ring structure<\/span><\/h2>\n<p>First, let&#8217;s look at the for-each loop structure:<\/p>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\">for (data_type item: collection) {\r\n\r\n\u2026\r\n\r\n}<\/pre>\n<\/div>\n<p>In the above structure,<\/p>\n<ul>\n<li>collection is a collection or array in which you want to write a circle.<\/li>\n<li>An item is a single element of the collection.<\/li>\n<\/ul>\n<h2><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter wp-image-258171 size-full\" src=\"https:\/\/ded9.com\/wp-content\/uploads\/2021\/03\/for-each-loop-in-java-1.jpg\" alt=\"For each ring structure\" width=\"828\" height=\"454\" srcset=\"https:\/\/ded9.com\/wp-content\/uploads\/2021\/03\/for-each-loop-in-java-1.jpg 828w, https:\/\/ded9.com\/wp-content\/uploads\/2021\/03\/for-each-loop-in-java-1-300x164.jpg 300w, https:\/\/ded9.com\/wp-content\/uploads\/2021\/03\/for-each-loop-in-java-1-768x421.jpg 768w\" sizes=\"(max-width: 828px) 100vw, 828px\" \/><\/h2>\n<h2>How does the for-each loop work?<\/h2>\n<p>Here&#8217;s how the for-each loop works.<\/p>\n<ul>\n<li>Repeat through any component of the given array or collection,<\/li>\n<li>Stores each item in an item.<\/li>\n<li>And executes the body of the ring.<\/li>\n<\/ul>\n<p><strong>Example: for-each loop<\/strong><\/p>\n<p>The following program calculates the sum of all the elements of an array of integers.<\/p>\n<blockquote>\n<ol>\n<li dir=\"ltr\">class EnhancedForLoop {<\/li>\n<li dir=\"ltr\">public static void main (String [] args) {<\/li>\n<li dir=\"ltr\"><\/li>\n<li dir=\"ltr\">int [] numbers = {3, 4, 5, -5, 0, 12};<\/li>\n<li dir=\"ltr\">int sum = 0;<\/li>\n<li dir=\"ltr\"><\/li>\n<li dir=\"ltr\">for (int number: numbers) {<\/li>\n<li dir=\"ltr\">sum + = number;<\/li>\n<li dir=\"ltr\">}<\/li>\n<li dir=\"ltr\"><\/li>\n<li dir=\"ltr\">System.out.println (\u201cSum =\u201d + sum);<\/li>\n<li dir=\"ltr\">}<\/li>\n<li dir=\"ltr\">}<\/li>\n<\/ol>\n<\/blockquote>\n<p><strong>Output<\/strong><\/p>\n<blockquote>\n<p dir=\"ltr\">Sum = 19<\/p>\n<\/blockquote>\n<p>In the above program, the execution of the for-each loop is as follows:<\/p>\n<p><img decoding=\"async\" class=\"lazyloaded aligncenter wp-image-50083\" src=\"https:\/\/ded9.com\/wp-content\/uploads\/2025\/02\/word-image.png\" alt=\"In the above program, the execution of the for-each loop is as follows:\" width=\"400\" height=\"340\" data-ll-status=\"loaded\" \/><\/p>\n<p>You see a repeat of the for-each loop<\/p>\n<ul>\n<li>All elements of numbers are repeated.<\/li>\n<li>Each element is stored in the number variable.<\/li>\n<li>The loop body is executed; i.e., the number is added to the sum.<\/li>\n<\/ul>\n<h3><img decoding=\"async\" class=\"aligncenter wp-image-258174 size-full\" src=\"https:\/\/ded9.com\/wp-content\/uploads\/2021\/03\/1vyvy.jpg\" alt=\"You see a repeat of the for-each loop\n\nAll elements of numbers are repeated.\nEach element is stored in the number variable.\nThe loop body is executed; i.e., the number is added to the sum.\" width=\"1030\" height=\"579\" srcset=\"https:\/\/ded9.com\/wp-content\/uploads\/2021\/03\/1vyvy.jpg 1030w, https:\/\/ded9.com\/wp-content\/uploads\/2021\/03\/1vyvy-300x169.jpg 300w, https:\/\/ded9.com\/wp-content\/uploads\/2021\/03\/1vyvy-1024x576.jpg 1024w, https:\/\/ded9.com\/wp-content\/uploads\/2021\/03\/1vyvy-768x432.jpg 768w\" sizes=\"(max-width: 1030px) 100vw, 1030px\" \/><\/h3>\n<h3>forEach() vs. Traditional for Loop<\/h3>\n<p>Both <code>forEach()<\/code> and the traditional <code>for<\/code> loop can be used to iterate over collections and arrays. However, the <code>forEach()<\/code> method lacks the flexibility that the <code>for<\/code> loop provides.<\/p>\n<p>With a traditional <code>for<\/code> loop, you have complete control over loop variables, conditions, and increments, whereas <code>forEach()<\/code> Abstracts these details:<\/p>\n<div>\n<div class=\"rounded-b-xl bg-background-static-850 px-4 pb-1.5 dark:bg-background-static-900\">\n<div>\n<pre><code>List&lt;String&gt; names = List.of(\"Larry\", \"Steve\", \"James\", \"Conan\", \"Ellen\");\r\nfor (int i = 0; i &lt; names.size(); i++) {\r\n    LOG.info(names.get(i));\r\n}\r\n<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<p>Additionally, you can modify loop conditions:<\/p>\n<div>\n<div class=\"rounded-b-xl bg-background-static-850 px-4 pb-1.5 dark:bg-background-static-900\">\n<div>\n<pre><code>for (int i = 0; i &lt; names.size() - 1; i++) {\r\n    LOG.info(names.get(i));\r\n}\r\n<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<p>In the example above, the last element is skipped by adjusting the loop condition (<code>names.size() - 1<\/code>). This level of customization is not possible with <code>forEach()<\/code>.<\/p>\n<p>While <code>forEach()<\/code> allows operations on individual elements, it does not permit modifications to the collection. In contrast, the <code>for<\/code> loop provides more flexibility, enabling both element-specific operations and direct changes in the collection.<\/p>\n<h3><span style=\"font-family: georgia, palatino, serif;\"><code>forEach()<\/code> vs. Enhanced <code>for<\/code> Loop<\/span><\/h3>\n<p>At a basic level, both loops serve the same purpose: iterating over elements in a collection. However, their underlying mechanics differ\u2014while the enhanced <code>for<\/code> loop uses an <strong>external iterator<\/strong>, the <code>forEach()<\/code> The method relies on an <strong>internal iterator<\/strong>.<\/p>\n<h4>Internal Iterator \u2013 <code>forEach()<\/code><\/h4>\n<p>An internal iterator handles iteration behind the scenes, allowing the programmer to focus solely on defining operations for each element in the collection. Instead of explicitly managing the iteration process, the Iterator ensures that elements are processed sequentially.<\/p>\n<p>Here&#8217;s an example:<\/p>\n<div>\n<div class=\"rounded-b-xl bg-background-static-850 px-4 pb-1.5 dark:bg-background-static-900\">\n<div>\n<pre><code>List&lt;String&gt; names = List.of(\"Larry\", \"Steve\", \"James\", \"Conan\", \"Ellen\");\r\nnames.forEach(name -&gt; LOG.info(name));\r\n<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<p>In the <code>forEach()<\/code> In the method above, a lambda expression is passed as an argument. This means that instead of manually controlling iteration, we specify what should be done to each element\u2014the method handles the rest.<\/p>\n<p>While <code>forEach()<\/code> simplifies code readability and reduces verbosity, the enhanced <code>for<\/code> A loop may be preferable when greater control over iteration is required.<\/p>\n<h2>FAQ<\/h2>\n<div id=\"rank-math-rich-snippet-wrapper\"><div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-1\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">What is the Java for-each loop used for?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>The for-each loop is used to iterate over every element in an array or a collection without manually managing an index or loop counters.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-2\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">What is the syntax of the for-each loop in Java?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>for (Type element : arrayOrCollection) { \/* use element *\/ } \u2014 where element holds each item in turn, and the loop runs until all elements are processed.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-3\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Are there limitations when using for-each instead of a traditional for loop?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Yes \u2014 you cannot easily modify elements by index, cannot get the index of current element, cannot iterate in reverse, and you should not use it when you must change the collection\u2019s structure.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>In Java, there is another form of loop (in addition to the standard for loop) for working with arrays and sets. If you are working with arrays and sets, you can duplicate their items using another for loop structure (advanced for loop form). This loop type is called a for-each loop because it iterates over [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":5213,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[11513],"tags":[840],"class_list":["post-5212","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java-2","tag-java"],"acf":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/posts\/5212","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/comments?post=5212"}],"version-history":[{"count":5,"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/posts\/5212\/revisions"}],"predecessor-version":[{"id":266013,"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/posts\/5212\/revisions\/266013"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/media\/5213"}],"wp:attachment":[{"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/media?parent=5212"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/categories?post=5212"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ded9.com\/tr\/wp-json\/wp\/v2\/tags?post=5212"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}