Java break, continue, and return Statements
Learn how to control the flow of your loops and methods. Use break, continue, and return to stop loops, skip iterations, and exit functions.
What are Flow Control Statements?
Flow control statements let you control how your program runs. They help you stop loops before they naturally end, skip certain iterations, or exit methods early. Think of them as remote controls for your loops and functions - you can pause, skip, or stop them whenever you want.
- break: Stops a loop completely and exits it immediately
- continue: Skips the current iteration and moves to the next one
- return: Exits a method and optionally sends back a value
Think of it this way: Imagine a train going through 10 stations. break means the train stops and gets off the track. continue means the train skips the current station but keeps going. return means the train reaches its destination and sends back any cargo.
The break Statement
The break statement completely exits a loop. When Java encounters break, the loop stops immediately, and the program continues with code after the loop. Break is useful when you find what you're looking for and don't need to continue looping.
Example 1: break with for loop
public class BreakExample1 {
public static void main(String[] args) {
System.out.println("Counting from 1 to 10:");
for (int i = 1; i <= 10; i++) {
if (i == 5) {
System.out.println("Found 5! Stopping loop.");
break; // Exit the loop when i equals 5
}
System.out.println("Number: " + i);
}
System.out.println("Loop ended. Program continues here.");
}
}
Counting from 1 to 10: Number: 1 Number: 2 Number: 3 Number: 4 Found 5! Stopping loop. Loop ended. Program continues here.
How it works:
- Loop starts counting: 1, 2, 3, 4
- When i equals 5, the condition if (i == 5) is true
- break exits the loop immediately
- Numbers 6-10 are never printed
- Program continues after the loop
Example 2: break to find a value
public class BreakExample2 {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50, 60};
int searchFor = 40;
boolean found = false;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == searchFor) {
System.out.println("Found " + searchFor + " at position " + i);
found = true;
break; // Stop searching once found
}
}
if (!found) {
System.out.println(searchFor + " not found in array.");
}
}
}
Found 40 at position 3
Real-world use: This searches an array for a value. Once the value 40 is found, break stops the search immediately instead of checking all remaining elements.
Example 3: break with while loop
public class BreakExample3 {
public static void main(String[] args) {
int count = 0;
while (true) { // Infinite loop
count++;
System.out.println("Attempt: " + count);
if (count == 3) {
System.out.println("Success! Exiting loop.");
break; // Exit the infinite loop
}
}
System.out.println("Program continues after loop.");
}
}
Attempt: 1 Attempt: 2 Attempt: 3 Success! Exiting loop. Program continues after loop.
Key Point: break exits the innermost loop. If you have nested loops (loops inside loops), break only exits the current loop, not all of them.
The continue Statement
The continue statement skips the rest of the current iteration and jumps to the next one. The loop doesn't stop - it just skips the code after continue and starts the next cycle. Use continue when you want to skip certain values but keep looping.
Example 1: continue to skip even numbers
public class ContinueExample1 {
public static void main(String[] args) {
System.out.println("Printing only odd numbers from 1 to 10:");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println("Number: " + i);
}
}
}
Printing only odd numbers from 1 to 10: Number: 1 Number: 3 Number: 5 Number: 7 Number: 9
How it works:
- When i = 1 (odd): skip the continue, print 1
- When i = 2 (even): i % 2 == 0 is true, so continue executes
- continue skips the print statement and goes to i = 3
- Loop continues with 3, 4, 5... but only prints odd numbers
Example 2: continue to skip invalid input
public class ContinueExample2 {
public static void main(String[] args) {
int[] scores = {45, 85, 30, 92, 55, 88};
System.out.println("Processing passing scores (50+):");
for (int i = 0; i < scores.length; i++) {
if (scores[i] < 50) {
continue; // Skip failing scores
}
System.out.println("Score " + scores[i] + " is passing!");
}
}
}
Processing passing scores (50+): Score 85 is passing! Score 92 is passing! Score 88 is passing!
Real-world use: When processing data, continue skips items that don't meet requirements (scores below 50) and only processes valid ones.
Example 3: continue in while loop
public class ContinueExample3 {
public static void main(String[] args) {
int num = 0;
while (num < 10) {
num++;
if (num == 5) {
System.out.println("Skipping 5...");
continue; // Skip when num is 5
}
System.out.println("Number: " + num);
}
}
}
Number: 1 Number: 2 Number: 3 Number: 4 Skipping 5... Number: 6 Number: 7 Number: 8 Number: 9 Number: 10
break vs continue:
break = Stop the entire loop
continue = Skip this iteration, keep looping
The return Statement
The return statement exits a method immediately and optionally sends back a value to whoever called the method. When return is executed, everything after it in that method is ignored. Return is used to finish a method's job and give back a result.
Example 1: return with a value
public class ReturnExample1 {
// Method that returns a value
public static int add(int a, int b) {
int sum = a + b;
return sum; // Exit method and send back the sum
// System.out.println("This line never runs!");
}
public static void main(String[] args) {
int result = add(5, 3);
System.out.println("Result: " + result);
}
}
Result: 8
How it works:
- add(5, 3) is called from main
- Inside add: sum = 5 + 3 = 8
- return sum exits the method and sends 8 back
- In main, result receives the value 8
- Any code after return is never executed
Example 2: Early return to exit method
public class ReturnExample2 {
// Method to check if age is adult
public static boolean isAdult(int age) {
if (age < 18) {
return false; // Exit early if not adult
}
return true; // Exit with true if adult
}
public static void main(String[] args) {
System.out.println("Age 16 is adult? " + isAdult(16));
System.out.println("Age 20 is adult? " + isAdult(20));
}
}
Age 16 is adult? false Age 20 is adult? true
How it works:
- isAdult(16): age < 18 is true, so return false immediately
- The second return statement is never reached
- isAdult(20): age < 18 is false, so continue to return true
- Early return stops the method without running the rest
Example 3: void method with return (no value)
public class ReturnExample3 {
// Method with void (no return value)
public static void printGrade(int score) {
if (score < 50) {
System.out.println("Grade: F");
return; // Exit the method
}
if (score < 70) {
System.out.println("Grade: C");
return;
}
if (score < 90) {
System.out.println("Grade: B");
return;
}
System.out.println("Grade: A");
}
public static void main(String[] args) {
printGrade(45);
printGrade(65);
printGrade(88);
printGrade(95);
}
}
Grade: F Grade: C Grade: B Grade: A
How it works:
- void methods don't return a value, just return (with no value)
- For score 45: first if is true, prints "F", then return exits the method
- Other score checks don't run because we already returned
- return exits even void methods to prevent running unnecessary code
return vs break vs continue:
break = Exits loop
continue = Skips to next iteration of loop
return = Exits the entire method
Quick Comparison: break, continue, and return
break Statement
What it does: Exits the entire loop completely
Used in: for loops, while loops, switch statements
Example: When you find what you're searching for and don't need to continue looping
continue Statement
What it does: Skips the rest of current iteration and goes to next one
Used in: for loops, while loops
Example: When you want to process only certain items (skip odd numbers, process only passing scores)
return Statement
What it does: Exits the entire method and optionally returns a value
Used in: Any method (not just loops)
Example: When you've finished calculating a result and want to send it back to the caller
Which One to Use?
Use break: To stop looping early
Use continue: To skip certain items but keep looping
Use return: To exit a method and send back results
Common Mistakes to Avoid
Mistake 1: Using break outside a loop
// WRONG: break can only be used in loops
// if (age > 18) {
// break; // ERROR! Not in a loop
// }
// CORRECT: Use break only inside loops
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // OK, inside a loop
}
}
Explanation: break can only be used inside loops (for, while, do-while). Using it elsewhere causes an error.
Mistake 2: Forgetting to update loop variable with continue
// WRONG: Infinite loop!
int i = 0;
while (i < 5) {
if (i == 2) {
continue; // Skips i++, creating infinite loop
}
System.out.println(i);
i++;
}
// CORRECT: Update variable before continue
int i = 0;
while (i < 5) {
if (i == 2) {
i++; // Update first
continue;
}
System.out.println(i);
i++;
}
Explanation: With continue, make sure the loop counter updates before continue, or you'll get an infinite loop.
Mistake 3: Code after return that never runs
// NOT necessarily wrong, but unnecessary
public static int getValue() {
return 5;
System.out.println("This never runs!"); // Unreachable code
}
// BETTER: Put return at the end
public static int getValue() {
System.out.println("Getting value...");
return 5;
}
Explanation: Any code after return never executes. Put return at the end of your method logic.
Summary of Mistakes:
1. break/continue only work in loops
2. With continue in while loops, update counter before continue
3. Code after return never runs
Real-World Example: User Authentication System
Here's a practical program that uses break, continue, and return together:
Example: Login Attempt Counter
public class LoginSystem {
// Method to validate password
public static boolean validatePassword(String password) {
if (password == null || password.length() < 6) {
return false; // Exit early if invalid
}
return true;
}
// Method to process login attempts
public static void attemptLogin() {
String[] passwords = {"pass", "weak", "password123", "abc", "secure456"};
int maxAttempts = 3;
int successCount = 0;
System.out.println("=== Login System ===");
System.out.println("Maximum successful attempts: " + maxAttempts);
System.out.println();
for (int i = 0; i < passwords.length; i++) {
String currentPassword = passwords[i];
// Skip invalid passwords
if (!validatePassword(currentPassword)) {
System.out.println("Attempt " + (i + 1) + ": '" + currentPassword + "' - Too weak!");
continue; // Skip to next password without counting
}
// Process valid password
System.out.println("Attempt " + (i + 1) + ": '" + currentPassword + "' - SUCCESS!");
successCount++;
// Break if we've had enough successes
if (successCount >= maxAttempts) {
System.out.println("Maximum successful attempts reached!");
break; // Stop processing more passwords
}
}
System.out.println("\nTotal successful logins: " + successCount);
}
public static void main(String[] args) {
attemptLogin();
}
}
=== Login System === Maximum successful attempts: 3 Attempt 1: 'pass' - Too weak! Attempt 2: 'weak' - Too weak! Attempt 3: 'password123' - SUCCESS! Attempt 4: 'abc' - Too weak! Attempt 5: 'secure456' - SUCCESS! Maximum successful attempts reached! Total successful logins: 2
How this program uses all three statements:
- return in validatePassword(): Exits the method early with false if password is too short
- continue in loop: Skips weak passwords without counting them, moves to next password
- break in loop: Stops processing when we reach the maximum successful attempts
- This shows real-world usage: validation (return), filtering (continue), and stopping conditions (break)
Key Takeaways
break Exits Loops
Use break when you want to stop a loop completely. Once break executes, the loop ends immediately and the program continues after the loop.
continue Skips Iterations
Use continue when you want to skip the rest of the current loop iteration but keep looping. Perfect for filtering out unwanted items while processing a collection.
return Exits Methods
Use return to exit a method and optionally send back a value. Methods that return a value use return. Even void methods can use return to exit early.
They Control Program Flow
These statements let you make programs that respond to different situations. You can stop processing when needed, skip unwanted items, or finish calculations early.
Use Them Wisely
While powerful, too many break/continue statements make code hard to follow. Use them when they make code clearer, not more confusing.