Reputation: 32343
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
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
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