What is the use of constructor in Java?

JavaServer Side ProgrammingProgramming

A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class and, have no return type.

There are two types of constructors parameterized constructors and no-arg constructors the main purpose of a constructor is to initialize the instance variables of a class.

Example

In the following example we are trying to initialize the instance variables of a class using no-arg constructor.

Live Demo

public class Test {
   int num;
   String data;
   Test(){
      num = 100;
      data = "sample";
   }
   public static void main(String args[]){
      Test obj = new Test();
      System.out.println(obj.num);
      System.out.println(obj.data);
   }
}

Output

100
sample

Example

In the following example we are trying to initialize the instance variables of a class using parameterized constructor.

Live Demo

import java.util.Scanner;
public class Test {
   int num;
   String data;
   Test(int num, String data){
      this.num = num;
      this.data = data;
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a string value: ");
      String data = sc.nextLine();
      System.out.println("Enter an integer value: ");
      int num = sc.nextInt();
     
      Test obj = new Test(num, data);
      System.out.println(obj.num);
      System.out.println(obj.data);
   }
}

Output

Enter a string value:
sample
Enter an integer value:
1023
1023
sample
raja
Published on 05-Feb-2021 10:29:57
Advertisements