What is the Purpose of Default Constructor in Java

In object-orientated programming, the constructor plays an important role. A constructor is similar to the member functions of the class. However, their signature and purpose differ. The constructors have no return type, unlike the methods. Also, the constructor name always matches with the class, which makes it easily identifiable.

In general, there are three types of constructors:

  1. Default Constructor
  2. No-Argument Constructor
  3. Parameterized Constructor

Out of these, the default constructor is a constructor which the java compiler itself includes within the code if the user forgets to add one. The default constructor’s purpose is to initialize the objects with default values. It assigns the following default values:

  1. A null value for objects
  2. 0.0 for float and double variables.
  3. False for boolean
  4. 0 for byte, short, int, and long variables.

If you compile and run the following code, you will get the output 0, because the default constructor will assign 0 value to the integer variable.

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

Output:

0

Leave a Comment

Your email address will not be published. Required fields are marked *