3

Lets suppose we have function like:

private int x() {
    while(true) {
        if(true) {

        } else {
            return 0;
        }
    }
}

why Java compiler compiles such kind of code without error message ("Missing return statement"). Such kind od code will compile and never stops during execution.

In comparision, following code will not compile ("Missing return statement"):

private int y() {
    if(true) {

    } else {
        return 1;
    }
}
user109447
  • 1,069
  • 1
  • 10
  • 20
  • I haven't tried to compile this, but I doubt the first one will compile. Are you sure you haven't made any typos? – RaminS May 24 '16 at 23:12
  • I checked it and it compiles ! – user109447 May 24 '16 at 23:13
  • @Gendarme [it does compile](http://ideone.com/pfwYzS). – Andy Turner May 24 '16 at 23:13
  • 1
    This is called "Path sensitivity", and it's something nice compilers (like Java's!) can do. Essentially, the compiler is capable of creating a flow graph of all the different paths through a given function; if any paths exist which exit the function without a return statement, it will not compile. The first block of code has no such path, and the second path does. – Edward Peters May 24 '16 at 23:26

0 Answers0