Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java

What is a default constructor in Java?

Tarun Telang

Overview

In Java, we have a default constructor that doesn't take any arguments. We typically use it to initialize fields to their default values.

The default value for the variables of numeric types such as byte, int, short, and long is 0. The default value for float and double is 0.0. The default value for boolean is false. The default value for the reference variables is null.

Syntax

We use the below syntax for the default constructor:

public class MyClass {
   public MyClass() {
   }
}
Syntax of the default constructor

Example

Below is an example of how we use a default constructor to initialize fields:

public class MyClass {
   private int x;
   private String y;

   public MyClass() {
      this.x = 5;
      this.y = "Educative";
   }

   public int getX() {
      return x;
   }

   public String getY() {
      return y;
   }

   public static void main(String[] args) {
     MyClass myClass = new MyClass();
     System.out.println(myClass.getX());
     System.out.println(myClass.getY()); 
   }
}
An example of how a default constructor works

Explanation

In the example above, we'll initialize the fields x and y to their default values (5 and "Educative", respectively).

What if you don't write a default constructor for a class?

If you don't write a default constructor, the compiler will automatically generate one. However, this may not always be what you want. For example, if you have fields that need to be initialized to non-default values, you'll need to write your constructor.

It's generally a good idea to write your own default constructor, even if you don't initialize any fields. This makes your code more precise and easier to understand.

Let's differentiate between a default constructor and a no-argument constructor. The main difference between the two is that a default constructor will initialize fields to their default values. In contrast, a no-argument constructor will not initialize any fields.

For example, consider the following class:

public class MyClass {

  private int x;
  public MyClass() { } // no-argument constructor
   
  public int getX() {
    return x;
  }
   
  public static void main(String[] args) {
    MyClass myClass = new MyClass();
    System.out.println(myClass.getX());
  }
}


An example of a no-argument constructor

In the example above, the no-argument constructor doesn't initialize the field x. This means that if we create an object of this class, the field x will have whatever value was assigned to it by the default constructor (which, in this case, is 0).

RELATED TAGS

java
RELATED COURSES

View all Courses

Keep Exploring