Tutorialspoint

1 Answer
Arushi

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.

A program that demonstrates this is given as follows:

Example

 Live Demo

class NumberValue {
   private int num;
   public void display() {
      System.out.println("The number is: " + num);
   }
}
public class Demo {
   public static void main(String[] args) {
      NumberValue obj = new NumberValue();
      obj.display();
   }
}

Output

The number is: 0

Now let us understand the above program.

The NumberValue class is created with a data member num and single member function display() that displays the value of num. A code snippet which demonstrates this is as follows:

class NumberValue {
   private int num;
   public void display() {
      System.out.println("The number is: " + num);
   }
}

In the main() method, an object obj of class NumberValue is created and the default constructor is called. Then display() method is called. A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String[] args) {
      NumberValue obj = new NumberValue();
      obj.display();
   }
}

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.