title: Java switch : variable declaration and scope
body: <p>How does the Java compiler handle the following switch block ?
  What is the scope of the 'b' variable ?</p>
  
  <p>Note that the 'b' variable is declared only in the first branch of the switch statement. Attempting to declare it in the second branch as well results in a "duplicate local variable" compilation error.</p>
  
  <pre><code>    int a = 3;
      switch( a ) {
      case 0:
          int b = 1;
          System.out.println("case 0: b = " + b);
          break;
      case 1:
          // the following line does not compile: b may not have been initialized
          // System.out.println("case 1 before: b = " + b);
          b = 2;
          System.out.println("case 1 after: b = " + b);
          break;
      default:
          b = 7;
          System.out.println("default: b = " + b);
      }
  </code></pre>
  
  <p>Note: the above code compiles with a java 1.6 compiler.</p>