Does Constructor Return Any Value in Java



No, the constructor does not return any value.

  • While declaring a constructor you will not have anything like a return type.
  • In general, the Constructor is implicitly called at the time of instantiation.
  • And it is not a method, its sole purpose is to initialize the instance variables.

Read more about constructors: Java Constructors 

Example

public class Sample{
   public Sample(){
      System.out.println("This is a constructor");
   }
   public static void main(String args[]){
      Sample obj = new Sample();
   }
}

Output

This is a constructor

Code explanation

The class Sample has a constructor that prints "This is a constructor". When we create an object using new Sample(), the constructor is called automatically, and the message is printed. The constructor doesn't return anything; its only job is to initialize the object.

Updated on: 2024-10-23T17:34:48+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements