It is a function that has same name as the class name. It can’t have any return type , not even void. It is implicitly called whenever an object of a class is called. It is used to initialize the data members of the class

There are two types of constructors in java.

  1. Default constructor:- it doesn’t take any initializes all the data members. If no Constructor is defined in the class then java compiler gives you a default constructor which assigns default values to the data members according their data type.(this constructor is taken back from the java compiler if the user defines even one constructor of its own)
  2. parameterized constructor:– it takes arguments and assigns these values to the data members.
    Example of Constructor
Class Student
int age, String name;
public Student()                         //default constructor
Age= 10;
Name= "abc"}

public Student (int a)                    //parameterized Constructor

public Student (int a, String str)        //parameterized Constructor

Constructor overloading:

String str=”Computer”;
str.substrint(2); //output—> mputer (Extracts all the letters from index 2 to the last index.
str.substrint(2, 4); //output–>mp(Extracts letters from index 2 to 3)


Please enter your comment!
Please enter your name here