3

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?

Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
Ambareesh
  • 324
  • 1
  • 4
  • 18
  • See here: https://stackoverflow.com/questions/23058029/missing-return-statement-within-if-for-while – Daedalus Oct 07 '18 at 19:16
  • 3
    No. There is no code path that results in the outer loop being terminated and thus failing to return a value. Now if the `break` terminated the outer loop you would have a point. But the only conditions that can terminate the outer loop are the ones that `return i` or `-1`. – Elliott Frisch Oct 07 '18 at 19:16

4 Answers4

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

GBlodgett
  • 12,704
  • 4
  • 31
  • 45
1

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) {

} 
star67
  • 1,505
  • 7
  • 16
1

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

Aragorn
  • 5,021
  • 5
  • 26
  • 37
0

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.
 }
Joe
  • 341
  • 2
  • 11