-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathBreakExamples.java
48 lines (45 loc) · 1019 Bytes
/
BreakExamples.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package loopAndFlow;
public class BreakExamples {
public static void main(String[] args) {
// Break statement breaks out of the loop
for (int i = 0; i < 10; i++) {
System.out.print(i);
if (i == 5) {
break;
}
}
// Output is 012345
// Break can be used in a while also
int i = 0;
while (i < 10) {
System.out.print(i);
if (i == 5) {
break;
}
i++;
}
// Output is 012345
System.out.println();
// Break statement takes execution out of inner most loop
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 10; k++) {
System.out.print(j + "" + k);
if (k == 5) {
break;// Takes out of loop using k
}
}
}
// Output is 000102030405101112131415
System.out.println();
// To get out of an outer for loop, label's need to be used
outer: for (int j = 0; j < 2; j++) {
for (int k = 0; k < 10; k++) {
System.out.print(j + "" + k);
if (k == 5) {
break outer;// Takes out of loop using j
}
}
}
// Output is 000102030405
}
}