We know that all objects that are created must be given initial values. We can do this by two approaches. The first approach uses the dot operator to access the instance variables and then assigns value to them individually. But it can be a tedious approach to initialize all the variables of all the objects individually.

And the second approach is using the help of a method like get_data() initialize each object individually.
          example:          object.get_data(15,10);

It would be more concise and simpler to initialize an object when it is first created. Constructors in java enables and object to initialize itself when it is first created.

Constructor has the same name as the class itself.  Secondly then do not specify a return type even void.

Constructors in java are of two types:-
1.  Default constructor
2.  Parameterized constructor

Default Constructor:- 

A constructor that does not have any parameter is known as default constructor.
Default constructor provides the default values to the object like 0, null etc. depending on the type.

             ex:    Rectangle r1=new Rectangel()

Note: If there is no constructor in a class, compiler automatically creates a default constructor.

EXAMPLE:

 


import java.util.Scanner;

class Rectangle
{
   int length,breadth;

   void display()
   {
        Scanner in=new Scanner(System.in);
        System.out.print("\n\n");
        System.out.println("length = "+length);
        System.out.println("breadth = "+breadth);
        System.out.print("\n");
   }
};
public class main_class
{
   public static void main(String args[])
   {
         Rectangle r1=new Rectangle();
         r1.display();
   }
}

OUTPUT:
 

PARAMETERIZED CONSTRUCTOR :

A constructor which have parameter is known as parameterized constructor.

                ex:    Rectangle r1=new Rectange(10,20);

A parameterized constructor is used to assign different values to distinct objects.

EXAMPLE:
 

import java.util.Scanner;

class Rectangle
{
   int length,breadth;

   Rectangle(int l,int b)
   {
        length=l;
        breadth=b;
   }

   void display()
   {
        Scanner in=new Scanner(System.in);
        System.out.print("\n\n");
        System.out.println("length = "+length);
        System.out.println("breadth = "+breadth);
        System.out.print("\n");
   }
};
public class main_class
{
   public static void main(String args[])
   {
         Rectangle r1=new Rectangle(10,20);
         Rectangle r2=new Rectangle(30,40);
         r1.display();
         r2.display();
   }
}

OUTPUT: