durron597
durron597

Reputation: 32343

Switch local variable compile error

Why is this a compile error? Java cannot reach both declarations of bar.

import java.util.Random;

public class SwitchTest {
  public static void main(String[] args) {
    Random r = new Random();
    int foo = r.nextInt(2);

    switch(foo) {
    case 0:
      int bar = r.nextInt(10);
      System.out.println(bar);
      break;
    case 1:
      int bar = r.nextInt(10) + 10; // Doesn't compile!!
      System.out.println(bar);
      break;
    }
  }
}

Upvotes: 2

Views: 65

Answers (2)

Diego C Nascimento
Diego C Nascimento

Reputation: 2801

You could declare bar outside the scope too

import java.util.Random;

public class SwitchTest {
  public static void main(String[] args) {
    Random r = new Random();
    int foo = r.nextInt(2);

    int bar;    //bar is out of the switch scope

    switch(foo) {
    case 0:
      bar = r.nextInt(10);
      System.out.println(bar);
      break;
    case 1:
      bar = r.nextInt(10) + 10;
      System.out.println(bar);
      break;
    }
  }
}

Upvotes: 3

Jim Garrison
Jim Garrison

Reputation: 86774

They're both in the same lexical scope, which is different from execution reachability.

Put braces around the code inside each case and it will work.

Upvotes: 6

Related Questions