First,i think you should know that there are two types of break and continue in Java which are labeled break,unlabeled break,labeled continue and unlabeled continue.Now, i will talk about the difference between them.
class BreakDemo {
public static void main(String[] args) {
int[] arrayOfInts =
{ 32, 87, 3, 589,
12, 1076, 2000,
8, 622, 127 };
int searchfor = 12;
int i;
boolean foundIt = false;
for (i = 0; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;//this is an unlabeled break,an unlabeled break statement terminates the innermost switch,for,while,do-while statement.
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at index " + i);
} else {
System.out.println(searchfor + " not in the array");
}
}
An unlabeled break statement terminates the innermost switch ,for ,while ,do-while statement.
public class BreakWithLabelDemo {
public static void main(String[] args) {
search:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
System.out.println(i + " - " + j);
if (j == 3)
break search;//this is an labeled break.To notice the lab which is search.
}
}
}
A labeled break terminates an outer statement.if you javac and java this demo,you will get:
0 - 0
0 - 1
0 - 2
0 - 3
class ContinueDemo {
public static void main(String[] args) {
String searchMe = "peter piper picked a " + "peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++) {
// interested only in p's
if (searchMe.charAt(i) != 'p')
continue;//this is an unlabeled continue.
// process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
An unlabeled continue statement skips the current iteration of a for,while,do-while statement.
public class ContinueWithLabelDemo {
public static void main(String[] args) {
search:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
System.out.println(i + " - " + j);
if (j == 3)
continue search;//this is an labeled continue.Notice the lab which is search
}
}
}
A labeled continue statement skips the current iteration of an outer loop marked with the given lable,if you javac and java the demo,you will get:
0 - 0
0 - 1
0 - 2
0 - 3
1 - 0
1 - 1
1 - 2
1 - 3
2 - 0
2 - 1
2 - 2
2 - 3
if you have any question , you can see the Java tutorial of this:enter link description here