Declaring and initializing variables in Java switches

I have a crazy question about Java switches.

int key = 2; switch (key) { case 1: int value = 1; break; case 2: value = 2; System.out.println(value); break; default: break; } 

Scenario 1 - When key is two, it will successfully print the value as 2.
Scenario 2 - When I am going to comment on value = 2 in case 2: it goes through, saying that the value of the local variable may not be initialized.

Questions:

Scenario 1: If the thread does not go into case 1: (when key = 2 ), then how does it know the type of the value variable as int ?

Scenario 2. If the compiler knows the type of the value variable as int , then it must access the expression int value = 1; in case 1: (Declaration and Initialization). Then why is it sqawrk When I am going to comment on value = 2 in case 2: saying that the value of the local variable may not have been initialized.

+91
java scope initialization declaration switch-statement
May 30 '12 at 6:04 a.m.
source share
6 answers

Switch statements are mostly odd in terms of scope. From section 6.3 JLS :

The declaration volume of a local variable in a block (ยง14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any other declarators on the right in the statement for declaring the local variable.

In your case, case 2 is in the same block as case 1 and appears after it, although case 1 will never be executed ... therefore the local variable is in scope and is writable even though you logically never Do not follow up on the declaration. (The declaration is not "executable," although initialization is.)

If you comment out the purpose of value = 2; , the compiler still knows which variable you are accessing, but you will not go through any execution path that assigns a value to it, so you get an error like you would try to read any other undefined local variable.

I would strongly recommend that you not use local variables declared in other cases - this leads to very confusing code, as you saw. When I introduce local variables into switch statements (which I try to do rarely - cases should be very short, ideally), I usually prefer to introduce a new scope:

 case 1: { int value = 1; ... break; } case 2: { int value = 2; ... break; } 

I think this is clearer.

+108
May 30 '12 at 6:12
source share

The variable was declared (as int) but not initialized (initial value assigned). Think of the line:

 int value = 1; 

how

 int value; value = 1; 

The int value tells the compiler at compile time that you have a variable called value, which is int. The value = 1 element initializes it, but this occurs at run time and does not occur at all if this switch branch is not specified.

+21
May 30 '12 at 6:10
source share

From http://www.coderanch.com/t/447381/java-programmer-SCJP/certification/variable-initialization-within-case-block

Ads are processed at compile time and are independent of the execution flow of your code. Since value declared in the local volume of the switch block, it can be used anywhere in this block from the point of its declaration.

+18
May 30 '12 at 6:10
source share

With JEP 325 Integration : Switch Expressions (Preview) in Early JDK-12 Access Assemblies. There are certain changes that can be seen from John's answer -

  1. The scope of local variables - local variables in switching cases can now be local for the case itself instead of the entire switching block. An example (similar to what John also tried syntactically) considers the Day enumeration class for further explanation:

     public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } // some another method implementation Day day = Day.valueOf(scanner.next()); switch (day) { case MONDAY,TUESDAY -> { var temp = "mon-tue"; System.out.println(temp); } case WEDNESDAY,THURSDAY -> { var temp = Date.from(Instant.now()); // same variable name 'temp' System.out.println(temp); } default ->{ var temp = 0.04; // different types as well (not mandatory ofcourse) System.out.println(temp); } } 
  2. Switch Expressions - If the goal is to assign a value to a variable and then use it, you can use switch expressions once. eg

     private static void useSwitchExpression() { int key = 2; int value = switch (key) { case 1 -> 1; case 2 -> 2; default -> {break 0;} }; System.out.println("value = " + value); // prints 'value = 2' } 
+2
Sep 08 '18 at 18:55
source share

This explanation may help.

  int id=1; switch(id){ default: boolean b= false; // all switch scope going down, because there is no scope tag case 1: b = false; case 2:{ //String b= "test"; you can't declare scope here. because it in the scope @top b=true; // b is still accessible } case 3:{ boolean c= true; // case c scope only b=true; // case 3 scope is whole switch } case 4:{ boolean c= false; // case 4 scope only } } 
0
Oct 20 '18 at 0:42
source share

Java specification:

https://docs.oracle.com/javase/specs/jls/se12/html/jls-14.html#jls-14.11

The case of sudden termination due to a label break is handled as a general rule for tagged statements (ยง14.7).

https://docs.oracle.com/javase/specs/jls/se12/html/jls-14.html#jls-14.7

Marked statements:

LabeledStatement: identifier: operator

LabeledStatementNoShortIf: Identifier: StatementNoShortIf

Unlike C and C ++, the Java programming language does not have a goto operator; statement identifier labels are used with break (ยง14.15) or continue (ยง14.16) statements that appear anywhere inside a marked statement.

The label area of โ€‹โ€‹a labeled statement is the statement directly contained.

In other words, case 1, case 2 are labels in the switch statement. break and continue statements can be applied to labels.

Because labels share the scope of the statement, all variables defined in the labels share the scope of the switch statement.

0
Jul 05 '19 at 20:07 on
source share



All Articles