Am I not returning a string?

I'm writing a method to find the upper case letters in a given string. I have this

public static String FindUpperCase (String x){
 for (int i = x.length(); i>=0; i--){
      if (Character.isUpperCase(x.charAt(i))){
          return x.substring(i); }
    }

But I'm getting an error thats telling me I must return a string. When I look up on the API what substring does it tells me that it returns a string that is a subset of the other string...which means I am returning a string, right? I was told that it was because I am returning a string within the loop and that's not the same thing but I'm a little confused by what this means because isn't the loop in the method? Does anyone know what I'm doing wrong or how I can fix this?

Jon Skeet
people
quotationmark

No, you're not always returning a string. What if the input is entirely lower case?

Basically, you need a return statement (or throw an exception) after the for loop, to handle the situation where you get to the end of it. Even in cases that you can reason that you'll never actually get to the end of the loop, the Java compiler follows strict rules for reachability, as specified in section 14.21 of the JLS. So even if your return statement were unconditional and we know that length() always returns a non-negative value, this still wouldn't compile:

public static String broken(String input) {
    // *We* know that we'll always go into the body of the loop...
    for (int x = input.length(); x >= 0; x--) {
        return input;
    }
    // The end of the method is still reachable from the compiler's standpoint
}

The end of a non-void method can't be reachable - you must either throw an exception or return a value.

Also note that your initial value should be x.length() - 1 or x.charAt(i) will throw an exception. You should also change your method name to follow Java naming conventions.

Oh, and currently you're not returning "the upper case letters" - you're returning "everything from the last upper case character onwards" which is entirely different.

people

See more on this question at Stackoverflow