A break
statement exits a loop before an entry
condition fails. For example, in this variation on the
CountWheat
program an error message is printed, and you
break out of the for
loop if j
becomes
negative.
class CountWheat {
public static void main (String args[]) {
int total = 0;
for (int square=1, grains = 1; square <= 64; square++) {
grains *= 2;
if (grains <= 0) {
System.out.println("Error: Overflow");
break;
}
total += grains;
System.out.print(total + "\t ");
if (square % 4 == 0) System.out.println();
}
System.out.println("All done!");
}
}
Here's the output:
% javac CountWheat.java % java CountWheat 2 6 14 30 62 126 254 510 1022 2046 4094 8190 16382 32766 65534 131070 262142 524286 1048574 2097150 4194302 8388606 16777214 33554430 67108862 134217726 268435454 536870910 1073741822 2147483646 Error: Overflow All done!
The most common use of break
is in switch
statements.