Branching Statements:-
Branching statements are used to control the flow of the program by jumping to specific sections of code. That is used to control the flow of a program by altering the sequence in which statements are executed.
Example :-
// while loop
int i = 1;
while (i < =10)
{
if (i ==5)
{
break;
}
System.out.println(i);
i++;
}
Output :- 1 2 3 4
In the above example, the break statement is used to terminate the for loop when the value of i is equal to 5. As a result, the loop only prints the numbers from 1 to 4.
2. Continue :- The continue statement in Java is used to skip the remaining statements in the current iteration of a loop and start the next iteration. It can be used in all types of loops, including for loops, while loops, and do-while loops.
Example :-
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
continue; // skip the remaining statements in the current iteration
}
System.out.println(i);
}
Output :- 0 1 2 3 5 6 7 8 9
As you can see, the value 4 is not printed to the console because the continue statement is used to skip the current iteration of the loop.
Labeled continue statements :-
Java also supports labeled continue statements, which can be used to skip to the next iteration of a specific loop, even if it is an inner loop. To use a labeled continue statement, you first need to label the loop that you want to skip to. This can be done using the continue label; statement.
Example :-
outer: // This is Lable
for (int i = 0; i < 3; i++)
{
inner: // This is Lable
for (int j = 0; j < 3; j++)
{
if (j == 2)
{
continue outer;
}
System.out.println(“I : ” + i + “, j : ” + j);
}
}
Output :- I : 0, j : 0
I : 0, j : 1
I : 1, j : 0
I : 1, j : 1
I : 2, j : 0