Home Segments Top Top Previous Next

433: Mainline

Finally, you can, if you like, terminate a loop immediately by including a break statement at the point where you what termination; in the following contrived example, the break statement eliminates the need for an ordinary testing expression:

public class Demonstrate { 
 public static void main (String argv[]) { 
  System.out.println(powerOf2(4)); 
 } 
 public static int powerOf2 (int n) { 
  int result = 1;        
  for (int counter = n; ; --counter) { 
   if (counter == 0) {break;} 
   result = result * 2; 
  } 
  return result; 
}} 

You can stop while loops, as well as for loops, with break statements.