java return keyword is one of the
most frequently used keyword in java and also one of the concept, which
most programmers say they are well aware of. But, I still meet
programmers who say that they are little confused when they come down to
return statement. Especially with respect to the method which has void
as their return type. So, this post would help you in clearing those
doubts and help you understand the clear picture of it... in the most
simplest way.
We all know that Java return keyword is
used to return the control back to calling method with a certain
data-type which was promised during the method declaration. As many
wanted to know if we can use just the return keyword(like this: return;) but not return any value(like this: return obj;), then I have to say yes to that. Se the below java programs which will help you understanding the difference better,
public class ReturnTypes {
public static void main(String args[]){
functionVoid();
functionType();
}
public static int functionType(){
return 1;
}
private static void functionVoid() {
System.out.println("1");
if(true){
return;
}
// return; // This line if UnCommented, would result in Compilation error
System.out.println("2");
}
}
functionVoid();
functionType();
}
public static int functionType(){
return 1;
}
private static void functionVoid() {
System.out.println("1");
if(true){
return;
}
// return; // This line if UnCommented, would result in Compilation error
System.out.println("2");
}
}
If you see in the method functionType()
the return keyword is used to return an primitive int value, which is
quiet normal and know to almost every java programmer.
But, If you see the method functionVoid()
it in fact uses the controversial return keyword(just "return;") which
doesn't return anything at-all. Yes this is absolutely valid to use it
that way... Ahaaaa hold on, I am not yet done completely... and now
imagine if you can use the same return type outside the scope of if
statement, as It's already available in program but commented out...
That will certainly thorough you an compilation error.
Now why so.. There is nothing wrong with
the syntax of return; statement but the error is something different as
the compiler is just complaining about "Unreachable Code"...
By now you know that we can use both of
these conventions and are very much valid. But you can ask yourself a
question on why actually java needs a return; statement in the first,
when we already know that the method is not meant to return any thing
back to the calling function as we have declared it void...??
The answer is, you can treat return keyword as a form of goto
statement. As it will directly move the control to the line where the
method is called. And if you want to accomplish that in an void method then what other option you have to do that other than return; statement.