What is the return type of a Constructor in Java?



A Constructor in Java is similar to a method, and it is invoked at the time of creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class. The main purpose of a constructor is to initialize the instance variables of a class.

Return Type of Constructor

In Java, constructors do not have a return type, not even void. They are used to initialize the object when it is created.

  • A constructor doesn't have any return type.
  • The data type of the value returned by a method may vary, return type of a method indicates this value.
  • A constructor doesn't return any values explicitly, it returns the instance of the class to which it belongs.

There are four types of constructors in Java, and none of them has a return type:

  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor
  • Static Constructor

Example 1

In the following example, we will see how a constructor is used to initialize an object without a return type:

public class ConstructorExample {
   public static class Student {
      private String name;

      public Student(String name) {
         this.name = name;
      }

      public String getName() {
         return name;
      }

      public void setName(String name) {
         this.name = name;
      }
   }

   public static void main(String[] args) {
      Student student = new Student("John Doe"); 
      System.out.println(student.getName());
   }
}

Following is the output of the above code:

John Doe

Example 2

In the following example, we will take a constructor and try to return a value from it, which will result in a compilation error:

public class ConstructorExample {
   public static class Student {
      private String name;

      public Student(String name) {
         this.name = name;
         return name; // This line will cause a compilation error
      }

      public String getName() {
         return name;
      }

      public void setName(String name) {
         this.name = name;
      }
   }

   public static void main(String[] args) {
      Student student = new Student("John Doe"); 
      System.out.println(student.getName());
   }
}

Following is the output of the above code:

ConstructorExample.java:7: error: incompatible types: unexpected return value
         return name; // This line will cause a compilation error
                ^
1 error

In conclusion, constructors in Java do not have a return type, not even void. They are used to initialize the object when it is created and do not return any value explicitly.

Updated on: 2025-08-21T12:35:03+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements