Break-Statement-In-Java .

In this session i have discussed break statement in Java .


The break is a keyword in Java which is used to break the loop . It is also used in switch case to break the case . If you will use the break in inner loop then it will terminate the inner loop only .

Example : Write a Java program that will demonstrate the break statement in loop .

class Hello{ 
         
      public static void main(String args[]){  
  
            int i;
            for(i=1;i<10;i++){
            
                System.out.print(i);
                System.out.print(" ");
                if(i==6){
                
                    break;
                }
            }
            System.out.print("Out of loop i="+i);
      }
} 
    OUTPUT : 1 2 3 4 5 Out of loop i=6
    

Example : Write a program that will demonstrate the break statement in nested loop .

class Hello{ 
         
    public static void main(String args[]){  

        int i=1,j=1;
        for(i=1;i<=3;i++){
        
            for(j=1;j<=3;j++){
            
                System.out.print("\n"+i+" "+j);
                if(i==2 && j==2){
                
                    break; //will break inner loop  only
                }
            }//end of for loop
        }
    }
}
    
    OUTPUT : 1 1
             1 2
             1 3
             2 1
             2 2
             3 1 
             3 2
             3 3
    


Example : Write a program that will demonstrate the break statement in switch .

class Hello{ 
         
    public static void main(String args[]){  

            int i ,x,y,result;
            i=2;
            x=20;
            y=10;
            switch(i){
            
                case 1:{
                
                    int sum=x+y;
                    System.out.print("Sum="+sum);
                    break;
                }
                case 2:{
                
                    int sub=x-y;
                    System.out.print("Sub="+sub);
                    break;
                }
                case 3:{
                
                    int mul=x*y;
                    System.out.print("Mul="+mul);
                    break;
                }
                default :{
                
                    System.out.print("Invalid number");
                    break;
                }
            }
      }
}
    
    OUTPUT : Sub=10
    

Welcome to AndroidATPoint.

back image                     next image