Reputation: 67
I am a new programmer, I don't know what is the result of this return? I comment it. Is that true that there is {} follow by if()? Thank you
public void blow(int amount)
{
if (this.popped)
return; //what is this? true or false
this.radius += amount;
if (this.radius <= this.maxRadius)
return; // what is this?
this.radius = 0;
this.popped = true;
}
Upvotes: 0
Views: 85
Reputation: 106390
First things first: one does not return values from a method that is declared to return void
.
These return
statements are acting as early exits; they simply force the execution of the method to stop (more formally, "completes abruptly") and return control to its caller without any result. A side-effect will occur if it advances past the first return
, as the state of radius
will have been altered at that point.
More formally, this is coming from the Java Language Specification on why this is permissible:
If a method is declared
void
, then its body must not contain any return statement (§14.17) that has an Expression, or a compile-time error occurs.
In general, it's not a good practice to have multiple exit paths, as it can make debugging a bit of a pain, and lead to confusion while reading the code.
Upvotes: 1
Reputation: 1429
Your method has a return type of void, which means it can't return anything. The return;
statement just allows you to skip the rest of the code inside the method and exit the method.
Upvotes: 0
Reputation: 1739
This just returns the control flow back to the place from where the function was called. It terminates the execution of blow.
Edit: Since your function has a return type of void, you cannot have a value returned, so any which way you look at this the return is just to terminate the function.
This is what it is
public void blow(int amount)
{
if (this.popped)
return; //This stops the function right here, no lines
//in the function beyond this are executed
this.radius += amount;
if (this.radius <= this.maxRadius)
return; // same as above
this.radius = 0;
this.popped = true;
}
Upvotes: 0