0
int param1 = 1;
        switch (param1){
            case 0:
                int block2 = 10; // if this line is commented gives a compilation error
                System.out.println(block2);
                break;
            case 1:
                block2 = 5; // if this line is commented below line gives a compilation error
                System.out.println(block2);
                break;
            default:
//                System.out.println(block2); // comilation error
        }

I try debug and dont makes sence because I dont see the declaration of the variable. this code run in a main

  • 1
    "*... I dont see the declaration of the variable." - Which variable? – Turing85 Jul 31 '23 at 14:43
  • 1
    Please be more precise. What exactly do you mean with "I dont see the declaration of the variable"? Are you refering to `int block2`? That is clearly declared in case 0, and since java cases fall through and don't have their own scope it is therefor also available in other cases. – OH GOD SPIDERS Jul 31 '23 at 14:44
  • does this answer your question htps://stackoverflow.com/questions/47543667/jpql-query-hibernate-with-clause-not-allowed-on-fetched-associations – DEV Jul 31 '23 at 14:46
  • @OHGODSPIDERS I dint know that, thanks – Alan Barrientos Jul 31 '23 at 14:49

1 Answers1

1

It's a quirk of switch expressions. The Java compiler allows you to declare the variable, and to reference it if it has been initialized. That's why you need to assign it, so why your case 2 gives a compilation error: It sees the declaration from case 0, but there's no initialization, so you can't reference it.

However, this code is confusing, and you shouldn't write it like this. Use a different variable for each case. An IDE like IntelliJ will generate a warning if you do it this way:

Local variable 'block2' declared in one 'switch' branch and used in another

Jorn
  • 20,612
  • 18
  • 79
  • 126