This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Return keyword" Watch "Return keyword" New topic

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

Joined: Sep 28, 2004
Posts: 18494

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.


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

Joined: May 26, 2003
Posts: 30050

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

Joined: Oct 13, 2005
Posts: 37879
That's how it works; whether it is good programming is a different matter. There is a brief discussion in JavaRanch here.
I agree. Here's the link:
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