by Dinesh Thakur

This example computes the sum of positive numbers input by the user. When a negative number is input, the condition (num<0) become true and break statement is executed which leads to the termination of the while loop and the next statement following the loop is executed which displays the sum of positive numbers. The condition of the while loop always remains true as we have specified a non-zero value 1 which makes it run infinitely. The only way to exit this loop is to. use break statement.

In the nested loops, if the break statement occurs in the inner loop then the control is transferred only out of the inner loop and it has nothing to do with the rest of the surrounding looping statements. But in same cases, we need to jump not only out of the inner loop but also from the outer loop(s). In such a case, Java provides another form of break statement known as labeled break statement. It allows you to specify from which loop you want to break. The labeled break statement enables you to jump immediately to the statement following the end of any enclosing statement black or loop that is identified by the label in the labeled break statement regardless of haw many levels of nested blacks are there.

Before you use a labeled break statement, one should label the statement black or loop you want to exit from. To label a black or loop, you put a label (i.e.labelname) followed by a colon at the start of it. Once you have labeled a block or loop, you can use this label along with the break statement. The general form of the labeled break statement is

break label;

On execution it will cause to exit out of the labeled black or loop and resume with the next statement after the labeled break or loop.

//Program to Show Sum of Indefinite Numbers
import java.util.Scanner;
public class SumPositiveNumbers
       public static void main(String[] ars)
          int num,sum=0;
          Scanner input = new Scanner(;
          System.out.print("Enter Numbers(Negative Number to Quit) :");
                         num=input.nextInt(); //Read number
                         sum +=num;
                         System.out.println( "Sum is : " +sum);

Java Calculate The Sum Of Only The Positive Numbers. Example