1. Unlabelled Statements
In Unlabelled statements, both the keywords (break and continue) are used directly.
A 'break' statement (unlabeled) will exit out of the innermost loop construct and proceed with the next line of code after the loop.
A 'continue' statement (unlabeled) will exit this iteration and proceeds with the next iteration, but NOT the whole loop.
2. Labelled Statements
A Label is commonly used with loop statements like for or while. However, in conjunction with break and continue statements, a label statement must be placed just before the statement being labeled, and it consists of a valid identifier that ends with a colon (:).
A 'break' statement (labeled) will exit out of the LABEL and proceed with the next line of code after the loop.
A 'continue' statement (labeled) will exit this iteration and proceeds with the next iteration, but NOT the whole LABEL.
The difference between labeled and unlabeled 'break' and 'continue' is shown in the following Java example.
import java.io.* ;
public class Demo {
public static void main (String a[]) {
System.out.println() ;
System.out.println("1. Unlabeled Statements ") ;
System.out.println() ;
System.out.println("1.1 'Break' Command Demo ") ;
for (int i = 1 ; i <= 3 ; i++) {
if (i == 3) {
break ;
} else {
System.out.println(" i = " +i) ;
}
}
System.out.println() ;
System.out.println("1.2 'Continue' Command Demo ") ;
for (int i = 1 ; i <= 5 ; i++) {
if (i == 3) {
continue ;
} else {
System.out.println(" i = " +i) ;
}
}
System.out.println() ;
System.out.println("2. Labeled Statements") ;
System.out.println() ;
System.out.println("2.1 'Break' Command Demo ") ;
System.out.println("Beginning of foo 1 label") ;
foo1: // Declaring a label foo 1
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
System.out.println("i=" +i + " j="+j);
if ( j == 3 )
break foo1;
} // end of inner loop
System.out.println("End of for loop"); // Never prints
}
System.out.println("End of foo 1 label") ;
System.out.println( ) ;
System.out.println("2.2 'Continue' Command Demo ") ;
System.out.println("Beginning of foo 2 label") ;
foo2: // Declaring a label foo 2
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
System.out.println("i=" +i + " j="+j);
continue foo2;
} // end of inner loop
System.out.println("End of for loop"); // Never prints
}
System.out.println("End of foo 2 label") ;
}
}
The Output for the program is as follows:
1. Unlabeled Statements
1.1 'Break' Command Demo
i = 1
i = 2
1.2 'Continue' Command Demo
i = 1
i = 2
i = 4
i = 5
2. Labeled Statements
2.1 'Break' Command Demo
Beginning of foo 1 label
i=0 j=0
i=0 j=1
i=0 j=2
i=0 j=3
End of foo 1 label
2.2 'Continue' Command Demo
Beginning of foo 2 label
i=0 j=0
i=1 j=0
i=2 j=0
i=3 j=0
i=4 j=0
End of foo 2 label
No comments:
Post a Comment