scubbo
scubbo

Reputation: 5837

Java "Duplicate local variable" - is the error thrown in Java or 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.

Upvotes: 4

Views: 4312

Answers (2)

gregwhitaker
gregwhitaker

Reputation: 13420

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;
        }
    }

Upvotes: 5

nos
nos

Reputation: 229244

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

Upvotes: 4

Related Questions