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;
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With