In the following code:
private static void example() {
String inputString = "test";
switch (inputString) {
case "test":
String outputString = "The string said test";
case "not test":
String outputString = "The string did not say test";
}
/*Do stuff with ouputString*/
}
Eclipse highlights the line after Case "not test" with the error Duplicate local variable outputString. However, since they are in separate branches of the switch statement, they are not actually in conflict, as only one can ever be in effect at a time.
Obviously, in this case I could get around the problem by moving the outputString declaration outside the switch statement. However, in more complex programs, the solution might not be so simple.
Is this simply an error thrown by Eclipse to prevent poor programming technique, or an actual Java error?
I’m very new to Java, so apologies if this is a newbie question – I’ve had a google for “Duplicate local variable Java”, but so far all that turned up were people asking for help with fixing the problem (the usual solution being to rename one of the variables), not discussion of the problem itself.
The scope of a variable in each case of a switch statement in java is the whole switch statement.
You can create further nested scopes by adding braces like so: