Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
The following methods go without return statements even though they have an explicit return type int.

Java
public int foo1()
{
    while(true) {}
}

public int foo2()
{
    for(;;);
}

public int foo3()
{
    while(true)
    {
        if(true)
        {
            //... Stuff
        }
    }
}

All of the above methods issue no compiler error even though they contain no return statement. It may be because they all are infinite loops that will never return and hence, the compiler may ignore the return statement. If it is so, then the following case is also obvious.

Java
public int foo4()
{
    if(true)
    {
        return(5);
    }
}


In the preceding method, the compiler complains about missing return statement even though the if condition is always true and consequently, the return statement is obviously going to return the specified value. Suppressing this error requires another return statement within an else block or otherwise.

Are there some specific reasons behind it? The preceding is not the case with C# that works perfectly as expected.
Posted
Comments
Manfred Rudolf Bihy 23-Jan-12 7:10am    
Interesting find! 5+
I hope someone savvy (more than me anyhow :) ) in java will unravel that mystery for us.

I've found some interesting information about the phenomenon you've observed here: Compiler complains about missing return statement even though it is impossible[^]. There is a great link in that discussion that points to the Java Language Specification[^]: Statements 14.21[^]. With some titbits at the end of above mentioned section here[^].

Regards,

Manfred
 
Share this answer
 
The above examples are pretty much rubbish - but also never ending loops. That can also cause a compiler warning (also error?). You will also get the error due to the return value when you add a break condition.

The example foo4() is not ever lasting. Therefor it needs to return "something":

Java
public int foo4() {
    if(true){ return(5); }
    return -1; // invalid int value
}
 
Share this answer
 
v2
Comments
TorstenH. 23-Jan-12 7:56am    
Who the... thanks for downvoting an understandable explanation.
A comment would be fine.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900