fmi
fmi

Reputation: 512

I'm confused about return methods in java

I have a method that is looking for vowels:

 public boolean isVowel(char ch) {
    String vowels = "aeiou";
    char[] chars = vowels.toCharArray();
    for (char letter : chars) {
        if (letter == Character.toUpperCase(ch) || letter == Character.toLowerCase(ch)){
            return true;
        }
    }
    return false;
}

Why doesn't this statement ALWAYS return false? The last line is outside of both the 'for' loop and the conditional statement. Shouldn't it override the true returned within the inner statement?

Upvotes: 0

Views: 133

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

return doesn't just set what the method's return value will be when it ends, it also ends the execution of the method, right then and there. In your case, that means when it hits return true;, it exits the loop (doesn't finish it) and the method right away, returning true.

It's only if the loop's if never branches into that return true; that you reach the end of the method, which returns false.

Upvotes: 2

Guy
Guy

Reputation: 50809

When you use return the method execution ends there and returns the value. return true; will return true, no netter what other return statements return.

return false; will be executed only if the if condition is not met even once.

Upvotes: 1

Moishe Lipsker
Moishe Lipsker

Reputation: 3034

In Java, when you return in a method, the code exits and doesn't execute anything later in that method.

Once the code returns in the for loop, no other later code in that method (like the return false) will be executed.

Upvotes: 1

Related Questions