This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
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


Win a copy of Java 8 in Action this week in the Java 8 forum!
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: 14687
    
  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: 14687
    
  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?
 
Similar Threads
Keep getting String error in my JSP page
class ClockTime
Compilation problem with if condition
Help! Problems with a method calling itself...
how to get data from a db into an array?