This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Java in General and the fly likes Break statement versus return ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Java » Java in General
Bookmark "Break statement versus return ?" Watch "Break statement versus return ?" New topic

Break statement versus return ?

Amandeep Singh
Ranch Hand

Joined: Jul 17, 2008
Posts: 850

In above method, I want to go out of the loop and method in 1 shot by using return.
What is recommended approach, is it to use break and then outside loop use return ?

SCJP 1.4, SCWCD 5, SCBCD 5, OCPJWSD 5,SCEA-1, Started Assignment Part 2
My blog-
Rob Spoor

Joined: Oct 27, 2005
Posts: 20077

I'm not touching this with a 10-foot pole. The discussion about using return (and even break and continue in loops) within methods is a highly debated one. I would just return in the loop though.

How To Ask Questions How To Answer Questions
Amandeep Singh
Ranch Hand

Joined: Jul 17, 2008
Posts: 850
OK then as Rob also suggested, I will go through return loop.
Paul Clapham

Joined: Oct 14, 2005
Posts: 19719

If you break out of the loop, then aren't you going to need some logic to avoid executing the code which comes after the loop?

Perhaps the same logic which caused you to break out of the loop in the first place?

Then that would complicate your method and also require duplicate code. I wouldn't do that.
Amandeep Singh
Ranch Hand

Joined: Jul 17, 2008
Posts: 850
I agree with you Paul.
I am going to use return statement only instead of break. Using return will break the loop and go out of method also in 1 shot.
I agree. Here's the link:
subject: Break statement versus return ?
jQuery in Action, 3rd edition