1.

Role of default constructor in Java

Answer»

A default constructor is a constructor without PARAMETERS that is automatically created if there is no constructor written by the programmer. All the DATA MEMBERS in a class are initialized by the default constructor to their default values.

The default values of numeric data types is 0, of references is null, of floating point numbers is 0.0 and of booleans is false.

A program that demonstrates a default constructor in Java is given as follows:

class Student {   INT rollNumber;   String name;   float MARKS; } public class Demo {    public static void main(String args[])    {      Student s = new Student();      System.out.println(s.rollNumber);      System.out.println(s.name);      System.out.println(s.marks);    } }

The output of the above program is as follows:

0 null 0.0

In the above program, the default constructor is called when an object s of class Student is created. Then the default values of the data members of class Student are printed.



Discussion

No Comment Found