📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
1. Using a break keyword to Exit a for Loop
package net.javaguides.corejava.controlstatements.loops;
public class BreakWithForLoop {
public static void main(String args[]) {
for (int i = 0; i < 100; i++) {
if (i == 10)
break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Loop complete.
2. Using break to Exit a while Loop
package net.javaguides.corejava.controlstatements.loops;
public class BreakWithWhileLoop {
public static void main(String args[]) {
int i = 0;
while (i < 100) {
if (i == 10)
break; // terminate loop if i is 10
System.out.println("i: " + i);
i++;
}
System.out.println("Loop complete.");
}
}
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Loop complete.
3. Using break with Nested Loops
package net.javaguides.corejava.controlstatements.loops;
public class BreakWithNestedLoops {
public static void main(String args[]) {
for (int i = 0; i < 3; i++) {
System.out.print("Pass " + i + ": ");
for (int j = 0; j < 100; j++) {
if (j == 10)
break; // terminate loop if j is 10
System.out.print(j + " ");
}
System.out.println();
}
System.out.println("Loops complete.");
}
}
Pass 0: 0 1 2 3 4 5 6 7 8 9
Pass 1: 0 1 2 3 4 5 6 7 8 9
Pass 2: 0 1 2 3 4 5 6 7 8 9
Loops complete.
Using break with a switch case Statement
public class BreakSwitchCaseExample {
public static void main(String args[]) {
int num = 2;
switch (num) {
case 1:
System.out.println("Case 1 ");
break;
case 2:
System.out.println("Case 2 ");
break;
case 3:
System.out.println("Case 3 ");
break;
default:
System.out.println("Default ");
}
}
}
Case 2
Comments
Post a Comment
Leave Comment