

{"id":6594,"date":"2018-01-26T05:01:53","date_gmt":"2018-01-26T05:01:53","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=6594"},"modified":"2026-05-16T17:27:16","modified_gmt":"2026-05-16T11:57:16","slug":"loops-in-java","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/loops-in-java\/","title":{"rendered":"Loops in Java &#8211;  for, while, do-while"},"content":{"rendered":"<div class='__iawmlf-post-loop-links' style='display:none;' data-iawmlf-post-links='[{&quot;id&quot;:2162,&quot;href&quot;:&quot;https:\\\/\\\/www.cs.amherst.edu\\\/~jerager\\\/cs23\\\/doc\\\/progguide\\\/pitfalls-infiniteLoops.html&quot;,&quot;archived_href&quot;:&quot;http:\\\/\\\/web-wp.archive.org\\\/web\\\/20240412163949\\\/https:\\\/\\\/www.cs.amherst.edu\\\/~jerager\\\/cs23\\\/doc\\\/progguide\\\/pitfalls-infiniteLoops.html&quot;,&quot;redirect_href&quot;:&quot;&quot;,&quot;checks&quot;:[{&quot;date&quot;:&quot;2025-12-11 00:19:55&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2025-12-15 11:49:35&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2025-12-30 10:51:37&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-01-18 15:35:17&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-01-21 19:57:52&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-01-25 21:02:52&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-01-29 01:20:17&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-02-01 16:34:59&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-02-12 12:02:40&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-02-17 03:56:39&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-03-03 17:05:29&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-03-08 18:09:02&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-03-12 00:53:13&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-03-16 19:57:25&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-03-21 18:53:05&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-04-05 00:11:42&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-04-14 00:59:39&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-04-27 13:44:52&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-05-07 11:42:59&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-05-15 07:34:44&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-05-26 14:38:35&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-06-03 06:22:31&quot;,&quot;http_code&quot;:200},{&quot;date&quot;:&quot;2026-06-07 04:29:44&quot;,&quot;http_code&quot;:200}],&quot;broken&quot;:false,&quot;last_checked&quot;:{&quot;date&quot;:&quot;2026-06-07 04:29:44&quot;,&quot;http_code&quot;:200},&quot;process&quot;:&quot;done&quot;}]'><\/div>\n<p>Loops are a fundamental concept in programming. To understand what loops are, we have to look at some real-life cases of loops. Consider your daily routine, you wake up, you brush, you wear clothes, and then head off to work, come back, eat, and then sleep off. Again, the next day, you do the same things in the same order and go to sleep again. This cycle keeps on repeating. This concept of repetitive actions performed time and again is called a loop. In this Java tutorial, we will learn about the loops in Java.<\/p>\n<h3>Need of the Loops in Java<\/h3>\n<p>Imagine a program that is required to output a particular value of a variable 800 times. Now we all know that the code for writing output is System.out.println(\u201cText\u201d); But to print this 800 times, we will need to write the same line 800 times in the code. That would take up a lot of effort, which is particularly just copy pasting the same sentence 800 times.<\/p>\n<p>Let us say that you have managed to copy and paste the entire thing easily. Now, if there is a different program that requires you to print the first 800 natural numbers. The copy-paste method would not work because you still would have to go to all these lines and fit a number. That&#8217;s where loops come into play. Loops make it very easy to group all the code that needs to be repetitively processed and throw it under scope. The loop does the remaining job.<\/p>\n<h3>Loops in Java<\/h3>\n<p><em><strong>Looping in Java is defined as performing some lines of code in an ordered fashion until a condition is false.<\/strong><\/em><\/p>\n<p>The main aim of using loops is to simplify repetitive tasks. Some loops operate over the number of iterations, while others on the termination conditions. If not given a proper terminating condition, loops will result in the execution of infinite loops, which is not good practice in coding.<\/p>\n<p><strong>In Java, there are three primary types of loops:-<\/strong><\/p>\n<p><strong>1. for loop<\/strong><br \/>\n<strong>2. Enhanced for loop<\/strong><br \/>\n<strong>3. while loop<\/strong><br \/>\n<strong>4. do-while loop<\/strong><\/p>\n<h3>For loop in Java<\/h3>\n<p>A Java for loop consists of 3 primary factors that define the loop itself. These are the initialization statement, a testing condition, and an increment or decrement part for incrementing\/decrementing the control variable.<\/p>\n<p><strong>The basic syntax of the Java for loop goes like this:<\/strong><\/p>\n<p>for(initializing statement;testing condition;increment\/decrement)<br \/>\n{<br \/>\n\/\/code to be iterated<br \/>\n}<\/p>\n<p>The initializing statement marks the beginning of the loop structure. It contains a variable with some initial value that is defined by the programmer. This is the value of the control variable when the control shifts into the loop. However, this statement is executed only once.<br \/>\nIf a particular variable is declared within this part, then the scope of the variable remains limited within the loop.<\/p>\n<p><strong>The control flow of the for loop in Java is explained with a flowchart diagram:<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-forloop.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-78534\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-forloop.jpg\" alt=\"Flow Diagram for forloop\" width=\"567\" height=\"425\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-forloop.jpg 567w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-forloop-300x225.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-forloop-150x112.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-forloop-520x390.jpg 520w\" sizes=\"auto, (max-width: 567px) 100vw, 567px\" \/><\/a><\/p>\n<p><strong>A program of the for loop in Java:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.dataflair.loops;\r\nimport java.io. * ;\r\npublic class ForLoop {\r\n  public static void main(String[] args) {\r\n    int i;\r\n    for (i = 0; i &lt;= 10; i++) {\r\n      System.out.println(\"Studying for loops at DataFlair\");\r\n      System.out.println(\"Value of i = \" + i);\r\n    }\r\n  }\r\n}<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Studying for loops at DataFlair<br \/>\nValue of i = 0<br \/>\nStudying for loops at DataFlair<br \/>\nValue of i = 1<br \/>\nStudying for loops at DataFlair<br \/>\nValue of i = 2<br \/>\nStudying for loops at DataFlair<br \/>\nValue of i = 3<br \/>\nStudying for loops at DataFlair<br \/>\nValue of i = 4<br \/>\nStudying for loops at DataFlair<br \/>\nValue of i = 5<br \/>\nStudying for loops at DataFlair<br \/>\nValue of i = 6<br \/>\nStudying for loops at DataFlair<br \/>\nValue of i = 7<br \/>\nStudying for loops at DataFlair<br \/>\nValue of i = 8<br \/>\nStudying for loops at DataFlair<br \/>\nValue of i = 9<br \/>\nStudying for loops at DataFlair<br \/>\nValue of i = 10<\/div>\n<p>Observe the value of the loop\u2019s control variable i as it increases from 0 to 10 and then stops because the value of i becomes 11 and the condition becomes false. Hence, it goes out of the loop.<\/p>\n<h4>a. Enhanced for loop in Java<\/h4>\n<p>This is similar to a for loop except that it has some enhanced features. It can be used to iterate over the elements of a collection without knowing the index of each element. You also do not need to know the size of the collection.<\/p>\n<p>However, there are some limitations to this enhanced for loop. This loop object is immutable, which means the values that are retrieved during the execution of the loop are read-only. You cannot change the values in the collection while using this loop, which is easily done by other loops.<\/p>\n<p><strong>The syntax for Java enhanced for loop is:<\/strong><\/p>\n<p>for(&lt;datatype&gt; &lt;variable_name&gt;:&lt;collection_name&gt;)<br \/>\n{<br \/>\n\/\/Statements;<br \/>\n}<\/p>\n<p><strong>Java program to illustrate the use of enhanced for-loop:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.dataflair.loops;\r\nimport java.io. * ;\r\npublic class EnhancedFor {\r\n  public static void main(String[] args) {\r\n    String array[] = {\r\n      \"DataFlair\",\r\n      \"Java\",\r\n      \"Python\"\r\n    };\r\n    for (String a: array) {\r\n      System.out.println(a);\r\n    }\r\n  }\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">DataFlair<br \/>\nJava<br \/>\nPython<\/div>\n<h3>While loop in Java<\/h3>\n<p>The While loop is very important as we cannot know the extent of a loop every time we define one. For example, if we were asked to take a dynamic collection and iterate through every element, for loops would be impossible to use because we do not know the size of the collection. Then we would have to use an enhanced for loop or a while loop.<\/p>\n<p>A while loop iterates through a set of statements till its boolean condition returns false. As long as the condition given evaluates to true, the loop iterates.<\/p>\n<p>The condition of the while loop structure is checked first, and then the control proceeds into the loop structure only if the condition evaluates to true. Hence, it is called an entry-controlled loop. The body of the loop generally contains a variable that controls the Boolean condition mentioned.<\/p>\n<p><strong>The basic syntax of the Java while loop is:<\/strong><\/p>\n<p>while(boolean condition)<br \/>\n{<br \/>\n\/\/statements;<br \/>\n}<\/p>\n<p>As soon as the condition hits false, the loop terminates.<\/p>\n<p>If you are still confused about the working flow of the while loop, refer to the flowchart below.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-Whileloop.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-78535\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-Whileloop.jpg\" alt=\"Flow Diagram for Whileloop\" width=\"733\" height=\"401\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-Whileloop.jpg 733w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-Whileloop-300x164.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-Whileloop-150x82.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-Whileloop-520x284.jpg 520w\" sizes=\"auto, (max-width: 733px) 100vw, 733px\" \/><\/a><\/p>\n<p><strong>A Java program to illustrate the use of a while loop:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.dataflair.loops;\r\nimport java.io. * ;\r\npublic class WhileLoop {\r\n  public static void main(String[] args) {\r\n    int i = 0;\r\n    while (i &lt; 5) {\r\n      System.out.println(\"Learning Java at DataFlair\");\r\n      System.out.println(\"The value of i is = \" + i);\r\n      i++;\r\n    }\r\n    System.out.println(\"The value of i became \" + i + \" that is why it broke out of the loop\");\r\n  }\r\n\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Learning Java at DataFlair<br \/>\nThe value of i is = 0<br \/>\nLearning Java at DataFlair<br \/>\nThe value of i is = 1<br \/>\nLearning Java at DataFlair<br \/>\nThe value of i is = 2<br \/>\nLearning Java at DataFlair<br \/>\nThe value of i is = 3<br \/>\nLearning Java at DataFlair<br \/>\nThe value of i is = 4<br \/>\nThe value of i became 5 that is why it broke out of the loop<\/div>\n<h3>Do-while loop in Java<\/h3>\n<p>The Java do-while loop executes the statement first and then checks for the condition. Other than that, it is similar to the while loop. The difference lies in the fact that if the condition is true at the start of the loop, the statements would still be executed; in the case of a while loop, it would not be executed at all.<\/p>\n<p>Do while loop is an exit-controlled loop because of the fact that it checks the condition after the statements inside it are executed.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-Dowhileloop.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-78536\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-Dowhileloop.jpg\" alt=\"Flow Diagram for Dowhileloop\" width=\"821\" height=\"379\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-Dowhileloop.jpg 821w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-Dowhileloop-300x138.jpg 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-Dowhileloop-150x69.jpg 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-Dowhileloop-768x355.jpg 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Flow-Diagram-for-Dowhileloop-520x240.jpg 520w\" sizes=\"auto, (max-width: 821px) 100vw, 821px\" \/><\/a><\/p>\n<p><strong>An example Java program to illustrate the use of a do-while loop:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.dataflair.loops;\r\nimport java.io. * ;\r\npublic class DoWhileLoop {\r\n  public static void main(String[] args) {\r\n    int i = 0;\r\n    do {\r\n      i++;\r\n      System.out.println(\"Learning Java at DataFlair\");\r\n      System.out.println(\"The value of i is \" + i);\r\n\r\n    }\r\n    while ( i != 5 );\r\n  }\r\n\r\n}<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Learning Java at DataFlair<br \/>\nThe value of i is 1<br \/>\nLearning Java at DataFlair<br \/>\nThe value of i is 2<br \/>\nLearning Java at DataFlair<br \/>\nThe value of i is 3<br \/>\nLearning Java at DataFlair<br \/>\nThe value of i is 4<br \/>\nLearning Java at DataFlair<br \/>\nThe value of i is 5<\/div>\n<p>Notice that even when the condition is false at i=5(bold), the statements still execute.<\/p>\n<h3>Nested Loops in Java<\/h3>\n<p>As the name suggests, nested loops are basically one loop functioning inside another one. After the first iteration of the outer loop starts, the inner loop starts. As soon as the inner loop finishes its iterations and exits, the first iteration of the outer loop completes, and then it goes for the second iteration. This keeps on repeating till the outermost loop finishes its iterations.<\/p>\n<p>However, nested loops don&#8217;t necessarily mean two loops. You can include as many loops as you want inside one another. If there are two loops, one inside another, one of them having <strong>N<\/strong> iterations and the other one having <strong>M<\/strong> iterations. Then the total number of iterations would be <strong>M x N.<\/strong><\/p>\n<p><strong>Basic syntax for a for loop inside a for loop:<\/strong><\/p>\n<p>for(initializer;condition;increment\/decrement)<br \/>\n{<br \/>\nfor(initializer;condition;increment\/decrement)<br \/>\n{<br \/>\n\/\/code to be nested<br \/>\n}<br \/>\n}<\/p>\n<p><strong>A Java program to understand the concept of nested loops:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.dataflair.loops;\r\npublic class NestedLoop {\r\n  public static void main(String[] args) {\r\n    int i,\r\n    j,\r\n    k;\r\n    k = 0;\r\n    for (i = 0; i &lt; 6; i++) {\r\n      for (j = 0; j &lt; 6; j++) {\r\n        System.out.print(k + \"\\t\");\r\n        k++;\r\n      }\r\n      System.out.println(\"\");\r\n    }\r\n  }\r\n}<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p><span style=\"font-weight: 400\">0 \u00a0 \u00a0 \u00a0 \u00a0 1\u00a0 \u00a0 \u00a0 \u00a0 2\u00a0 \u00a0 \u00a0 \u00a0 3 \u00a0 \u00a0 \u00a0 4\u00a0 \u00a0 \u00a0 \u00a0 5\u00a0 \u00a0 \u00a0 \u00a0<\/span><\/p>\n<p><span style=\"font-weight: 400\">6 \u00a0 \u00a0 \u00a0 \u00a0 7\u00a0 \u00a0 \u00a0 \u00a0 8\u00a0 \u00a0 \u00a0 \u00a0 9 \u00a0 \u00a0 \u00a0 10\u00a0 \u00a0 \u00a0 11<\/span><\/p>\n<p><span style=\"font-weight: 400\">12\u00a0 \u00a0 \u00a0 13\u00a0 \u00a0 \u00a0 14\u00a0 \u00a0 \u00a0 15\u00a0 \u00a0 \u00a0 16\u00a0 \u00a0 \u00a0 17<\/span><\/p>\n<p><span style=\"font-weight: 400\">18\u00a0 \u00a0 \u00a0 19\u00a0 \u00a0 \u00a0 20\u00a0 \u00a0 \u00a0 21\u00a0 \u00a0 \u00a0 22\u00a0 \u00a0 \u00a0 23<\/span><\/p>\n<p><span style=\"font-weight: 400\">24\u00a0 \u00a0 \u00a0 25\u00a0 \u00a0 \u00a0 26\u00a0 \u00a0 \u00a0 27\u00a0 \u00a0 \u00a0 28\u00a0 \u00a0 \u00a0 29<\/span><\/p>\n<p><span style=\"font-weight: 400\">30\u00a0 \u00a0 \u00a0 31\u00a0 \u00a0 \u00a0 32\u00a0 \u00a0 \u00a0 33\u00a0 \u00a0 \u00a0 34\u00a0 \u00a0 \u00a0 35<\/span><\/p>\n<\/div>\n<p>This is a matrix(6&#215;6) which is made by using a nested for loop.<\/p>\n<h3>Some Common Mistakes While Coding Loops<\/h3>\n<h4>Infinite loop in Java<\/h4>\n<p>While designing loops, we can always commit mistakes like forgetting to update the condition variable or not defining a proper condition, which leads to the loop being run an infinite number of times. Different IDEs have different mechanisms to stop live execution of code. It&#8217;s important to know your own IDE\u2019s shortcut to stop live execution of a program in case you have the unfortunate incident of <strong><a href=\"https:\/\/www.cs.amherst.edu\/~jerager\/cs23\/doc\/progguide\/pitfalls-infiniteLoops.html\" target=\"_blank\" rel=\"noopener\">java infinite loop<\/a><\/strong>.<\/p>\n<p>The infinite loop results in a program running for an infinite time, which can cause the system to hang. Increase the load on the CPU due to continuous calculations carried out without termination.<\/p>\n<p><strong>Example of an infinite loop in Java:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.dataflair.loops;\r\nimport java.io. * ;\r\npublic class InfiniteWhileLoop {\r\n  public static void main(String[] args) {\r\n    int i = 0;\r\n    while (i &lt; 5) {\r\n      System.out.println(\"Learning Java at DataFlair\");\r\n      System.out.println(\"The value of i is = \" + i);\r\n    }\r\n  }\r\n\r\n}<\/pre>\n<p>The program gives the output infinite time, and you can see the value of i remaining the same.<\/p>\n<h4>Running out of memory in Java<\/h4>\n<p>Sometimes, due to improper planning, we can overflow a collection with data using loops. This is due to poor planning and incorrect choice of collection or looping.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.dataflair.loops;\r\nimport java.util. * ;\r\npublic class Overflowloop {\r\n\r\n  public static void main(String[] args) {\r\n    int i;\r\n    ArrayList &lt; Integer &gt; ar = new ArrayList &lt; &gt;();\r\n    try {\r\n      for (i = 0; i &lt;= Integer.MAX_VALUE; i++) {\r\n        ar.add(i);\r\n      }\r\n    } catch(Exception e) {\r\n      \/\/TODO: handle exception\r\n      System.out.println(e);\r\n    }\r\n  }\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Exception in thread &#8220;main&#8221; java.lang.OutOfMemoryError: Java heap space<br \/>\nat java.base\/java.lang.Integer.valueOf(Integer.java:1071)<br \/>\nat Overflowloop.main(overflowloop.java:12)<\/div>\n<h3>Comparison of Java Loops<\/h3>\n<table>\n<tbody>\n<tr>\n<td><b>Comparison<\/b><\/td>\n<td><b>for loop<\/b><\/td>\n<td><b>while loop<\/b><\/td>\n<td><b>do-while loop<\/b><\/td>\n<\/tr>\n<tr>\n<td><b>Introduction<\/b><\/td>\n<td><span style=\"font-weight: 400\">It iterates a block of code for a known number of times, which is known to the programmer<\/span><\/td>\n<td><span style=\"font-weight: 400\">This iterates a block of code based on the output of a Boolean condition<\/span><\/td>\n<td><span style=\"font-weight: 400\">It is similar to the while loop except the fact that it checks for the condition after the statement is executed for that particular iteration.\u00a0<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>When to use<\/b><\/td>\n<td><span style=\"font-weight: 400\">It should be used when the number of iterations is constant and known before the execution of the program.\u00a0<\/span><\/td>\n<td><span style=\"font-weight: 400\">When the number of iterations is not fixed, a while loop can be used to iterate.\u00a0<\/span><\/td>\n<td><span style=\"font-weight: 400\">If there is a necessity for executing the loop at least once whilst having no knowledge about the number of iterations, the do-while loop has to be used.\u00a0<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>Syntax<\/b><\/td>\n<td><span style=\"font-weight: 400\">for(initializing statement;testing condition;increment\/decrement)<\/span><span style=\"font-weight: 400\"><br \/>\n<\/span><span style=\"font-weight: 400\">{<\/span><span style=\"font-weight: 400\"><br \/>\n<\/span> <span style=\"font-weight: 400\">\/\/code to be iterated<\/span><span style=\"font-weight: 400\"><br \/>\n<\/span><span style=\"font-weight: 400\">}<\/span><\/td>\n<td><span style=\"font-weight: 400\">while(boolean condition)<\/span><\/p>\n<p><span style=\"font-weight: 400\">{<\/span><\/p>\n<p><span style=\"font-weight: 400\">\/\/statements;<\/span><\/p>\n<p><span style=\"font-weight: 400\">}<\/span><\/td>\n<td><span style=\"font-weight: 400\">do<\/span><\/p>\n<p><span style=\"font-weight: 400\">{<\/span><\/p>\n<p><span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0\u00a0\/\/statements<\/span><\/p>\n<p><span style=\"font-weight: 400\">}<\/span><\/p>\n<p><span style=\"font-weight: 400\">while(boolean condition);<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>Example<\/b><\/td>\n<td><span style=\"font-weight: 400\">for(i=1;i&lt;5;i++)<\/span><\/p>\n<p><span style=\"font-weight: 400\">{<\/span><\/p>\n<p><span style=\"font-weight: 400\">System.out.println(\u201cHello\u201d);<\/span><\/p>\n<p><span style=\"font-weight: 400\">}<\/span><\/td>\n<td><span style=\"font-weight: 400\">while(a&lt;10)<\/span><\/p>\n<p><span style=\"font-weight: 400\">{<\/span><\/p>\n<p><span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\u00a0a++;<\/span><span style=\"font-weight: 400\"><br \/>\n<\/span><span style=\"font-weight: 400\"> }<\/span><\/td>\n<td><span style=\"font-weight: 400\">do<\/span><\/p>\n<p><span style=\"font-weight: 400\">{<\/span><\/p>\n<p><span style=\"font-weight: 400\">a++;<\/span><\/p>\n<p><span style=\"font-weight: 400\">}<\/span><\/p>\n<p><span style=\"font-weight: 400\">while(a&lt;10)<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>Infinite Loop Syntax<\/b><\/td>\n<td><span style=\"font-weight: 400\">for(;;)<\/span><\/p>\n<p><span style=\"font-weight: 400\">{<\/span><\/p>\n<p><span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\/\/code<\/span><\/p>\n<p><span style=\"font-weight: 400\">}<\/span><\/td>\n<td><span style=\"font-weight: 400\">while(true)<\/span><\/p>\n<p><span style=\"font-weight: 400\">{<\/span><\/p>\n<p><span style=\"font-weight: 400\">\u00a0\u00a0\u00a0\/\/code<\/span><\/p>\n<p><span style=\"font-weight: 400\">}<\/span><\/td>\n<td><span style=\"font-weight: 400\">do<\/span><\/p>\n<p><span style=\"font-weight: 400\">{<\/span><\/p>\n<p><span style=\"font-weight: 400\">\u00a0\/\/code<\/span><\/p>\n<p><span style=\"font-weight: 400\">}<\/span><\/p>\n<p><span style=\"font-weight: 400\">while(true);<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Loops can be used to solve a wide range of programming problems in addition to these fundamental uses. Any Java programmer needs to know how to use them. Understanding switch statements is essential for any Java programmer. Here are some more instances of Java applications that make use of loops:<\/p>\n<p><strong>1. Simulations:<\/strong> Real-world processes can be simulated with the help of loops. A loop could be used, for instance, to mimic the behaviour of a complex system or to simulate the spread of a disease among a population.<br \/>\n<strong>2. Numerical techniques:<\/strong> Loops are a necessary component of many numerical techniques, including numerical integration and differential equation solving.<\/p>\n<h3>Summary<\/h3>\n<p>Looping is a core concept in programming, and without loops, iterative tasks would be difficult to perform. A strong concept of loops in Java would enable programmers to build programs that can handle repetitive tasks easily.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Loops are a fundamental concept in programming. To understand what loops are, we have to look at some real-life cases of loops. Consider your daily routine, you wake up, you brush, you wear clothes,&#46;&#46;&#46;<\/p>\n","protected":false},"author":5,"featured_media":78533,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[4018,4154,4852,7470,7499,7587,7744,8412,16116],"class_list":["post-6594","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-do-while-loops-in-java","tag-enhanced-for-loop-in-java","tag-for-loop-in-java","tag-java-do-while-loops","tag-java-for-loop","tag-java-loops","tag-java-while-loop","tag-loops-in-java","tag-while-loop-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Loops in Java - for, while, do-while - DataFlair<\/title>\n<meta name=\"description\" content=\"Java Loops are a fundamental concept that helps in the reusability of the code. We will see the type of loops in Java with syntax &amp; example.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/loops-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Loops in Java - for, while, do-while - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Java Loops are a fundamental concept that helps in the reusability of the code. We will see the type of loops in Java with syntax &amp; example.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/loops-in-java\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2018-01-26T05:01:53+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-05-16T11:57:16+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Loops-in-Java-df.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Loops in Java - for, while, do-while - DataFlair","description":"Java Loops are a fundamental concept that helps in the reusability of the code. We will see the type of loops in Java with syntax & example.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/loops-in-java\/","og_locale":"en_US","og_type":"article","og_title":"Loops in Java - for, while, do-while - DataFlair","og_description":"Java Loops are a fundamental concept that helps in the reusability of the code. We will see the type of loops in Java with syntax & example.","og_url":"https:\/\/data-flair.training\/blogs\/loops-in-java\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2018-01-26T05:01:53+00:00","article_modified_time":"2026-05-16T11:57:16+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Loops-in-Java-df.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"10 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/loops-in-java\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/loops-in-java\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823"},"headline":"Loops in Java &#8211; for, while, do-while","datePublished":"2018-01-26T05:01:53+00:00","dateModified":"2026-05-16T11:57:16+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/loops-in-java\/"},"wordCount":1874,"commentCount":1,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/loops-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Loops-in-Java-df.jpg","keywords":["do while loops in java","enhanced for loop in java","for loop in java","java do while loops","java for loop","java loops","java while loop","Loops in java","while loop in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/loops-in-java\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/loops-in-java\/","url":"https:\/\/data-flair.training\/blogs\/loops-in-java\/","name":"Loops in Java - for, while, do-while - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/loops-in-java\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/loops-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Loops-in-Java-df.jpg","datePublished":"2018-01-26T05:01:53+00:00","dateModified":"2026-05-16T11:57:16+00:00","description":"Java Loops are a fundamental concept that helps in the reusability of the code. We will see the type of loops in Java with syntax & example.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/loops-in-java\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/loops-in-java\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/loops-in-java\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Loops-in-Java-df.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/01\/Loops-in-Java-df.jpg","width":1200,"height":628,"caption":"Loops in Java"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/loops-in-java\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Java Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/java\/"},{"@type":"ListItem","position":3,"name":"Loops in Java &#8211; for, while, do-while"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/7f83c342f5d1632d6f7b4b0b0f447823","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/4cf3a74600d131330b8c481d519afd1574093ed89f6d3396a95393ad223eb7cd?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam1\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/6594","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=6594"}],"version-history":[{"count":20,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/6594\/revisions"}],"predecessor-version":[{"id":148301,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/6594\/revisions\/148301"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/78533"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=6594"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=6594"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=6594"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}