Reputation: 32331
What is the significance of the return statement inside a method whose return type is void . For example see this below program (I cant paste my companys code so i pasted some sample )
public class Pavan {
public static void main(String args[]) {
Pavan r = new Pavan ();
r.kiran();
}
public void kiran() {
int a = 10;
if (a == 10) {
return;
}
System.out.println("Hi I am Kiran");
}
}
Upvotes: 1
Views: 222
Reputation: 7899
public void kiran() {
int a = 10;
if (a == 10) {
return;
}
System.out.println("Hi I am Kiran");
}
It will stop going ahead to that return statement mean System.out.println("Hi I am Kiran");
will not be executed.
Upvotes: 0
Reputation: 7048
return causes control to be returned to the caller, it doesn't necessarily mean a value should be returned to that caller. "return;" is effectively "return void"
Upvotes: 2
Reputation: 56829
return
in void
method will just return from the execution of the function early.
It has such usage, but overusing it is not good. Use it if it makes the code clearer.
Upvotes: 3
Reputation: 308259
It returns from the method invocation, i.e. it doesn't run any more statements after the return.
An alternative and equivalent way to write your method kiran
would be this:
public void kiran() {
int a = 10;
if (a != 10) {
System.out.println("Hi I am Kiran");
}
}
Upvotes: 6