Default Constructor In Java

Java Default Constructor?

Default constructor in Java is a constructor with no parameters. The default constructor does nothing, but it enables all variables that are not initialized in their declaration to assume default values as follows:

  • Numeric data members are set too.
  • Boolean data memberrs are set to false.
  • String are set to null.

In practical programs, we often need to initialize the various data elements of the different object with different values when they are created. This can be achieved by passing the arguments to the constructor functions when the object is created.

Note: Even if we do not define any constructor explicitly, the compiler will automatically provide a default constructor implicitly.

Java Default Constructor Syntax:

      	public class MyClass{
   //This is the constructor
   MyClass(){
   }
   ..
}

Java Default Constructor Example 1:



Output :

Object created and i = 5

Java Default Constructor Example 2:



Output :

 a = 0
 b = false