{"id":88596,"date":"2023-10-04T19:00:58","date_gmt":"2023-10-04T13:30:58","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=88596"},"modified":"2023-10-04T19:00:58","modified_gmt":"2023-10-04T13:30:58","slug":"java-break-statement","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/java-break-statement\/","title":{"rendered":"Java Break Statement"},"content":{"rendered":"<p>In Java, the break statement is used within loop and switch statements to control the flow of execution by immediately exiting the loop or switch block it is placed in. It is used to terminate the current loop iteration or to exit the switch block prematurely.<\/p>\n<p>The break statement is a control flow mechanism that helps improve the efficiency and readability of your code by allowing you to exit loops or switch blocks when specific conditions are met.<\/p>\n<p>It&#8217;s a powerful tool for managing program flow and making your code more responsive to different scenarios.<\/p>\n<p>A break statement is a versatile tool that allows you to control the flow of your code and make it more responsive to different conditions and scenarios. It&#8217;s commonly used to optimize loop execution, handle cases efficiently, and manage program flow. Here&#8217;s how the break statement works in different contexts:<\/p>\n<h2>Within Loops:<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class DataFlair{\n    public static void main(String[] args) {\n        for (int i = 1; i &lt; 10; i++) {\n            if (i == 6) {\n                break; \/\/ Exit the loop when i is 6\n            }\n            System.out.println(i);\n        }\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>1<br \/>\n2<br \/>\n3<br \/>\n4<br \/>\n5<\/p>\n<p><strong>Time Complexity:<\/strong> O(1)<\/p>\n<p><strong>Auxiliary Space:<\/strong> O(1)<\/p>\n<h4>Explanation:<\/h4>\n<p>In this example, the loop will iterate from 0 to 2 and then exit when i becomes 3 due to the break statement.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/the-loop-will-iterate.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-88705 size-full\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/the-loop-will-iterate.webp\" alt=\"the loop will iterate\" width=\"500\" height=\"284\" \/><\/a><\/p>\n<h3>Break with do-while loop:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class DataFlair {\n        public static void main(String[] args) {\n            Scanner scanner = new Scanner(System.in);\n            do {\n                System.out.print(\"Enter a number (or -1 to exit): \");\n                int num = scanner.nextInt();\n                if (num == -1) {\n                    System.out.println(\"Exiting the loop.\");\n                    break; \/\/ Exit the loop when -1 is entered\n                }\n                System.out.println(\"You entered: \" + num);\n            } while (true);\n            System.out.println(\"Loop has been stopped.\");\n      }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Enter a number (or -1 to exit):<\/strong> 3<\/p>\n<p><strong>You entered:<\/strong> 3<\/p>\n<p><strong>Enter a number (or -1 to exit):<\/strong> 22<\/p>\n<p><strong>You entered:<\/strong> 22<\/p>\n<p><strong>Enter a number (or -1 to exit):<\/strong> 5<\/p>\n<p><strong>You entered:<\/strong> 5<\/p>\n<p><strong>Enter a number (or -1 to exit):<\/strong> -1<\/p>\n<p>Exiting the loop.<\/p>\n<p>The loop has been stopped.<\/p>\n<p><strong>Time Complexity:<\/strong> Unbounded or Undefined (depends on user input)<\/p>\n<p><strong>Auxiliary Space:<\/strong> O(1)<\/p>\n<h4>Explanation:<\/h4>\n<p>In this example, the program uses a do-while loop to repeatedly prompt the user to enter a number. If the user enters -1, the program displays a message and exits the loop using the break statement. Otherwise, it displays the entered number and continues looping.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Break-with-do-while-loop.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88706\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Break-with-do-while-loop.webp\" alt=\"Break with do-while loop\" width=\"500\" height=\"361\" \/><\/a><\/p>\n<h3>Within Switch Statements :<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class DataFlair{\n    public static void main(String[] args) {\n        int dayOfWeek = 3;\n        switch (dayOfWeek) {\n            case 1:\n                System.out.println(\"Monday\"); \n                break;\n            case 2:\n                System.out.println(\"Tuesday\");\n                break;\n            case 3:\n                System.out.println(\"Wednesday\");\n                break; \/\/ Exit the switch block after printing \"Wednesday\"\n           default:\n            System.out.println(\"Other day\");\n        }\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>Wednesday<\/p>\n<p><strong>Time Complexity:<\/strong> O(1)<\/p>\n<p><strong>Auxiliary Space:<\/strong> O(1)<\/p>\n<h4>Explanation:<\/h4>\n<p>In this example, when dayOfWeek is 3, the case for Wednesday will execute, and then the break statement will exit the switch block.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Within-Switch-Statements.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88707\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Within-Switch-Statements.webp\" alt=\"Within Switch Statements\" width=\"500\" height=\"301\" \/><\/a><\/p>\n<h3>Using Break with Labeled Statements<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class DataFlair{\n    public static void main(String[] args) {\n        outerloop: for (int i = 0; i &lt; 3; i++) {\n            for (int j = 0; j &lt; 3; j++) {\n                if (i == 1 &amp;&amp; j == 1) {\n                    break outerLoop; \/\/ Exit both loops\n                }\n                System.out.println(\"i: \" + i + \", j: \" + j);\n            }\n        }\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>i: 0, j: 0<\/p>\n<p>i: 0, j: 1<\/p>\n<p>i: 0, j: 2<\/p>\n<p>i: 1, j: 0<\/p>\n<p><strong>Time Complexity:<\/strong> O(1)<\/p>\n<p><strong>Auxiliary Space:<\/strong> O(1)<\/p>\n<h4>Explanation:<\/h4>\n<p>In this example, the labelled break statement breaks out of both nested loops when i is 1 and j is 1.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Using-Break-with-Labeled-Statements.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88708\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Using-Break-with-Labeled-Statements.webp\" alt=\"Using Break with Labeled Statements\" width=\"500\" height=\"429\" \/><\/a><\/p>\n<p>A potent control flow tool, the break statement enables you to govern the flow of your program and escape loops or switch blocks in response to certain situations.<\/p>\n<h3>Handling Special Cases:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"> class DataFlair {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        while (true) {\n            System.out.print(\"Enter your age: \");\n            int age = scanner.nextInt();\n            if (age &lt; 0) {\n                System.out.println(\"Invalid age. Please enter a non-negative value.\");\n                break; \/\/ Exit the loop on invalid input\n            }\n            if (age &gt;= 18) {\n                System.out.println(\"You are an adult.\");\n            } \n            else {\n                System.out.println(\"You are a minor.\");\n            }\n        }\n        System.out.println(\"Exiting the program.\");\n    }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Enter your age:<\/strong> 20<\/p>\n<p>You are an adult.<\/p>\n<p><strong>Enter your age:<\/strong> 8<\/p>\n<p>You are a minor.<\/p>\n<p><strong>Enter your age:<\/strong> -2<\/p>\n<p>Invalid age. Please enter a non-negative value.<\/p>\n<p>Exiting the program.<\/p>\n<p><strong>Time Complexity:<\/strong> O(1)<\/p>\n<p><strong>Auxiliary Space:<\/strong> O(1)<\/p>\n<h4>Explanation:<\/h4>\n<p>In this example, the program prompts the user to enter their age. If the user enters a negative value, the program displays an error message and exits the loop using the break statement. Otherwise, it determines whether the user is an adult (age 18 or older) or a minor (age below 18) and continues looping.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Handling-Special-Cases.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-88709\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Handling-Special-Cases.webp\" alt=\"Handling Special Cases\" width=\"500\" height=\"397\" \/><\/a><\/p>\n<h3>Stopping Infinite Loop:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class DataFlair {\n        public static void main(String[] args) {\n            Scanner scanner = new Scanner(System.in);\n            while (true) {\n                System.out.print(\"Enter 'exit' to stop the loop: \");\n                String userInput = scanner.nextLine();\n                if (userInput.equalsIgnoreCase(\"exit\")) {\n                    System.out.println(\"Exiting the loop.\");\n                    break; \/\/ Exit the loop when the user enters 'exit'\n                }\n                System.out.println(\"Looping... You entered: \" + userInput);\n            }\n            System.out.println(\"Loop has been stopped.\");\n        }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><strong>Enter &#8216;exit&#8217; to stop the loop:<\/strong> TechVidvan<\/p>\n<p><strong>Looping&#8230; You entered:<\/strong> TechVidvan<\/p>\n<p><strong>Enter &#8216;exit&#8217; to stop the loop:<\/strong> Java course<\/p>\n<p><strong>Looping&#8230; You entered<\/strong> the Java course<\/p>\n<p><strong>Enter &#8216;exit&#8217; to stop the loop:<\/strong> break statement demo<\/p>\n<p><strong>Looping&#8230; You entered:<\/strong> break statement demo<\/p>\n<p><strong>Enter &#8216;exit&#8217; to stop the loop:<\/strong> exit<\/p>\n<p>Exiting the loop.<\/p>\n<p>The loop has been stopped.<\/p>\n<p><strong>Time Complexity:<\/strong> Unbounded or Undefined (depends on user input)<\/p>\n<p><strong>Auxiliary Space:<\/strong> O(1)<\/p>\n<h4>Explanation:<\/h4>\n<p>In this example, the program creates an infinite loop that prompts the user to enter some input. If the user enters the word &#8220;exit&#8221; (case-insensitive), the program displays a message and exits the loop using the break statement.<\/p>\n<h3>Conclusion<\/h3>\n<p>The reserved keyword in Java is a break. It is one of the keywords used by programmers to immediately end the execution of a loop or conditional expression and shift the program execution control to the following step. Under the decision-making statements is its better use case scenario.<\/p>\n<p>You may skip pointless iterations by using break statements. The program&#8217;s overall processing time and performance may be improved by doing this. Therefore, when we are sure that we don&#8217;t need to iterate anymore, we must utilize the break statement.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Java, the break statement is used within loop and switch statements to control the flow of execution by immediately exiting the loop or switch block it is placed in. It is used to&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":88704,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[5224,1722,296,5225,250],"class_list":["post-88596","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-learn-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java Break Statement - TechVidvan<\/title>\n<meta name=\"description\" content=\"The Java Break Statement is used within loop and switch statements to control the flow of execution by immediately exiting.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/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 - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"The Java Break Statement is used within loop and switch statements to control the flow of execution by immediately exiting.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/java-break-statement\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-10-04T13:30:58+00:00\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\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=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java Break Statement - TechVidvan","description":"The Java Break Statement is used within loop and switch statements to control the flow of execution by immediately exiting.","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:\/\/techvidvan.com\/tutorials\/java-break-statement\/","og_locale":"en_US","og_type":"article","og_title":"Java Break Statement - TechVidvan","og_description":"The Java Break Statement is used within loop and switch statements to control the flow of execution by immediately exiting.","og_url":"https:\/\/techvidvan.com\/tutorials\/java-break-statement\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2023-10-04T13:30:58+00:00","author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/java-break-statement\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-break-statement\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Java Break Statement","datePublished":"2023-10-04T13:30:58+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-break-statement\/"},"wordCount":682,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-break-statement\/#primaryimage"},"thumbnailUrl":"","keywords":["break statement","break statement in java","java","java break statement","Learn Java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/java-break-statement\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/java-break-statement\/","url":"https:\/\/techvidvan.com\/tutorials\/java-break-statement\/","name":"Java Break Statement - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-break-statement\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-break-statement\/#primaryimage"},"thumbnailUrl":"","datePublished":"2023-10-04T13:30:58+00:00","description":"The Java Break Statement is used within loop and switch statements to control the flow of execution by immediately exiting.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-break-statement\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/java-break-statement\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/java-break-statement\/#primaryimage","url":"","contentUrl":""},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/java-break-statement\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Java Break Statement"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/88596","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=88596"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/88596\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=88596"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=88596"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=88596"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}