Break and Continue

Break and Continue are the 2 keywords that are mostly used in loop statements.

Break Statement

As the name suggests Break keyword is used to break from the loop.

Example 1 :

Keep Entering the Number Until It is the multiple of 10.

import java.util.Scanner;

public class BreakStatement {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a=2,b=6;
        while(a<b) {
            System.out.println("Enter the number");
            int i = sc.nextInt();
            if(i%10 == 0) {
                System.out.println("Multiple of Ten");
                break;
            }
        }
    }
}

OR

import java.util.Scanner;

public class BreakStatement {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(true) {
            System.out.println("Enter the number");
            int i = sc.nextInt();
            if(i%10 == 0) {
                System.out.println("Multiple of Ten");
                break;
            }
        }
    }
}

Continue Statement

It is a special kind of keyword used in Java programming language to skip an iteration. You will understand it through an example:

Example 3:

Display all numbers except multiples of 10.

import java.util.Scanner;

public class ContinueStatement {
    public static void main(String[] args) {
        do {
            System.out.println("Enter the number");
            Scanner sc = new Scanner(System.in);
            int num = sc.nextInt();
            if(num % 10 == 0) {
                continue;
            }
            System.out.println("Number Entered "+num);

        }while(true);        
    }
}

Example 3

To find if the number is prime or nonprime.

import java.util.Scanner;

public class PrimeNumber {
    public static void main(String[] args) {
        System.out.println("Enter a number");
        Scanner sc = new Scanner(System.in);
        boolean isPrime = true;
        int num = sc.nextInt();
        if(num == 2) {
            isPrime = true;
        }
        else {
            for(int i=2;i<=num-1;i++) {
                if(num%i ==0) {
                    isPrime = false;
                    break;
                }
                else {
                    isPrime = true;
                }        
            }    
        }
        if(isPrime == true) {
            System.out.println(isPrime);
        }
        else if(isPrime == false) {
            System.out.println(isPrime);
        }
        else {
            System.out.println(isPrime);
        }        
    }
}

This is it we will talk about some new topics.