

{"id":123418,"date":"2024-04-10T18:00:29","date_gmt":"2024-04-10T12:30:29","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=123418"},"modified":"2026-05-16T17:32:49","modified_gmt":"2026-05-16T12:02:49","slug":"java-while-loop","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/java-while-loop\/","title":{"rendered":"Java While Loop with Examples"},"content":{"rendered":"<p>The while loop is a control flow statement in Java that allows code to be executed repeatedly based on a given Boolean condition. The while loop is useful when the number of iterations is not known beforehand.<\/p>\n<p>A Java while loop enables repetitive execution of a block of code as long as the test condition evaluates to true. Till the condition is false, the loop iterates continuously. Once the condition becomes false, the loop terminates, and the control flow breaks out of the while loop.<\/p>\n<p>The key purpose of the Java while loop is to repeat a set of statements as long as the test condition holds. The while loop is ideally used when the number of iterations is not predetermined. For example, reading input from the user or a file line by line until no lines are left.<\/p>\n<p>The while loop in Java avoids the need to write many repeating if statements to execute code. While an if statement would need to be written multiple times for each iteration, the while loop compactly achieves the same behavior with better readability.<\/p>\n<p>Since the while loop depends on a condition to terminate, it is well-suited for scenarios where the exact number of iterations is unknown and depends on some business logic or external factor. Examples include &#8211; polling in multithreaded apps, reading files of variable length, user input loops, etc.<\/p>\n<h3>Syntax of the Java While Loop<\/h3>\n<p><strong>The syntax of the while loop contains 3 things mainly:<\/strong><\/p>\n<ul>\n<li><strong>Checking conditions:<\/strong> it is used with the while keyword to test the condition.<\/li>\n<li>Body of the loop enclosed in curly braces. It contains the statements that are to be performed when the testing condition is satisfied.<\/li>\n<li>At last, an updated condition, it is generally used to increment or decrement the variable passed to the while loop.<\/li>\n<\/ul>\n<p><strong>The syntax of the while loop in Java is straightforward:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">while (test_expression)\r\n{\r\n   \/\/ statements\r\n \r\n  update_expression;\r\n}<\/pre>\n<p>If the curly braces {} are not used with the while loop, then only the next immediate statement after the loop is considered part of the loop body. For most practical programs, curly braces are included to avoid confusion and define a block of statements for the loop.<\/p>\n<h3>Components of the While Loop in Java<\/h3>\n<h4>1) Test Expression in while loop<\/h4>\n<ul>\n<li><strong>Purpose:<\/strong> To evaluate the condition.<\/li>\n<li>Execution of the loop body and moving to the update expression depend on the test_expression.<\/li>\n<\/ul>\n<h4>2) Update Expression while loop<\/h4>\n<ul>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\"><strong>Purpose:<\/strong> Incrementing or decrementing the loop variable after executing the loop body.<\/span><\/li>\n<\/ul>\n<h3>Execution Flow of a Java While Loop<\/h3>\n<ul>\n<li>Entry into the while loop.<\/li>\n<li>Condition evaluation.<\/li>\n<li>Branching based on condition:<\/li>\n<\/ul>\n<p><strong>If the condition is true:<\/strong><\/p>\n<ul>\n<li>Flow enters the loop body.<\/li>\n<li>Statements inside the loop body are executed.<\/li>\n<li>Update_expression is executed.<\/li>\n<li>Control returns to the test condition for re-evaluation.<\/li>\n<\/ul>\n<p><strong>If the condition is false:<\/strong><\/p>\n<ul>\n<li>Flow exits the loop.<\/li>\n<li>Termination of the while loop (when the condition evaluates to false).<\/li>\n<\/ul>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2024\/04\/Execution-Flow-of-a-While-Loop-1.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-134340 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2024\/04\/Execution-Flow-of-a-While-Loop-1.webp\" alt=\"execution flow of a while loop\" width=\"600\" height=\"310\" \/><\/a><\/p>\n<h3>Examples of While Loops in Java<\/h3>\n<p>Let&#8217;s look at some examples to understand the usage of while loops.<\/p>\n<h4>Example 1: Printing \u201cDataFlair\u201d 5 times<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class DataFlairExample {\r\n    public static void main(String[] args) {\r\n        int i = 1;\r\n        while (i &lt;= 5) {\r\n            System.out.println(\"DataFlair\");\r\n            i++;\r\n        }\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nDataFlair<br \/>\nDataFlair<br \/>\nDataFlair<br \/>\nDataFlair<br \/>\nDataFlair<\/p>\n<ul>\n<li><strong>Time Complexity:<\/strong> O(n) where n = 5 is the constant number of iterations.<\/li>\n<li><strong>Auxiliary Space:<\/strong> O(1) since only two variables i and n are used.<\/li>\n<\/ul>\n<h4>Example 2: Finding the summation of numbers from 1 to 100<\/h4>\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        while (i &lt;= 100) {\r\n            sum += i;\r\n            i++;\r\n        }\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<ul>\n<li><strong>Time Complexity:<\/strong> O(n), where n = 100 is the constant number of iterations.<\/li>\n<li><strong>Auxiliary Space:<\/strong> O(1) since only three variables, sum, i, and n are used.<\/li>\n<\/ul>\n<h3>Conclusion<\/h3>\n<p>To sum up, Java&#8217;s while loops offer several notable features that make them a valuable tool for controlling program flow. These loops operate by repeatedly executing a specified code block as long as a designated test condition remains true, making them ideal for situations where the exact number of iterations is uncertain or depends on dynamic business logic.<\/p>\n<p>The flexibility of the test expression and update expression within while loops provides fine-grained control over the loop&#8217;s execution. Their versatility extends to various scenarios such as file processing, user input collection, and thread polling, where their use enhances the overall readability of code and creates a more efficient control flow compared to the repetition of if statements.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The while loop is a control flow statement in Java that allows code to be executed repeatedly based on a given Boolean condition. The while loop is useful when the number of iterations is&#46;&#46;&#46;<\/p>\n","protected":false},"author":86671,"featured_media":124265,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[31080,7345,31078,7744,31079,8152,16116],"class_list":["post-123418","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-execution-of-java-while-loop","tag-java","tag-java-tutorials","tag-java-while-loop","tag-java-while-loop-with-examples","tag-learn-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>Java While Loop with Examples - DataFlair<\/title>\n<meta name=\"description\" content=\"Java&#039;s while loops offer several notable features that make them a valuable tool for controlling program flow.\" \/>\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-while-loop\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java While Loop with Examples - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Java&#039;s while loops offer several notable features that make them a valuable tool for controlling program flow.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/java-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-04-10T12:30:29+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-05-16T12:02:49+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-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 While Loop with Examples - DataFlair","description":"Java's while loops offer several notable features that make them a valuable tool for controlling program flow.","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-while-loop\/","og_locale":"en_US","og_type":"article","og_title":"Java While Loop with Examples - DataFlair","og_description":"Java's while loops offer several notable features that make them a valuable tool for controlling program flow.","og_url":"https:\/\/data-flair.training\/blogs\/java-while-loop\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2024-04-10T12:30:29+00:00","article_modified_time":"2026-05-16T12:02:49+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-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-while-loop\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/java-while-loop\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/0e594f928e31fc96628ac40f6ae74f49"},"headline":"Java While Loop with Examples","datePublished":"2024-04-10T12:30:29+00:00","dateModified":"2026-05-16T12:02:49+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-while-loop\/"},"wordCount":691,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-while-loop\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-while-loop.webp","keywords":["execution of java while loop","Java","java tutorials","java while loop","java while loop with examples","Learn Java","while loop in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/java-while-loop\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/java-while-loop\/","url":"https:\/\/data-flair.training\/blogs\/java-while-loop\/","name":"Java While Loop with Examples - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-while-loop\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-while-loop\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-while-loop.webp","datePublished":"2024-04-10T12:30:29+00:00","dateModified":"2026-05-16T12:02:49+00:00","description":"Java's while loops offer several notable features that make them a valuable tool for controlling program flow.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/java-while-loop\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/java-while-loop\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/java-while-loop\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-while-loop.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-while-loop.webp","width":1200,"height":628,"caption":"java while loop"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/java-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 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\/123418","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=123418"}],"version-history":[{"count":10,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/123418\/revisions"}],"predecessor-version":[{"id":148302,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/123418\/revisions\/148302"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/124265"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=123418"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=123418"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=123418"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}