File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Why does this method works without a return statement outside while loop? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why does this method works without a return statement outside while loop?" Watch "Why does this method works without a return statement outside while loop?" New topic
Author

Why does this method works without a return statement outside while loop?

Varuna Seneviratna
Ranch Hand

Joined: Jan 15, 2007
Posts: 167
Why does this method works without a return statement outside while loop?

/**
* Returns "yes", "no", or "maybe" randomly
*
*/
public String getResponse()
{
int response=0;
while(true)
{
response=randomNumberGenerator.nextInt(3);

if(response==0)
return "No";
else if(response == 1)
return "Yes";
else
return "May be";
}
}


Varuna Seneviratna
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

Because the compiler is smart enough to understand that that the line before the last bracket will never be reached.


[My Blog]
All roads lead to JavaRanch
Varuna Seneviratna
Ranch Hand

Joined: Jan 15, 2007
Posts: 167
When placing return statements inside methods what is the theory to follow?
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

You have to return a value from any possible path. If the compiler finds a path where a value is not returned, it will result in a compiler error. This kind of error is automatically signaled by IDEs like Eclipse or IntelliJ.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why does this method works without a return statement outside while loop?