What do you mean by default constructor in Java?

JavaServer Side ProgrammingProgramming

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 and, have no return type.

The default constructor in Java initializes the data members of the class to their default values such as 0 for int, 0.0 for double etc. This constructor is implemented by default by the Java compiler if there is no explicit constructor implemented by the user for the class.

If you observe the following example, we are not providing any constructor to it.

public class Sample {
   int num;
   public static void main(String args[]){
      System.out.println(new Sample().num);
   }
}

If you compile and run the above program the default constructor initializes the integer variable num with 0 and, you will get 0 as result.

The javap command displays information about the fields, constructors, and methods of a class. If you (after compiling it) run the above class using javap command,  you can observe the default constructor added by the compiler as shown below −

D:\>javap Sample
Compiled from "Sample.java"
public class Sample {
   int num;
   public Sample();
   public static void main(java.lang.String[]);
}

Example

Live Demo

public class Sample{
   int num;
   Sample(){
      num = 100;
   }
   Sample(int num){
      this.num = num;
   }
   public static void main(String args[]){
      System.out.println(new Sample().num);
      System.out.println(new Sample(1000).num);
   }
}

Output

100
1000
raja
Published on 06-Feb-2021 09:03:09
Advertisements