Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When A Method Returns?

 
ernest fakudze
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What does it mean to say 'when a method returns'? I think i have a vague idea but maybe someone can clarify this once and for all for me. Thanks in advance.
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you call a method, program execution leaves the caller, and goes to that method. At some point, the method will finish, and then control "returns" back from where it originally came.
for example, two methods:
public void callingMethod()
{
doMethodCall(); //at this line, program execution "jumps" to the doMethodCall() method
}
public void doMethodCall()
{
//statements....
//when there are no more method statements, the method is done, so it returns. In this case, it returns back to the callingMethod(), since that is the method that called this one.
//You can also return explicitly, with a return statement:
return; //this immediately returns control to the caller.
}
If you have a method that declares that it returns a value, you put the value you are returning to the right of the return statement.
public int howManyFingersOnOneHand()
{
return 5; //control returns , AND the value 5 is returned to the calling method.
}
if I called the above method like so:
int fingerCount = howManyFingersOnOneHand();
the value 5 is returned from the method, and stored in the variable fingerCount.

I hope this helps!
 
William Barnes
Ranch Hand
Posts: 986
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe instead of using the phrase 'when the method returns' think of it as 'when the method is done executing'.
 
ernest fakudze
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks you so much for explaining this to me. It's that simple! Now I know and I'm happy . Really appreciate guys!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic