Declaring and initializing variables within Java switches
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.
Java switch : variable declaration and scope
The scope is, just as usual, delimited by {
and }
.
Why can't I initialize a variable inside a switch in Java?
Contrary to other replies, you do not need to initialize month
at declaration.
The problem is that if the textmonth
is none of the literal values, the execution will fall to the default
case, where month does not get initialized.
You could initialize it to an invalid value, say 0
in the default
case, but perhaps a better option is to give an error message and abort execution.
Local variables in Java switch control
The key point is that the default case means: no other case was taken.
The switch construct allows you to have local variables within its overall scope, but still each "read" must see a prior "write".
And the compiler can easily detect that the default case didn't see a initialization for b.
Beyond that, the reason why you can have such assignments in different cases is: the overall switch statement only has one "switch block".
See the Java Language Spec for further details!
Using variables, initialized in a switch-statement, outside
Add a default
case to catch any input that isn't recognized. In your case, this could throw a RuntimeException
, since something is wrong with your code if this case is reached.
default:
throw new RuntimeException("Unexpected operation: " + randomChar);
The error you are getting means that there is a code path that fails to initialize ans
. Do not take the easy way out and initialize ans
with a meaningless value when it is declared! That will just hide this valuable warning about a real problem with your code.
Variable's scope in a switch case
I'll repeat what others have said: the scope of the variables in each case
clause corresponds to the whole switch
statement. You can, however, create further nested scopes with braces as follows:
int key = 2;
switch (key) {
case 1: {
String str = "1";
return str;
}
case 2: {
String str = "2";
return str;
}
}
The resulting code will now compile successfully since the variable named str
in each case
clause is in its own scope.
How does java scope declarations in switch case statements?
Declarations aren't "run" - they're not something that needs to execute, they just tell the compiler the type of a variable. (An initializer would run, but that's fine - you're not trying to read from the variable before assigning a value to it.)
Scoping within switch statements is definitely odd, but basically the variable declared in the first case
is still in scope in the second case
.
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.
Unless you create extra blocks, the whole switch statement is one block. If you want a new scope for each case, you can use braces:
case 1: {
int y = 7;
...
}
case 2: {
int y = 5;
...
}
can I declare variables with the same name in every Case branch of a Switch-Case?
You need to move your variable declaration outside the switch block as next:
Example<?> ex;
switch (ch) {
case 1:
ex = new Example<Integer>();
break;
case 2:
ex = new Example<Float>();
break;
case 3:
ex = new Example<String>();
break;
default:
throw new IllegalArgumentException("Unknown type " + ch);
}
As you mixed several types that have nothing in common, you have to use the wildcard
for unknown type
.
Related Topics
Why Java.Util.Optional Is Not Serializable, How to Serialize the Object with Such Fields
How to Get Absolute Path to File in /Resources Folder of Your Project
Why Is Javafx Is Not Included in Openjdk 8 on Ubuntu Wily (15.10)
How to Convert a Byte Array into a Double and Back
How to Have a Textfield Inside a Label
Difference of Maven Jaxb Plugins
Java "Lambda Expressions Not Supported at This Language Level"
Java Properties Utf-8 Encoding in Eclipse
How to Use Jsch for Ssh Key-Based Communication
How to Run a Class in a War from the Command Line
How to Store Java Objects in Httpsession
Java.Sql.Sqlexception: Exhausted Resultset
Selenium Ie Webdriver Only Works While Debugging
Difference Between & and && in Java
Is There a 'Block Until Condition Becomes True' Function in Java