File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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: 844

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: 19654

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: 844
OK then as Rob also suggested, I will go through return loop.
Paul Clapham

Joined: Oct 14, 2005
Posts: 18541

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: 844
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.
jQuery in Action, 2nd edition
subject: Break statement versus return ?
Similar Threads
while loop doubt
what exactly is the purpose of the return keword in a void method ?
Coding conventions
working with arrays
infinite loop problem