Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Return Statement  RSS feed

 
Thanraj Danz
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm new to java , learning it through thinkjava. I don't understand the concept behind return statement given in the book. Could someone care to explain me with some good examples?.


Example mentioned in the book.

 
Swastik Dey
Rancher
Posts: 1812
15
Android Eclipse IDE Java Java ME
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Junilu Lacar
Sheriff
Posts: 11129
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanraj Danz wrote: I don't understand the concept behind return statement given in the book. Could someone care to explain me with some good examples?

It would help if you formatted the code properly.
 
Junilu Lacar
Sheriff
Posts: 11129
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you have on lines 2 to 5 is called a Sentinel or Guard Clause. Under the conditions specified by the guard clause, attempts to enter the method will be rejected or turned away so that the rest of the method does not get executed, kind of like how a sentry prevents unauthorized access to a secure area.

This construct allows you to keep logic in the method simpler and more straightforward by reducing the number of levels of nesting/indentation in the code. It's a common strategy used to avoid or fix the Arrow Code Antipattern.
 
Liutauras Vilda
Marshal
Posts: 4631
316
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanraj Danz wrote:I don't understand the concept behind return statement given in the book.
Welcome to Ranch.

In simple, "return" means return to the caller immediately (to the place, where the method has been called from), without executing the code below.
Examples below are just for presentation purpose, not showing a good practices.

1st Example - it exits the method and goes back to the caller once "if" statement's condition is satisfied.2nd example - returns only when all "if" statements are checked.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!