return

The return statement can be placed only in a method or a constructor. Its function is to return control to the invoker with or without a value.

In the case of a constructor, the return statement is not required. If placed in the constructor, it has to be the last statement that returns no value:

class ConstructorDemo{  private int field;  public ConstructorDemo(int i) {    this.field = i;    return;  }}

 An attempt to place the return statement as not the last statement of a constructor or to make it return any value will result in a compilation error. 

In the case of a method, if the method was declared as returning some type:

  • The return statement is required
  • The return statement has to be effectively (see the following example) the last ...

Get Introduction to Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.