Introduce Java break Keyword and give examples
The break
keyword in Java is used to terminate a loop or a switch statement prematurely. When the break
statement is encountered, the control flow of the program jumps to the statement immediately following the loop or switch block. This can be particularly useful when you want to exit a loop based on a certain condition.
break
in LoopsThe break
statement can be used in various types of loops, such as for
, while
, and do-while
loops.
break
in a for
looppublic class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
System.out.println(i);
}
System.out.println("Loop terminated.");
}
}
Output:
1
2
3
4
Loop terminated.
In this example, the loop prints numbers from 1 to 4. When i
reaches 5, the break
statement is executed, and the loop is terminated.
break
in a while
looppublic class BreakWhileExample {
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
if (i == 7) {
break; // Exit the loop when i is 7
}
System.out.println(i);
i++;
}
System.out.println("Loop terminated.");
}
}
Output:
1
2
3
4
5
6
Loop terminated.
In this example, the while
loop prints numbers from 1 to 6. When i
reaches 7, the break
statement is executed, and the loop is terminated.
break
in Switch StatementsThe break
statement is also commonly used in switch
statements to prevent fall-through behavior, where execution continues into the next case.
break
in a switch
statementpublic class BreakSwitchExample {
public static void main(String[] args) {
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break; // Exit the switch after this case
case 2:
dayName = "Tuesday";
break; // Exit the switch after this case
case 3:
dayName = "Wednesday";
break; // Exit the switch after this case
case 4:
dayName = "Thursday";
break; // Exit the switch after this case
case 5:
dayName = "Friday";
break; // Exit the switch after this case
case 6:
dayName = "Saturday";
break; // Exit the switch after this case
case 7:
dayName = "Sunday";
break; // Exit the switch after this case
default:
dayName = "Invalid day";
break; // Exit the switch after this case
}
System.out.println("Day: " + dayName);
}
}
Output:
Day: Wednesday
In this example, the switch
statement checks the value of day
. When it matches case 3, it assigns "Wednesday" to dayName
and then executes the break
statement to exit the switch.
break
keyword is used to exit loops and switch statements prematurely.