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

Ambareesh :

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?

GBlodgett :
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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=93876&siteId=1