Java - Using a return Statement Inside a Constructor

Introduction

A constructor cannot have a return type in its declaration.

You can use a return statement without an expression inside a constructor body.

The following code shows an example of using a return statement in a constructor.

If the x value is less than 0, it would just return from the constructor without output.

class Test {
  public Test(int x) {
    if (x < 0) {
      return;
    }
    System.out.println(x);
  }
}

Demo

class Test {
  public Test(int x) {
    if (x < 0) {
      return;/*from  w  w  w .  j av  a  2  s .c om*/
    }
    System.out.println(x);
  }
}

public class Main {
  public static void main(String[] args) {
    new Test(1);
    new Test(2);
    new Test(11);
  }
}

Result

Related Topic