The jump statements unconditionally transfer program control within a function. Java has three statements that perform an unconditional branch:
- return
- break
- continue
Of these, you may use return anywhere in the program, whereas break and continue are used inside the smallest enclosing like loops, etc.
The break statement:
A break statement skips the rest of the loop and jumps over to the statement following the loop.
A break statement terminates the smallest enclosing while, do-while, for, or switch. Execution resumes at the statement immediately following the body of the terminated statement.
Example:
public class Demo{
public static void main(String[] args) {
for(int i=1;i<=6;i++){
if(i==5)
break;
System.out.print(i);
}
System.out.println();
}
}
Output:
1234
The above code only terminates from the loop only when the value of i is 5.
Note: If a break statement appears in a nested-loop structure, it causes an exit from only the very loop it appears in.
The continue Statement:
The continue statement skips the rest of the loop statements and causes the next iteration of the loop.
continue is somewhat different from the break because instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between.
Example:
public class Demo{
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i%2==0)
continue;
System.out.print(i+" ");
}
}
}
Output:
1 3 5 7 9
Note: also read about the More about loops
Follow Me
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment