Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
  }
}
like image 476
durron597 Avatar asked Jul 13 '26 15:07

durron597


1 Answers

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.

like image 187
Jim Garrison Avatar answered Jul 15 '26 05:07

Jim Garrison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!