

{"id":123422,"date":"2024-10-25T18:00:42","date_gmt":"2024-10-25T12:30:42","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=123422"},"modified":"2024-10-25T18:32:49","modified_gmt":"2024-10-25T13:02:49","slug":"java-do-while-loop","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/java-do-while-loop\/","title":{"rendered":"Java do-while loop with Examples"},"content":{"rendered":"<p>Loops are essential constructs in Java. They facilitate the execution of a specific block of code either for a predetermined number of iterations or until a certain condition is satisfied. Three primary loop structures come to the fore in Java: the for loop, the while loop, and the do-while loop.<\/p>\n<p>Among these, the do-while loop holds a distinctive position, providing a unique approach to code repetition. Unlike the for and while loops, the do-while loop ensures that a designated code block is executed at least once before assessing the loop&#8217;s condition. This peculiarity makes it a valuable tool for scenarios in which an initial, mandatory execution is required, regardless of the outcome of the test condition.<\/p>\n<p>In this article, we will explore the do-while loop in Java, exploring its features, use cases, and advantages. By the end, you will have a comprehensive understanding of when and how to employ the do-while loop effectively in your Java programs, enhancing their flexibility and functionality.<\/p>\n<h2>Syntax of the Java do-while Loop<\/h2>\n<p><strong>The syntax of the Java do-while loop is:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">do {\r\n   \/\/ code block \r\n} while (test_expression);<\/pre>\n<ul>\n<li>The loop body contains code to execute repeatedly<\/li>\n<li>Update expression to increment\/decrement loop variable<\/li>\n<li>Condition check to determine if another iteration is required<\/li>\n<\/ul>\n<p>The test_expression must be evaluated using a boolean value, either true or false. It controls when the loop terminates.<\/p>\n<h3>Components of the do-while Loop in Java<\/h3>\n<ul>\n<li><b>Test Expression &#8211; <\/b>Evaluate a condition that controls the termination of the loop. Example: i &lt;= 10<\/li>\n<li><strong>Update Expression &#8211;<\/strong> Used to increment or decrement the loop variable. Example: i++<\/li>\n<\/ul>\n<h3>Step-by-step execution of the Java do-while loop<\/h3>\n<p>1. Control enters the loop<br \/>\n2. Statements in loop body are executed<br \/>\n3. Loop variable is updated via update expression<br \/>\n4. Condition check takes place<br \/>\n5. If condition is true, control goes back to loop body<br \/>\n6. If condition is false, loop terminates<br \/>\n7. Control flow moves out of loop<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2024\/04\/execution-of-the-do-while-loop.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-134342 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2024\/04\/execution-of-the-do-while-loop.webp\" alt=\"execution of the do while loop\" width=\"600\" height=\"310\" \/><\/a><\/p>\n<h3>Illustration of the Java do-while Loop<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class DoWhileExample {\r\n    public static void main(String[] args) {\r\n        int i = 1;\r\n        do {\r\n            System.out.println(i);\r\n            i++;\r\n        } while (i &lt; 1);\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\n1<\/p>\n<p>Though the test condition is false, the print statement executes once since the do-while checks the condition after the loop body.<\/p>\n<h3>Implementation Examples<\/h3>\n<p><strong>Example 1: Printing &#8220;DataFlair&#8221; 5 times<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class DoWhileExample {\r\n    public static void main(String[] args) {\r\n        int i = 1;\r\n        do {\r\n            System.out.println(\"DataFlair\");\r\n            i++;\r\n        } while (i &lt;= 5);\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nDataFlair<br \/>\nDataFlair<br \/>\nDataFlair<br \/>\nDataFlair<br \/>\nDataFlair<\/p>\n<p><strong>Example 2: Finding the summation of numbers from 1 to 100<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class SumExample {\r\n    public static void main(String[] args) {\r\n        int sum = 0;\r\n        int i = 1;\r\n\r\n        do {\r\n            sum += i;\r\n            i++;\r\n        } while (i &lt;= 100);\r\n\r\n        System.out.println(\"The sum of numbers from 1 to 100 is: \" + sum);\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\n<strong>The sum of numbers from 1 to 100 is:<\/strong> 5050<\/p>\n<p><strong>Example 3: do-while loop without curly braces {}<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class DoWhileWithoutBracesExample {\r\n    public static void main(String[] args) {\r\n        int i = 1;\r\n        do\r\n            System.out.println(\"Iteration \" + i);\r\n        while (i &lt;= 5);\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nIteration 1<br \/>\nIteration 2<br \/>\nIteration 3<br \/>\nIteration 4<br \/>\nIteration 5<\/p>\n<h3>Application of the do-while Loop in Java<\/h3>\n<p><strong>1. Menu Systems:<\/strong> Implementing interactive menus in software applications where the menu is displayed to the user at least once, ensuring they can choose further interaction.<\/p>\n<p><strong>2. Input Validation:<\/strong> Validating user input by repeatedly prompting the user until they enter valid data, ensuring the program doesn&#8217;t proceed with incorrect or invalid input.<\/p>\n<p><strong>3. Game Loops:<\/strong> In game development, the do-while loop is often used for game loops. This loop ensures that the game logic and rendering are executed at least once per frame before checking for conditions like game over.<\/p>\n<p><strong>4. Data Processing:<\/strong> Processing data or records, especially in batch processing scenarios, where you want to process each record until the end of the dataset is reached.<\/p>\n<p><strong>5. File Reading\/Writing:<\/strong> Read or write data to and from files, ensuring data integrity by performing at least one read or write operation before checking for the end of the file or completion.<\/p>\n<h3>Conclusion<\/h3>\n<p>In summary, the do-while loop in Java is a unique construct that ensures the execution of a code block at least once before checking the test condition. This feature is precious in scenarios where you must guarantee an initial execution, such as interactive menus or game development.<\/p>\n<p>Unlike the standard while loop, which evaluates the test condition first, the do-while loop executes the code block before checking the condition. This characteristic makes it an essential choice in scenarios where this post-condition execution is required, simplifying the coding process and ensuring a smoother user experience.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Loops are essential constructs in Java. They facilitate the execution of a specific block of code either for a predetermined number of iterations or until a certain condition is satisfied. Three primary loop structures&#46;&#46;&#46;<\/p>\n","protected":false},"author":86671,"featured_media":124267,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[19210,31082,7345,31081,31083,31078,8152,33190],"class_list":["post-123422","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-do-while-loop","tag-do-while-loop-in-java","tag-java","tag-java-do-while-loop","tag-java-do-while-loop-with-examples","tag-java-tutorials","tag-learn-java","tag-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>Java do-while loop with Examples - DataFlair<\/title>\n<meta name=\"description\" content=\"The do-while loop in Java is a unique construct that ensures the execution of a code block at least once before checking the test condition.\" \/>\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\/java-do-while-loop\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java do-while loop with Examples - DataFlair\" \/>\n<meta property=\"og:description\" content=\"The do-while loop in Java is a unique construct that ensures the execution of a code block at least once before checking the test condition.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/java-do-while-loop\/\" \/>\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=\"2024-10-25T12:30:42+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-10-25T13:02:49+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-do-while-loop.webp\" \/>\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\/webp\" \/>\n<meta name=\"author\" content=\"TechVidvan 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=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java do-while loop with Examples - DataFlair","description":"The do-while loop in Java is a unique construct that ensures the execution of a code block at least once before checking the test condition.","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\/java-do-while-loop\/","og_locale":"en_US","og_type":"article","og_title":"Java do-while loop with Examples - DataFlair","og_description":"The do-while loop in Java is a unique construct that ensures the execution of a code block at least once before checking the test condition.","og_url":"https:\/\/data-flair.training\/blogs\/java-do-while-loop\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2024-10-25T12:30:42+00:00","article_modified_time":"2024-10-25T13:02:49+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-do-while-loop.webp","type":"image\/webp"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/java-do-while-loop\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/java-do-while-loop\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/0e594f928e31fc96628ac40f6ae74f49"},"headline":"Java do-while loop with Examples","datePublished":"2024-10-25T12:30:42+00:00","dateModified":"2024-10-25T13:02:49+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-do-while-loop\/"},"wordCount":629,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-do-while-loop\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-do-while-loop.webp","keywords":["Do while Loop","do while loop in java","Java","java do while loop","java do while loop with examples","java tutorials","Learn Java","loop in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/java-do-while-loop\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/java-do-while-loop\/","url":"https:\/\/data-flair.training\/blogs\/java-do-while-loop\/","name":"Java do-while loop with Examples - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-do-while-loop\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-do-while-loop\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-do-while-loop.webp","datePublished":"2024-10-25T12:30:42+00:00","dateModified":"2024-10-25T13:02:49+00:00","description":"The do-while loop in Java is a unique construct that ensures the execution of a code block at least once before checking the test condition.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/java-do-while-loop\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/java-do-while-loop\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/java-do-while-loop\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-do-while-loop.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-do-while-loop.webp","width":1200,"height":628,"caption":"java do while loop"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/java-do-while-loop\/#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":"Java do-while loop with Examples"}]},{"@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\/0e594f928e31fc96628ac40f6ae74f49","name":"TechVidvan Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/c89190da3d4010c71ba476b618ab10fdc2335c82cdfa0ad5002d98d0f2473444?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/c89190da3d4010c71ba476b618ab10fdc2335c82cdfa0ad5002d98d0f2473444?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/c89190da3d4010c71ba476b618ab10fdc2335c82cdfa0ad5002d98d0f2473444?s=96&d=mm&r=g","caption":"TechVidvan Team"},"description":"TechVidvan Team provides high-quality content &amp; courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.","url":"https:\/\/data-flair.training\/blogs\/author\/test001\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/123422","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\/86671"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=123422"}],"version-history":[{"count":6,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/123422\/revisions"}],"predecessor-version":[{"id":143540,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/123422\/revisions\/143540"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/124267"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=123422"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=123422"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=123422"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}