The correct answer is: D. All of the above
The break
statement is used to exit from a loop or switch statement. It can be used in any type of loop, including for
, while
, and do-while
loops. It can also be used in a switch statement.
When the break
statement is encountered, the control flow of the program immediately exits the loop or switch statement. The next statement after the loop or switch statement is executed.
For example, the following code shows how to use the break
statement to exit from a for
loop:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
This code will print the numbers from 0 to 4, because the break
statement causes the loop to exit when i
is equal to 5.
The following code shows how to use the break
statement to exit from a while
loop:
int i = 0;
while (i < 10) {
if (i == 5) {
break;
}
System.out.println(i);
i++;
}
This code will also print the numbers from 0 to 4, because the break
statement causes the loop to exit when i
is equal to 5.
The following code shows how to use the break
statement to exit from a do-while
loop:
int i = 0;
do {
if (i == 5) {
break;
}
System.out.println(i);
i++;
} while (i < 10);
This code will also print the numbers from 0 to 4, because the break
statement causes the loop to exit when i
is equal to 5.
The following code shows how to use the break
statement to exit from a switch statement:
switch (x) {
case 1:
System.out.println("x is 1");
break;
case 2:
System.out.println("x is 2");
break;
case 3:
System.out.println("x is 3");
break;
default:
System.out.println("x is not 1, 2, or 3");
}
This code will print the message “x is 1” because the break
statement causes the switch statement to exit when x
is equal to 1.
The break
statement is a powerful tool that can be used to control the flow of your program. It is important to use it carefully, however, because it can cause your program to behave unexpectedly if you are not careful.