Java Duplicate Local Variable - Error Occurring 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 a Duplicate local variable outputString . However, since they are in separate branches of the switch , they do not actually conflict, since only one can ever act at a time.

Obviously, in this case, I could work around the problem by moving the outputString outside of the switch . However, in more complex programs, the solution may not be so simple.

Is this just an error caused by Eclipse to prevent a bad programming technique or an actual Java error?

I am very new to Java, so I apologize if this is a newbie question. I had Google for "Duplicate a local Java variable", but so far all that has appeared is people who ask for help in fixing the problem (the usual solution is to rename one of the variables), and not discuss the problem itself.

+4
source share
2 answers

The scope of the variable in each case of the switch statement in java is the entire switch statement.

You can create additional nested areas by adding curly braces:

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

Each case label is supposed to create a separate area that they do not possess. The scope here is a switch block, so you really declared 2 variables with the same name within the scope.

You can enter a new area for each of the case labels, for example.

 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 large, perhaps you should make a method for each case that completes all the work you do there.

+4
source

Source: https://habr.com/ru/post/1446783/


All Articles