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");
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.