Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java "Duplicate local variable" - is the error thrown in Java or Eclipse?

Tags:

java

eclipse

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.

like image 585
scubbo Avatar asked Jan 15 '23 00:01

scubbo


2 Answers

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:

 switch (inputString) {
        case "test": {
            String outputString = "The string said test";
            break;
        }
        case "not test": {
            String outputString = "The string did not say test";
            break;
        }
    }
like image 83
gregwhitaker Avatar answered Jan 21 '23 16:01

gregwhitaker


You are assuming that each case label creates a separate scope - which they don't. The scope here is the switch block, so you really have declared 2 variables with the same name within a scope.

You could introduce a new scope for each of the case labels, e.g.

switch (inputString) {
    case "test": {
        String outputString = "The string said test";
        break;
    }
    case "not test": {
        String outputString = "The string did not say test";
        break;
   }
}

Or if your switch is already big, perhaps you should make a method for each case that wraps all the work you do there

like image 33
nos Avatar answered Jan 21 '23 14:01

nos