Home Segments Top Top Previous Next

427: Mainline

Using Java's shorthand notations for variable reassignment, you can write the powerOf2 method as follows:

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 != 0; --counter) { 
    result = 2 * result; 
  } 
  return result; 
 } 
}