Get the tools you need to learn Java skills fast!
Video tutorials, eBooks, hands-on lab exercises, sample code.
Get started
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 The Software Craftsman this week in the Agile 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: 845

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

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

Joined: Oct 14, 2005
Posts: 19359

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: 845
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.
subject: Break statement versus return ?