Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt

 
Vallabhaneni Suresh Kumar
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Will there be compilation error, if a return statement is encountered with a for loop in Java. Is this a good practice to return within a for loop without breaking on a condition and then return a value.

Thank you
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried it to see if it will compile?

Layne
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Doubt" is not a very useful topic name. At the JavaRanch, we like it when you UseAMeaningfulSubjectLine

thanks,
Dave
 
Kj Reddy
Ranch Hand
Posts: 1704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vallabhaneni Suresh Kumar:
Will there be compilation error, if a return statement is encountered with a for loop in Java. Is this a good practice to return within a for loop without breaking on a condition and then return a value.

Thank you


There wont be any compilation error but once you return remaining for loop wont be executed. In some scenario this is kind of code optimization .
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Many folks suggest you allow only a single return from a method never use "break" to exit a loop. They make pretty good arguments, but I find them less compelling the smaller the method is. If the whole thing is less than 10-12 lines it's hard to say an early return or break makes it unreadable.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic