The jump statements unconditionally transfer program control within a function. Java has three statements that perform an unconditional branch:
Of these, you may use return anywhere in the program, whereas break and continue are used inside the smallest enclosing like loops, etc.
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.
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 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.
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
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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…