Significance of return in the method with return type as void in Java
Code Example:
public class TestReturn {
public void printNum(int[] ab){
int i = 0;
for( i=0; i<ab.length; i++){
if(ab[i] < 10){
System.out.println("less than 10开发者_如何学JAVA");
return;
}
else{
System.out.println("more than or equal to 10");
return;
}
}
}
public static void main(String args[])
{
TestReturn a = new TestReturn();
int[] ab = {67, 56, 34, 89, 2, 23, 92, 33, 9, 74};
a.printNum(ab);
}
}
In the above code return has been used twice. While running the code you can see that according to the input the code runs only once . Now if the return statement in the else block is commented out the loop runs for 5 times till it reaches the value 2 and then it stops printing.
This can be achieved through break statement also. Are there any more advantages of this return statement?
The only advantage of the return statement is that it exits the method. So if you had any further code after the loop and used break
, that would be executed.
With return
, it is not executed.
This is generally how I use return
- if I know the method has finished executing for the purposes of what you need it for, I put a return statement in.
With return
you end method's execution. With break
you get out of the for
loop.
return
is slightly faster than break
because it doesn't 'get out' of the for-loop, but quits the method completely. Also, if you had code after the loop, it would be run using break
, but not using return
.
精彩评论