Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Aha 2

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 9

Skip to content

geeksforgeeks
Courses 90% Refund
Tutorials
Java
Practice
Contests

Sign In

Java Arrays
Java Strings
Java OOPs
Java Collection
Java 8 Tutorial
Java Multithreading
Java Exception Handling
Java Programs
Java Project
Java Collections Interview
Java Interview Questions
Java MCQs
Spring
Spring MVC
Spring Boot
Hibernate

Content Improvement Event


Share Your Experiences
Java Tutorial
Overview of Java
Basics of Java
Input/Output in Java
Flow Control in Java
Decision Making in Java (if, if-else, switch, break, continue, jump)
Java if statement with Examples
Java if-else
Java if-else-if ladder with Examples
Loops in Java
For Loop in Java
Java while loop with Examples
Java do-while loop with Examples
For-each loop in Java
Continue Statement in Java
Break statement in Java
Usage of Break keyword in Java
return keyword in Java
Operators in Java
Strings in Java
Arrays in Java
OOPS in Java
Inheritance in Java
Abstraction in Java
Encapsulation in Java
Polymorphism in Java
Constructors in Java
Methods in Java
Interfaces in Java
Wrapper Classes in Java
Keywords in Java
Access Modifiers in Java
Memory Allocation in Java
Classes of Java
Packages in Java
Java Collection Tutorial
Exception Handling in Java
Multithreading in Java
Synchronization in Java
File Handling in Java
Java Regex
Java IO
Java Networking
JDBC - Java Database Connectivity
Java 8 Features - Complete Tutorial
Java Backend DevelopmentCourse
Break statement in Java
Last Updated : 03 May, 2024
Break Statement is a loop control statement that is used to terminate the loop. As
soon as the break statement is encountered from within a loop, the loop iterations
stop there, and control returns from the loop immediately to the first statement
after the loop.
Syntax:

break;
Basically, break statements are used in situations when we are not sure about the
actual number of iterations for the loop or we want to terminate the loop based on
some condition.

Break: In Java, the break is majorly used for:

Terminate a sequence in a switch statement (discussed above).


To exit a loop.
Used as a “civilized” form of goto.
Use of break in Switch cases

import java.io.*;
// Use of break statement in switch
class GFG {
public static void main (String[] args) {
//assigning n as integer value
int n = 1;
//passing n to switch
// it will check n and display output accordingly
switch(n){
case 1:
System.out.println("GFG");
break;
case 2:
System.out.println("Second Case");
break;
default:
System.out.println("default case");
}
}
}

Output
GFG
Using break to exit a Loop

Using break, we can force immediate termination of a loop, bypassing the


conditional expression and any remaining code in the body of the loop.
Note: Break, when used inside a set of nested loops, will only break out of the
innermost loop.

using-break-to-exit-a-loop-in-java

Example:

// Java program to illustrate using


// break to exit a loop
class BreakLoopDemo {
public static void main(String args[])
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++) {
// terminate loop when i is 5.
if (i == 5)
break;

System.out.println("i: " + i);


}
System.out.println("Loop complete.");
}
}

Output
i: 0
i: 1
i: 2
i: 3
i: 4
Loop complete.
Time Complexity: O(1)

Auxiliary Space : O(1)

Using break as a Form of Goto

Java does not have a goto statement because it provides a way to branch in an
arbitrary and unstructured manner. Java uses the label. A Label is used to
identifies a block of code.
Syntax:

label:
{
statement1;
statement2;
statement3;
.
.
}
Now, break statement can be use to jump out of target block.
Note: You cannot break to any label which is not defined for an enclosing block.
Syntax:

break label;
Example:

// Java program to illustrate


// using break with goto
class BreakLabelDemo {
public static void main(String args[])
{
boolean t = true;

// label first
first : {

// Illegal statement here


// as label second is not
// introduced yet break second;
second : {
third : {
// Before break
System.out.println("Before the break statement");

// break will take the control out of


// second label
if (t)
break second;
System.out.println("This won't execute.");
}
System.out.println("This won't execute.");
}

// First block
System.out.println("This is after second block.");
}
}
}

Output
Before the break statement
This is after second block.
Time Complexity: O(1)

Auxiliary Space : O(1)

https://youtu.be/4uqb7-QpOAc?list=PLqM7alHXFySF5ErEHA1BXgibGg7uqmA4_

Related Articles:

Decision making in Java


Break statement in C++
Three 90 Challenge is back on popular demand! After processing refunds worth INR
1CR+, we are back with the offer if you missed it the first time. Get 90% course
fee refund in 90 days. Avail now!
Want to be a master in Backend Development with Java for building robust and
scalable applications? Enroll in Java Backend and Development Live Course by
GeeksforGeeks to get your hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or want to be a
Java Pro? This course equips you with all you need for building high-performance,
heavy-loaded backend systems in Java. Ready to take your Java Backend skills to the
next level? Enroll now and take your development career to sky highs.

Hello, amazing guys. Hope you're doing great.Play Video


author
harsh.agarwal0

62
Previous Article
Continue Statement in Java
Next Article
Usage of Break keyword in Java
Read More
Down Arrow
Similar Reads
Break and Continue statement in Java
The break and continue statements are the jump statements that are used to skip
some statements inside the loop or terminate the loop immediately without checking
the test expression. These statements can be used inside any loops such as for,
while, do-while loop. Break: The break statement in java is used to terminate from
the loop immediately. Wh
5 min read
Break Any Outer Nested Loop by Referencing its Name in Java
A nested loop is a loop within a loop, an inner loop within the body of an outer
one. Working: The first pass of the outer loop triggers the inner loop, which
executes to completion. Then the second pass of the outer loop triggers the inner
loop again. This repeats until the outer loop finishes. A break within either the
inner or outer loop would i
2 min read
Usage of Break keyword in Java
Break keyword is often used inside loops control structures and switch statements.
It is used to terminate loops and switch statements in java. When the break keyword
is encountered within a loop, the loop is immediately terminated and the program
control goes to the next statement following the loop. When the break keyword is
used in a nested loop
6 min read
Decision Making in Java (if, if-else, switch, break, continue, jump)
Decision Making in programming is similar to decision-making in real life. In
programming also face some situations where we want a certain block of code to be
executed when some condition is fulfilled. A programming language uses control
statements to control the flow of execution of a program based on certain
conditions. These are used to cause t
7 min read
Java if statement with Examples
Decision Making in Java helps to write decision-driven statements and execute a
particular set of code based on certain conditions.The Java if statement is the
most simple decision-making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition
is true then a block of stat
5 min read
Continue Statement in Java
Suppose a person wants code to execute for the values as per the code is designed
to be executed but forcefully the same user wants to skip out the execution for
which code should have been executed as designed above but will not as per the
demand of the user. In simpler words, it is a decision-making problem as per the
demand of the user. Real-Lif
6 min read
How to Use Callable Statement in Java to Call Stored Procedure?
The CallableStatement of JDBC API is used to call a stored procedure. A Callable
statement can have output parameters, input parameters, or both. The prepareCall()
method of connection interface will be used to create CallableStatement object.
Following are the steps to use Callable Statement in Java to call Stored Procedure:
1) Load MySQL driver a
2 min read
Import Statement in Java
Import statement in Java is helpful to take a class or all classes visible for a
program specified under a package, with the help of a single statement. It is
pretty beneficial as the programmer do not require to write the entire class
definition. Hence, it improves the readability of the program. This article focuses
on the import statements used
8 min read
Library Management System Using Switch Statement in Java
Here we are supposed to design and implement a simple library management system
using a switch statement in Java, where have operated the following operations Add
a new book, Check Out a book, display specific book status, search specific book,
and display book details using different classes. Follow the given link to build
the Library Management S
9 min read
Enhancements for Switch Statement in Java 13
Java 12 improved the traditional switch statement and made it more useful. Java 13
further introduced new features. Before going into the details of new features,
let's have a look at the drawbacks faced by the traditional Switch statement.
Problems in Traditional Switch1. Default fall through due to missing break:The
default fall-through behavior
5 min read
Article Tags :
Java
Practice Tags :
Java
three90RightbarBannerImg
course-img
215k+ interested Geeks
Master Java Programming - Complete Beginner to Advanced
Explore
course-img
214k+ interested Geeks
JAVA Backend Development - Live
Explore
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Explore
geeksforgeeks-footer-logo
Corporate & Communications Address:- A-143, 9th Floor, Sovereign Corporate Tower,
Sector- 136, Noida, Uttar Pradesh (201305) | Registered Address:- K 061, Tower K,
Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh,
201305
GFG App on Play Store
GFG App on App Store
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By
using our site, you acknowledge that you have read and understood our Cookie Policy
& Privacy Policy
Got It !
Lightbox

You might also like