Is the return type of a constructor void?

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes:

Example

Create a constructor:

// Create a Main class
public class Main {
  int x;  // Create a class attribute

  // Create a class constructor for the Main class
  public Main() {
    x = 5;  // Set the initial value for the class attribute x
  }

  public static void main(String[] args) {
    Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
    System.out.println(myObj.x); // Print the value of x
  }
}

// Outputs 5

Try it Yourself »

Note that the constructor name must match the class name, and it cannot have a return type (like void).

Also note that the constructor is called when the object is created.

All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.



Constructor Parameters

Constructors can also take parameters, which is used to initialize attributes.

The following example adds an int y parameter to the constructor. Inside the constructor we set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5:

A constructor is similar to method and it is invoked at the time 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.

Return type of a constructor

  • A constructor doesn’t have any return type.
  • The data type of the value retuned 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.

Example

Following is an example of a constructor in java −

Live Demo

public class Sample{
   public Sample(){
      System.out.println("Hello how are you");
   }  
   public Sample(String data){
      System.out.println(data);
   }  
   public static void main(String args[]){
      Sample obj = new Sample("Tutorialspoint");
   }  
}

Output

Tutorialspoint

Example

Live Demo

class Student{
   Integer age;
   Student(Integer age){
      this.age = age;
   }
   public void display() {
      System.out.println("Value of age: "+this.age);  
   }
}
public class GenericsExample {  
   public static void main(String args[]) {
      Student std = new Student(25);
      std.display();
   }
}

Output

Value of age: 25

Is the return type of a constructor void?


Is the return type of a constructor void?

Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. Mostly it is used to instantiate the instance variables of a class.

If the programmer doesn’t write a constructor the compiler writes a constructors on his behalf.

Example

If you closely observe the declaration of the constructor in the following example it just have the name of the constructor which is similar to class and, the parameters. It does not have any return type.

First, we'll get familiar with how object initialization works in Java and the JVM. Then, we'll dig deeper to see how object initialization and assignment work under-the-hood.

2. Instance Initialization

Let's start with an empty class:

public class Color {}

Here, we're going to create an instance from this class and assign it to some variable:

Color color = new Color();

After compiling this simple Java snippet, let's take a peek at its bytecode via the javap -c command:

0: new           #7                  // class Color
3: dup
4: invokespecial #9                  // Method Color."":()V
7: astore_1

When we instantiate an object in Java, the JVM performs the following operations:

  1. First, it finds a place in its process space for the new object.
  2. Then, the JVM performs the system initialization process. In this step, it creates the object in its default state. The new opcode in the bytecode is actually responsible for this step.
  3. Finally, it initializes the object with the constructor and other initializer blocks. In this case, the invokespecial opcode calls the constructor.

As shown above, the method signature for the default constructor is:

Method Color."":()V

The  is the name of instance initialization methods in the JVM. In this case, the  is a function that:

  • takes nothing as the input (empty parentheses after the method name)
  • returns nothing (V stands for void)

Therefore, the return type of a constructor in Java and JVM is void.

Taking another look at our simple assignment:

Color color = new Color();

Now that we know the constructor returns void, let's see how the assignment works.

3. How Assignment Works

JVM is a stack-based virtual machine. Each stack consists of stack frames. Put simply, each stack frame corresponds to a method call. In fact, JVM creates frames with a new method call and destroys them as they finish their job:

Each stack frame uses an array to store local variables and an operand stack to store partial results. Given that, let's take another look at the bytecode:

0: new           #7                // class Color
3: dup
4: invokespecial #9               // Method Color."":()V
7: astore_1

Here's how the assignment works:

  • The new instruction creates an instance of Color and pushes its reference onto the operand stack
  • The dup opcode duplicates the last item on the operand stack
  • The invokespecial takes the duplicated reference and consumes it for initialization. After this, only the original reference remains on the operand stack
  • The astore_1 stores the original reference to index 1 of the local variables array. The prefix “a” means that the item to be stored is an object reference, and the “1” is the array index

From now on, the second item (index 1) in the local variables array is a reference to the newly created object. Therefore, we don't lose the reference, and the assignment actually works — even when the constructor returns nothing!

4. Conclusion

In this quick tutorial, we learned how the JVM creates and initializes our class instances. Moreover, we saw how the instance initialization works under-the-hood.

For an even more detailed understanding of the JVM, it's always a good idea to check out its specification.

What is the return type of a constructor?

Therefore, the return type of a constructor in Java and JVM is void.

Does a constructor have a void return type in Java?

Note that the constructor name must match the class name, and it cannot have a return type (like void ). Also note that the constructor is called when the object is created.

Does void count as a return type?

In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value. You may or may not use the return statement, as there is no return value.

Can constructors return value return void?

No, constructor does not return any value.