VALUES

Break statement in Java

 

Java break statement

BREAK STATEMENT IN JAVA


Logically, break means stop. This meaning also applied to programming. 

Just as continue statement, a break statement is used in a loop to terminate or stop the loop from running when the condition we have stated have been met.

SYNTAX

 

Explanation

I said earlier that a break statement is used to terminate a loop. So imagine if you want to print numbers from 1-30 but you want the numbers to stop when the number is 22. Then, what do you do? 

The simple logic is use a break statement. The break statement terminates the loop ONCE the numbers are equal to 22.

Let’s take an example

Break for While loop


public class sample{

   public static void main(String args[]){

      int x =0;

      while(x<=10)

      {

          System.out.println(“Result : “+x );

          if (x==5)

          {

             break;

          }

          x++;

      }

      System.out.println(“Loop will stop at 5 because we used a break when num is 5 “);

  }

}

 

Break statement in Java

Results

Break for “For loop “


public class sample{

   public static void main(String args[]){

int num;

for (num =1; num<=15; num ++)

{

    System.out.println(“Result: “+num);

    if (num==8)

    {

         break;

    }

 }

   }

}

 

Break statement example in java

Result

Break statement


Continue statement in Java


Java Object Oriented Programming


Constructors in Java programming


Inheritance in Java


Please share 



Please share 


Related Articles

Back to top button