In the Java programming language, the break
statement is used to exit or terminate the execution of a loop or a switch statement. It is primarily used to control the flow of the program and allows you to prematurely exit a loop or skip the remaining code in a switch statement.
The break
statement can be used in the following contexts:
- Loop statements (such as
for
,while
, ordo-while
): When thebreak
statement is encountered within a loop, the loop is immediately terminated, and the program execution continues with the next statement after the loop.
for (int i = 0; i < 10; i++){ if (i == 5)
{ break; // terminates the loop when i reaches 5
}
System.out.println(i);
}
i
becomes 5, the break
statement is encountered, and the loop terminates.
- Switch statements: The
break
statement is used to exit the switch block. When abreak
statement is encountered within a switch case, the program execution jumps to the end of the switch block.
switch (day)
{
case 1: System.out.println("Monday");
break;
case 2: System.out.println("Tuesday");
break;
case 3: System.out.println("Wednesday");
break;
default: System.out.println("Invalid day");
}
In the above example, when day
is 3, the "Wednesday" message is printed, and then the break
statement is encountered, causing the program to exit the switch block.Note that if a break
statement is omitted in a switch case, the program will continue executing the following cases until a break
statement is encountered or until the end of the switch block is reached. This behavior is known as "fall-through" and can be intentionally used in some cases.
Overall, the break
statement is a control flow statement in Java that allows you to exit loops or switch statements prematurely and continue with the next statement after the loop or switch.
Comments
Post a Comment