We went through while, do while, for, for each loops in previous posts. These loop can be nested. We can also adding optional labels, break and continue statements to change the loop flow.
By default break and continue only effect the innermost loop in which it is located. An optional label can be added in front of a loop. In that case, break and continue can accept the optional label as an argument and effect the labeled loop. Let's take a look at some examples.
an example compare break and continue.
OCAJP>cat test.java
class test {
public static void main(String[] args) {
String a[] = {"a","b","c","d","e"};
for(int i = 0; i < 5; i++) {
if(i%2==1) continue;
System.out.println(a[i]);
}
System.out.println("test break");
for(int i = 0; i < 5; i++) {
if(i%2==1) break;
System.out.println(a[i]);
}
}
}
OCAJP>javac test.java
OCAJP>java test
a
c
e
test break
a
a more convoluted example showing the optional label usage.
OCAJP>cat test.java
class test {
public static void main(String[] args) {
OUTER: for(int i = 0; i< 3; i++) {
int j = 0;
MIDDLE: while((j = i*3) % 2 == 0) {
if(i == 0) break;
INNER: do{
j--;
if(j%2 == 0) continue;
if(j%3 == 0) break MIDDLE;
if(j%3 == 1) continue OUTER;
System.out.println("INNER loop j=" + j + ", i=" + i);
}while(j>0);
System.out.println("MIDDLE loop j=" + j + ", i=" + i);
continue OUTER;
}
System.out.println("OUTER loop j=" + j + ", i=" + i);
}
}
}
OCAJP>javac test.java
OCAJP>java test
OUTER loop j=0, i=0
OUTER loop j=3, i=1
INNER loop j=5, i=2
OUTER loop j=3, i=2
Back OCAJP