If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Java, break
and continue
are two control flow statements that allow you to modify the behavior of loops.
break
statement:break
statement is used to terminate the enclosing loop prematurely. When encountered, the loop immediately exits, and the program continues with the first statement after the loop.break
statement is commonly used when a certain condition is met, and there's no need to continue with the rest of the loop iterations.Example of using break
:
javaCopy codepublic class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration " + i);
if (i == 3) {
break; // Exit the loop when i equals 3
}
}
System.out.println("Loop terminated");
}
}
Output:
vbnetCopy codeIteration 1
Iteration 2
Iteration 3
Loop terminated
In the example above, the loop runs from 1 to 5, and when i
becomes 3, the break
statement is encountered, causing the loop to terminate prematurely.
continue
statement:continue
statement is used to skip the current iteration of a loop and move on to the next iteration.continue
statement is encountered, the program jumps to the next iteration, and any code after the continue
statement within the loop's body will be skipped for the current iteration.Example of using continue
:
javaCopy codepublic class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the current iteration when i equals 3
}
System.out.println("Iteration " + i);
}
System.out.println("Loop finished");
}
}
Output:
vbnetCopy codeIteration 1
Iteration 2
Iteration 4
Iteration 5
Loop finished
In the example above, the loop runs from 1 to 5, and when i
becomes 3, the continue
statement is encountered. This causes the program to skip the code inside the loop for that iteration and move on to the next iteration.
Both break
and continue
statements are useful tools to control the flow of loop execution in specific scenarios and make your code more efficient and readable. However, they should be used judiciously to avoid creating confusing or hard-to-read code.
Under Section 107 of the copyright act 1976, allowance is made for fair use for purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational, or personal use tips the balance in favor of fair use.
Comments: 0