Method scope inside Java switch statement

Tags: , , ,



In a rather loose way this question follows on from my previous one. The context here is building Android APKs with Phonegap CLI configured, via build-extras.gradle to use Java 7. Here is my code

public boolean execute(String action, JSONArray data, 
CallbackContext cbc) throws JSONException 
{
 Context ctxt = cordova.getActivity().getApplicationContext();
 // return doSave(data,cbc,ctxt);
 //the above compiles correctly 
 //doSave is a private method in the same class 
 switch(action)
 {
  case "save":return doSave(data,cbc,ctxt);break;
  //the compiler complains about an `unreachable statement`
  //other case statements ommitted for clarity
  default:cbc.error("Unknown action: "  + action);return false;
 }
 return false;
 //without this return the compiler is upset.
}

I am having some difficulty understanding two issues here

  1. As far as I can tell even without that last return I have defined a clear path of execution thanks to the switch...default clause so I cannot see why it requires a return statement there
  2. So inside the switch statement the private doSave method in the same class somehow becomes invisible?

I am coming back to Java after a long gap where I did only JS and PHP. However, I have done a great deal of Delphi coding at one time so I appreciate the rigor imposed by the Java compiler. In this instance though it seems to me that it is a bit excessive. Or perhaps I am misunderstanding something?

Answer

return doSave(data,cbc,ctxt);break;

Your break statement is unreachable.

You should remove that statement, as well as the final return false; statement, which is also unreachable.



Source: stackoverflow