Java break

Break:

Beak statement is used to terminate the loop immediately without checking the test expression.

Syntax of break:

break;

Example:

public class BreakExample {  
public static void main(String[] args) {  
    for(int i=1;i<=10;i++){  
        if(i==5){  
            //breaking the loop  
            break;  // use of brack
        }  
        System.out.println(i);  
    }  
}  
}
1
2
3
4

in this example, for loop used to print number 1 to 10

and in the body of for loop, there was if condition.  When I become 5 then break statement run which means loop gets terminated.

Where we use break statement:

Let’s try to understand with a logical example

We have to write the program in which we take numbers from the user as input

Then we give sum of all the number which the user gives

In this, we add one feature which is
if the user enters a negative number  then we return  the sum of all the number which user enter till now

Example:

import java.util.Scanner;

class UserInputSum {
    public static void main(String[] args) {
      
        int number, sum = 0;

        // create an object of Scanner
        Scanner input = new Scanner(System.in);
      
        while (true) {
            System.out.print("Enter a number: ");

            // takes double input from user
            number = input.nextInt();
         
            // if number is negative the loop terminates
            if (number < 0) {
                break;
            }
         
           sum += number;
        }
        System.out.println("Sum = " + sum);
    }
}
Enter a number: 3.2
Enter a number: 5
Enter a number: 2.3
Enter a number: 0
Enter a number: -4.5
Sum = 10.5



SHARE THIS PAGE





Important Link