I don't know what is the usage return;
. What does it mean ? Does it return something ? I think return
keyword use to put back some value but I am not sure because if constructors return only instance of class below code should be invalid.
public class Test {public Test() {return;}}
Any suggestions ?
Best Answer
It does not returns anything.
It means the end of any method which returns void, so in this case, it means the end of the constructor. See the example below:
class Test {private int sum;public Test(Object otherObj) {if (otherObj != null){sum = 42;return;}sum = 0;}public static void main(String[] args) {Test testZero = new Test(null);Test testNonZero = new Test(testZero);System.out.println(testZero.sum); // 0System.out.println(testNonZero.sum); // 42}}
if the otherObj
is not null, the sum
'll be 42, and the constructor will stop running.
You can use the same strategy, if you have a public void someFunction()
method, to exit at some point.