Declaring and initializing variables within 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 the key is two it successfully print the value as 2.
Scenario 2 – When I’m going to comment value = 2 in case 2: it squawks saying the The local variable value may not have been initialized.

Questions :

Scenario 1 : If the execution flow doesn’t go to case 1: (when the 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 have accessed to the int value = 1; expression in case 1:.(Declaration and Initialization). Then why does it sqawrk When I’m going to comment value = 2 in case 2:, saying the The local variable value may not have been initialized.



Declaring Variables in java within methods [closed]

I’m trying to understand variable declarations in Java. Actually, I’m trying to understand why you would not declare variables at the top of class, initiate them, and then use as needed. In the Heads

.class error during declaring/initializing variables?

I’m in the process of learning java. Today, my task was to find the errors in some code. I’m in the process of working on it, but I have no idea why the following error occurs. In the sample code, it

Declaring variables within FOR loops

A weird bug was occurring in production which I was asked to look into. The issue was tracked down to a couple of variables being declared within a For loop and not being initialized on each iteration

Declaring variables using Java wrapper classes

In Java, we can use the wrapper classes for declaring a variables. For example Integer x=5; This means that there is a reference ‘x’ that points to a value of 5. Then I declared another reference ca

Initializing an array of variables within a class instance in Java

I’m coming from a C background, and am running into a problem in Java. Currently, I need to initialize an array of variables within an array of objects. I know in C it would be similar to malloc-ing

java beginner: initializing class variables

I’ve just read the SUN java code conventions, very nice document btw. and I’ve read this 6.3 Initialization: Try to initialize local variables where they’re declared. The only reason not to initializ

Initializing static variables in java

What exactly is meant by Static variables are initialized when a class is loaded? I read lots of discussions available on the net but still I am confused. Step 2 is be the initialization step, right

Declaring class level variables JAVA

Is it possible to declare a class level variable from within a method? I’m simply trying to create a static counter, but I only want to create it if needed. The class calling it should live longer tha

declaring/initializing primitives equal to creating new objects

is declaring/initializing primitives the same as creating new objects? from what i know when we create primitives, we also creating wrapper classes for them. im implementing on java btw.

Declaring variables within interface or implementation?

In objective-c, I can declare an int or bool etc in the .m file, outside any function. That allows me to use such variable everywhere in the class. I can also declare such variables in the .h file, in

Answers

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

Declarations are processed at compile time and do not depend on the execution flow of your code. Since value is declared within the local scope of the switch block, it is useable anywhere in that block from the point of its declaration.

The variable has been declared (as an int), but not initialized (assigned an initial value). Think of the line:

int value = 1;

As:

int value;
value = 1;

The int value part tells the compiler at compile time that you have a variable called value which is an int. The value = 1 part initializes it, but that happens at run-time, and doesn’t happen at all if that branch of the switch isn’t entered.

Switch statements are odd in terms of scoping, basically. From section 6.3 of the JLS:

The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.

In your case, case 2 is in the same block as case 1 and appears after it, even though case 1 will never execute… so the local variable is in scope and available for writing despite you logically never “executing” the declaration. (A declaration isn’t really “executable” although initialization is.)

If you comment out the value = 2; assignment, the compiler still knows which variable you’re referring to, but you won’t have gone through any execution path which assigns it a value, which is why you get an error as you would when you try to read any other not-definitely-assigned local variable.

I would strongly recommend you not to use local variables declared in other cases – it leads to highly confusing code, as you’ve seen. When I introduce local variables in 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 believe this is clearer.