Java – Loop-and-a-half repetition control

Loop-and-a-half repetition control statements are used to control the flow of the loop. You wouldn’t want to run a loop forever. There will come a time when you need to stop a loop earlier and you can use the following statements to implement it:

  • break;
  • if statement
  • while statement

Example

import java.util.*;

class Running{
    int forest_gump;
    int months = 0;
    void method() throws InterruptedException{
        while(true){
            months++;
            System.out.println("Forrest is running for:" + months + "months now");
            Thread.sleep(500);
            if (months > 38){
                System.out.println("Forrest is tired");
                break;
            }
        }
    }
    
        public static void main(String[] args) {
            Running run_forest_run = new Running();
            try{
                run_forest_run.method();
            }
            catch(Exception e){

            }
        }        
}

The break statement breaks out of the while loop when the if condition is met. Forrest Gump felt tired after 38 months so he just stopped running.

You have to be careful working with infinite loops. They can create complexities and unintentional shutdowns.
There are also multiple exit points that can be taken during a run of a loop. You can put multiple if statements throughout the program to come out of the loop. You just have to make sure you do it as efficiently as possible.

Leave a comment

Design a site like this with WordPress.com
Get started