This is illegal syntax . This is not an extra thing to return a variable. You MUST return a variable of the type specified in your method.
public String myMethod() { if(condition) { return x; } }
You effectively say, I promise that any class can use this method (public), and I promise that it will always return String (String).
Then you say that my condition is true, I will return x. Well, this is too bad, there is no IF in your promise. You promised that myMethod will ALWAYS return a String. Even if your condition is ALWAYS true, the compiler must assume that it is likely that it is false. Therefore, you always need to return at the end of your non-void method outside of any conditions, ONLY IN THE CASE that all of your conditions fail.
public String myMethod() { if(condition) { return x; } return "";
CodeCamper
source share