Skip to main content

 

Java Constructors

  • A constructor is a method-like section of code. 
  • When a new instance of the class is created, it is called. 
  • Storage space for the object is allocated in the memory at the time the constructor is called.
  • To initialize the object, a unique kind of method is employed.
  • A constructor is invoked each time an object is created with the new() keyword.


What is the Purpose of creating constructor?


The purpose of a using constructor in Java programming language is to construct an object and assign values to the object's members. 

Rules for creating Java constructor

There are two rules defined for the constructor.
  • Constructor name must be the same as its class name
  • A Constructor must have no explicit return type
  • A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


      1. Default constructor
    2. No argument constructor
    3. Parameterized constructor

1. Default constructor

        The constructor is used to give the default values to the variables respect to its data type. For example it assigns '0' to the numerical type of variables, 'null' to the string type of variables etc. 

Syntax:
  
      <class name>() 
      {  }


Example
      
public class defaultconst{                                           
int a;
String b;
char c;
public defaultconst(){
}
public static void main(String[] s){
defaultconst dc=new defaultconst();
System.out.println(dc.a+" , "+dc.b+","+dc.c);
}
}

output


In the above example, noargconst() is the constructor and does not have the parameter list. Since it will be invoked when creating the object name 'dc'.

2. No-argument constructor

  • A constructor defined without any argument is called a No-Argument constructor.
  • It’s like overriding the default constructor.
  • It is used to do some pre-initialization tasks such as checking resources, network connections, logging, etc. 
Syntax:
  
      <class name>() 
      {  
        statements;
      }

Example
      
public class noargconst                                              
{
  int a=50;
  int b=60;
  public noargconst()
  {
    System.out.println("Sum of "+a+" and "+b+" is "+(a+b));
  }
  public static void main(String[] s)
  {
    noargconst dc=new noargconst();
  }
}

output


In the above example, noargconst() is the constructor and does not have the parameter list. Since it will be invoked when creating the object name 'dc'.

3. Parameterized constructor

  • If a constructor has a specific number of parameters then we call the constructor as parameterized constructor.
  • The values to be assigned while creating the object name.
  • This kind of constructor is used to provide different values for distinct object names. 
Syntax:
  
      <class name>(data type parameter1, data type parameter2,..) 
      {  
        statements;
      }

Example

public class paraconst                                               
{                                                                    
  public paraconst(int a, int b)                                     
  {                                                                  
     System.out.println("Sum of "+a+" and "+b+" is "+(a+b));         
  }                                                                  
  public static void main(String[] s)                                
  {                                                                  
    paraconst d0=new paraconst(100,50);                              
    paraconst d1=new paraconst(-50,50);                              
    paraconst d2=new paraconst(134,89);                              
  }                                                                  
}                                                                    

output



In the above example, paraconst() is the constructor and has two parameters, such as 'a' and 'b'. If we pass the parameters, we will assign the values when creating object names. 'd0', 'd1', and 'd2' are the object names for the class paraconst(). Though, here, different values are assigned for the different objects. We can assign the same values to all objects, but it is not necessary.


We can use all constructors in a program like follows

class shapes                                                         
{                                                                    
   shapes()                                                          
  {                                                                  
       System.out.println("Welcome to the program");                 
  }                                                                  
  shapes(int i,int j)                                                
  {                                                                  
      System.out.println("Area of square is"+i*j);                     }                                                                  
  shapes(int r)                                                      
  {                                                                  
        System.out.println("Area of a circle"+3.14*r*r);             
   }                                                                 
}                                                                    
public class area                                                    
{                                                                    
   public static void main(String s[])                               
   {                                                                 
        shapes s0=new shapes();                                      
        shapes s1=new shapes(10,15);                                 
        shapes s2=new shapes(20);                                    
    }                                                                
}                                                                    

Output



By 
Dr. Karthigai Selvi
Galgotias University
India

Comments

Popular posts from this blog

How to pass an object as an argument in Java programming? We know that the concept of calling a method as pass by value and pass by reference. Java allows us to pass primitive types of data when calling a method that is called as 'a method call by value' or 'passed by value'. In the same manner, we can create an object by passing primitive type of data using constructors.  Java allows us to create an object by passing reference of another object ie. One Object can be passed to another object. This is called as 'call by reference' or 'passed by reference'.  Syntax     <class name> <object name1>=new <class name>;      <class name> <object name2> ;     <object name2>=<object name1>; Example Program class test {      int i;      test(int a)      {      i=a;      }      int testmethod(test t)     ...
  Introduction to Java (For B.Tech/BCA Students) Java is a powerful, high-level programming language widely used in academic learning and professional software development. Developed in the mid-1990s, Java was designed with the goal of creating programs that can run on different types of computers without needing major changes. This platform independence is achieved through the concept of “write once, run anywhere,” making Java especially valuable in today’s diverse computing environment. For B.Tech students, Java serves as an excellent foundation for understanding core programming concepts. It fully supports object-oriented programming (OOP), including classes, objects, inheritance, polymorphism, abstraction, and encapsulation. These concepts are essential for building structured, reusable, and scalable software systems, which are central to modern computer science and engineering education. Java programs are compiled into an intermediate form called bytecode, which runs on th...
  Identifiers, Literals, Operators and Separators in Java Programming Language Here is a clear introduction (exam-ready + student-friendly) to Identifiers, Literals, Separators, and Operators in programming (especially Java/C-style languages). 🔹 Identifiers An identifier is the name given to a variable, method, class, array, or any user-defined item in a program. It helps identify these elements uniquely. ✔ Rules for Identifiers (Java) Must begin with a letter (A–Z or a–z), underscore (_), or dollar sign ($) Cannot start with a number Cannot be a reserved keyword Case-sensitive ( total and Total are different) No spaces allowed Examples ✔ Valid Identifiers int age; double totalMarks; String studentName; int _count; ❌ Invalid Identifiers int 2value;       // starts with number int total marks; // contains space int class;        // keyword 👉 ...