

{"id":123425,"date":"2024-10-28T18:00:43","date_gmt":"2024-10-28T12:30:43","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=123425"},"modified":"2024-10-28T18:13:09","modified_gmt":"2024-10-28T12:43:09","slug":"java-break-statement","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/java-break-statement\/","title":{"rendered":"Java Break Statement with Examples"},"content":{"rendered":"<p>The break statement is a vital control flow statement in Java that terminates the execution of loops or switch statements prematurely. In this article, we will learn about the break statement in detail through examples\u2014its syntax, usage in different contexts, complexity analysis, and more.<\/p>\n<p>The break statement allows you to exit from a code block, such as a loop or a switch statement. When encountered inside one of these blocks, the break statement immediately terminates the current iteration and transfers control to the following statement following the block.<\/p>\n<h2>The essential purposes served by the break statement are:<\/h2>\n<ul>\n<li>Terminating loops prematurely before their average completion.<\/li>\n<li>Branching out of conditional blocks in switch statements.<\/li>\n<\/ul>\n<p>The syntax of the break statement is simple &#8211;<strong> a semicolon follows the break keyword:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">break;<\/pre>\n<p>Let&#8217;s look at some common scenarios where the break statement is used in Java programs.<\/p>\n<h3><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2024\/04\/break-statement-in-java-example.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-134346 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2024\/04\/break-statement-in-java-example.webp\" alt=\"break statement in java example\" width=\"600\" height=\"422\" \/><\/a><\/h3>\n<h3>Uses of the Break Statement in Java<\/h3>\n<h4>1) Terminating a Switch Case<\/h4>\n<p>The break statement is commonly used to terminate a particular case in a switch statement. Without a break statement, control flow would &#8220;fall through&#8221; to subsequent cases until a break or the end of the switch block is reached.<\/p>\n<p><strong>Here is an example demonstrating the use of break-in switch cases:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class DayOfWeek {\r\n    public static void main(String[] args) {\r\n        int day = 3;\r\n\r\n        switch (day) {\r\n            case 1:\r\n                System.out.println(\"Monday\");\r\n                break; \/\/ Terminates this case\r\n\r\n            case 2:\r\n                System.out.println(\"Tuesday\");\r\n                break;\r\n\r\n            case 3:\r\n                System.out.println(\"Wednesday\");\r\n                break;\r\n\r\n            default:\r\n                System.out.println(\"Invalid day!\");\r\n        }\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nWednesday<\/p>\n<p>After printing the day, the break statements ensure that only that case is executed before jumping out of the switch block.<\/p>\n<h4>2) Exiting a Loop Prematurely<\/h4>\n<p>The break statement is commonly used to terminate loop execution based on some condition. This allows the loop to exit prematurely before its normal completion.<\/p>\n<p><strong>Here is an example to demo using a break to exit a while loop:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class WhileLoopExample {\r\n    public static void main(String[] args) {\r\n        int i = 1;\r\n        while (true) {\r\n            if (i &gt; 3) {\r\n                break;\r\n            }\r\n            System.out.println(i);\r\n            i++;\r\n        }\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\n1<br \/>\n2<br \/>\n3<\/p>\n<p>The break statement is used to exit the while loop when the value of i becomes greater than 3.<\/p>\n<p>One important point is that when nested loops are present, a break statement only terminates the innermost loop containing it.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2024\/04\/exiting-a-loop-prematurely.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-134348 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2024\/04\/exiting-a-loop-prematurely.webp\" alt=\"exiting-a-loop-prematurely\" width=\"600\" height=\"444\" \/><\/a><\/p>\n<h4>3) Using Break as a Form of Goto<\/h4>\n<p>Unlike languages like C, Java does not have an explicit goto statement. The break statement is sometimes used to simulate goto behavior in Java by &#8220;jumping out&#8221; of labeled blocks.<\/p>\n<p><strong>Labeling Blocks: <\/strong>We can label any block of code by prefixing it with an identifier followed by a colon:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">block_label: {\r\n  \/\/ Code statements\r\n}<\/pre>\n<p><strong>For example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int[][] arr = {\r\n  {1, 2, 3}, \r\n  {4, 5, 6}  \r\n};\r\n\r\nint sum = 0;\r\n\r\nrow_loop: \r\nfor(int i=0; i&lt;arr.length; i++) {\r\n  for(int j=0; j&lt;arr[i].length; j++) {\r\n    if(arr[i][j] % 2 != 0) {\r\n      continue row_loop; \r\n    }\r\n    sum += arr[i][j];\r\n  }\r\n}\r\n\r\nSystem.out.println(\"Sum of even elements = \" + sum);<\/pre>\n<p><strong>Output: <\/strong><br \/>\n\/\/ Sum of even elements = 12<\/p>\n<p>Here row_loop is the label for the outer for loop.<\/p>\n<p><strong>Breaking to a Label:<\/strong> To exit the labeled block, we can use the break statement with a label name.<\/p>\n<p><strong>For example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">block_label: {\r\n  \/\/ Some code\r\n  \r\n  if(some_condition) {\r\n    break block_label;\r\n  }\r\n  \r\n  \/\/ Rest of code\r\n}<\/pre>\n<p>When the break with the label is encountered, the control jumps just after the labeled block.<\/p>\n<p><strong>Let&#8217;s add a break with label to the multi-dimensional array example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">public class MultiDimensionalArrayExample {\r\n    public static void main(String[] args) {\r\n        int[][] multiArray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };\r\n        int targetValue = 5;\r\n        boolean found = false;\r\n\r\n\r\n        searchLoop: \/\/ Label for the outer loop\r\n        for (int i = 0; i &lt; multiArray.length; i++) {\r\n            for (int j = 0; j &lt; multiArray[i].length; j++) {\r\n                if (multiArray[i][j] == targetValue) {\r\n                    found = true;\r\n                    break searchLoop; \/\/ Breaks out of both loops\r\n                }\r\n            }\r\n        }\r\n\r\n\r\n        if (found) {\r\n            System.out.println(\"Value \" + targetValue + \" found in the multi-dimensional array.\");\r\n        } else {\r\n            System.out.println(\"Value \" + targetValue + \" not found in the multi-dimensional array.\");\r\n        }\r\n    }\r\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nValue 5 is found in the multi-dimensional array.<\/p>\n<p>The break statement with the searchLoop label terminates the outer for loop&#8217;s execution when an odd element is encountered in the array.<\/p>\n<p>A key point to note is that labels have function scope in Java. We cannot jump out of a function using a label defined outside it.<\/p>\n<h3>Complexity Analysis<\/h3>\n<ul>\n<li><strong>Time Complexity:<\/strong> The break statement runs in constant O(1) time. Any overhead depends on where it is used.<\/li>\n<li><span style=\"margin: 0px;padding: 0px\"><strong>Space Complexity:<\/strong> The break statement does not require additional memory, so it takes constant O(1) auxiliary space.<\/span><\/li>\n<\/ul>\n<h3>Conclusion<\/h3>\n<p>In conclusion, the break statement in Java plays a crucial role in controlling the execution flow in loops and switch statements.<\/p>\n<p>This article thoroughly explored its syntax and usage in various contexts. It demonstrated how the break statement could terminate specific cases in switch statements, premature exit loops based on conditions, and even simulate a form of &#8220;goto&#8221; behaviour using labelled blocks.<\/p>\n<p>The article also briefly touched upon the complexity analysis of the break statement, emphasizing its low time and space complexities. In Java, the break statement proves to be an essential tool for programmers to efficiently manage the flow of their code, ensuring that it behaves as desired in different scenarios.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The break statement is a vital control flow statement in Java that terminates the execution of loops or switch statements prematurely. In this article, we will learn about the break statement in detail through&#46;&#46;&#46;<\/p>\n","protected":false},"author":86671,"featured_media":124270,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[19213,2174,7345,31084,31085,31078,8152],"class_list":["post-123425","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-break-statement","tag-break-statement-in-java","tag-java","tag-java-break-statement","tag-java-break-statement-with-examples","tag-java-tutorials","tag-learn-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java Break Statement with Examples - DataFlair<\/title>\n<meta name=\"description\" content=\"The break statement in Java plays a crucial role in controlling the flow of execution in loops and switch statements.\" \/>\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-break-statement\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Break Statement with Examples - DataFlair\" \/>\n<meta property=\"og:description\" content=\"The break statement in Java plays a crucial role in controlling the flow of execution in loops and switch statements.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/java-break-statement\/\" \/>\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-28T12:30:43+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-10-28T12:43:09+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-break-statement.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 Break Statement with Examples - DataFlair","description":"The break statement in Java plays a crucial role in controlling the flow of execution in loops and switch statements.","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-break-statement\/","og_locale":"en_US","og_type":"article","og_title":"Java Break Statement with Examples - DataFlair","og_description":"The break statement in Java plays a crucial role in controlling the flow of execution in loops and switch statements.","og_url":"https:\/\/data-flair.training\/blogs\/java-break-statement\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2024-10-28T12:30:43+00:00","article_modified_time":"2024-10-28T12:43:09+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-break-statement.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-break-statement\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/java-break-statement\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/0e594f928e31fc96628ac40f6ae74f49"},"headline":"Java Break Statement with Examples","datePublished":"2024-10-28T12:30:43+00:00","dateModified":"2024-10-28T12:43:09+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-break-statement\/"},"wordCount":645,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-break-statement\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-break-statement.webp","keywords":["Break Statement","break statement in java","Java","java break statement","java break statement with examples","java tutorials","Learn Java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/java-break-statement\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/java-break-statement\/","url":"https:\/\/data-flair.training\/blogs\/java-break-statement\/","name":"Java Break Statement with Examples - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/java-break-statement\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/java-break-statement\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-break-statement.webp","datePublished":"2024-10-28T12:30:43+00:00","dateModified":"2024-10-28T12:43:09+00:00","description":"The break statement in Java plays a crucial role in controlling the flow of execution in loops and switch statements.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/java-break-statement\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/java-break-statement\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/java-break-statement\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-break-statement.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/11\/java-break-statement.webp","width":1200,"height":628,"caption":"java break statement"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/java-break-statement\/#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 Break Statement 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\/123425","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=123425"}],"version-history":[{"count":8,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/123425\/revisions"}],"predecessor-version":[{"id":143544,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/123425\/revisions\/143544"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/124270"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=123425"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=123425"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=123425"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}