wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Return keyword Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Return keyword" Watch "Return keyword" New topic
Author

Return keyword

Juan Manuel Alberto de los Santos
Ranch Hand

Joined: Jun 26, 2008
Posts: 48


What is the use of return when is used like that ?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18117
    
  39

Well, the way it is written, it probably has no value. But if the condition did more than "if true". And there were code after the conditional... then this would be a way of conditionally leaving the method.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Juan Manuel Alberto de los Santos
Ranch Hand

Joined: Jun 26, 2008
Posts: 48
Conditionally leaving the method ?

returns to main ? it leaves main ?
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 29244
    
139

Let's consider a slightly more realistic example:

In this example, the return statement gets you out of the main method without executing any code after the if statement. This is still a bit contrived. A better example would call System.exit() so it could pass a return code back to the caller. "return" tends to be used more within methods other than the main method.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Juan Manuel Alberto de los Santos
Ranch Hand

Joined: Jun 26, 2008
Posts: 48
understood !

thank you
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36501
    
  16
That's how it works; whether it is good programming is a different matter. There is a brief discussion in JavaRanch here.
 
 
subject: Return keyword
 
Similar Threads
System.out.print(s + (b ? "T" : "F"));
Trouble crafting regular expression.
Polymorphism and HashMap problem
How does HashMap locate the correct value when multiple values are in the same bucket?
Not so good with boolean and loops