Ambareesh
Ambareesh

Reputation: 363

Why doesn't the compiler throw an error saying "No return statement"?

I was trying to solve a question in Leetcode, and one of the discussed solutions was the following:

public class Solve {
    public static void main(String[] args) {
        String haystack = "mississippi";
        String needle = "issip";
        System.out.println(strStr(haystack,needle)) ;
    }

    public static int strStr(String haystack, String needle) {
        for (int i = 0; ; i++) {
            for (int j = 0; ; j++) {
                if (j == needle.length()) return i;
                if (i + j == haystack.length()) return -1;
                if (needle.charAt(j) != haystack.charAt(i + j)) break;
            }
        }
    }
}

Shouldn't the compiler have thrown a "No return statement" error here?

Upvotes: 3

Views: 100

Answers (4)

GBlodgett
GBlodgett

Reputation: 12819

for (int i = 0; ; i++) {
    for (int j = 0; ; j++) {
       if (j == needle.length()) return i;
       if (i + j == haystack.length()) return -1;
       if (needle.charAt(j) != haystack.charAt(i + j)) break;
    }
}

Here both of the for loops are infinite loops. The break statement only breaks out of the inner for loop. Therefore there is no exit condition for the outer for loop except the return statements. There is no path for which the method cannot return a value so there is no reason for the compiler to complain.

Upvotes: 2

Joe
Joe

Reputation: 341

Your both for loops are infinite, the second one breaks or returns someday anyway! but the first one even has no break, then Java knows the you never rich to the last line.

 for (int i = 0; ; i++) {
      //Your second loop which is capable of returning or breaking (the second one is not technically infinite.
 }

Upvotes: 0

Aragorn
Aragorn

Reputation: 5289

The first for loop is infinite for the compiler, we know it will return, but compiler has no reason to complain. Good question though.

Upvotes: 1

star67
star67

Reputation: 1832

this is because you don't specify corner values for loop counters. if you add smth like i<N; or j<N; you would got compiler warning. But till that it's the same as:

while (true) {

} 

Upvotes: 1

Related Questions