Categories: Java

Jump Statements

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

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago