Java- break keyword / Chapter -7 / Flow Control

javabychetan.blogspot.com
3.Transfer Statement:-
1.break:-
break is used to break the control flow from switch & loops
We can  use break keyword in following places.


  • Inside switch ( ) to stop fall through.

example:
int x=0
switch(x)
{
  case 0 :
              System.out.println(0);
  case 1 :
              System.out.println(1);
                                  break;
  case 2 :
              System.out.println(2);

default : System.out.println(default);
}
Output is :   0
                   1


  • Inside loop to break loop execution based on some condition.
example:-

for(int i=0;i<10;i++)
{
          if(i==5)
           break;
            System.out.println(i);
}
Output is :  0
                 1
                 2
                 3
                 4
               

  • Inside labeled  blocks:
To break execution based on some condition.

example:-
class Test
{
       public static void main(String [] args)
       {
              int x=10;
              l1:
                {
                  System.out.println("begin");
                    if(x==10)
                    break;
                    else
                   System.out.println("end");
                }
                    System.out.println("Hello");
       }
}        
                Output is:-   begin
                                   Hello
       

Note:These are the only places where we can use break statement.
If we are using break anywhere else we will get compile time error saying"break outside switch or loop".
example:-
class Test
 {
  public static void main(String [] args)
       {
              int x=10;
              if(x==10)
              break;
                  System.out.println("Hello");
         }
 }              Compile Time Error: break outside switch or loop

No comments:

Post a Comment

Be the first to comment!

Don't just read and walk away, Your Feedback Is Always Appreciated. I will try to reply to your queries as soon as time allows.

Note:
1. If your question is unrelated to this article, please use our Facebook Page.
2. Please always make use of your name in the comment box instead of anonymous so that i can respond to you through your name and don't make use of Names such as "Admin" or "ADMIN" if you want your Comment to be published.

Regards,
JavaByChetan
Back To Home

Flipkart End Of Season Sale






© Copyright 2017 Javabychetan.blogspot.com