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

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

2 days ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

5 days ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

3 weeks ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

1 month ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

1 month ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

2 months ago