Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

return

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?

like image 474
Ambareesh Avatar asked Feb 03 '26 17:02

Ambareesh


1 Answers

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.

like image 94
GBlodgett Avatar answered Feb 06 '26 05:02

GBlodgett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!