Default constructor in java

Default or no-argument constructor

A constructor which does not have any parameter is called default or no-argument constructor. If no constructor is available within the class then java compiler automatically or robotically creates a default constructor on the time of compilation.

Syntax:

ClassName(){
       //Block of statements (Optional)
}

Why default constructor is used?

Default constructor is used to provide default values to the object properties i.e. to provide default state of an object.

Example

/**
 * This program is used to show the use of default constructor.
 * @author W3spoint
 */
public class DefaultConstructor  {
                String dataMember1;
                int dataMember2;
                DefaultConstructor (){
                       System.out.println("Default Constructor called.");
                }
 
                public static void main(String args[]){
                       //constructor call
                       DefaultConstructor obj1 = 
                                      new DefaultConstructor();
 
                       //print default values of object properties.
                       System.out.println("dataMember1= " + obj1.dataMember1);
                       System.out.println("dataMember2= " + obj1.dataMember2);
                }
}

Output

Default Constructor called.
dataMember1= null
dataMember2= 0

Java interview questions on constructor

Please Share