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?
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.