Constructor in Java: Syntax, Purpose and Examples

A constructor in Java is a special block of code with the same name as the class and no return type. It runs automatically when you create an object using the new keyword, setting the object’s fields to valid starting values. Java provides a default no-argument constructor if you do not write one yourself.

Key Takeaways

  • A constructor shares its name with the class and has no return type.
  • Java provides a default no-argument constructor automatically if you don’t write one.
  • A parameterised constructor lets you pass values at object creation time.
  • You can call one constructor from another using this().
  • Constructors are the cleanest way to enforce mandatory fields and avoid null-pointer surprises.

What a Constructor Is

Every time you write new Student() in Java, the JVM allocates memory for the object and then immediately calls a constructor. That constructor is your chance to give the object a valid, usable starting state before any other code touches it. Without a constructor, you’d have to call a dozen setter methods after every new, and you’d inevitably forget one.

According to the Oracle Java documentation, a constructor declaration looks like a method declaration, except it uses the name of the class and has no return type. That last point trips up a lot of beginners: if you accidentally write void Student(), Java treats it as a regular method, not a constructor, and your object won’t be initialised the way you expect.

The Default Constructor

If you write a class without any constructor at all, the Java compiler quietly inserts a no-argument constructor for you. This default constructor sets numeric fields to 0, booleans to false, and object references to null. The moment you write even one explicit constructor, the compiler stops providing the default, so you have to add the no-arg version yourself if you still need it.

This is one of the most common interview questions at Indian tech companies and product startups alike: “What happens to the default constructor when you define a parameterised constructor?” The answer: it disappears. You get a NoSuchMethodException at runtime if any code tries to call the no-arg constructor and you haven’t defined it. Understanding this early saves hours of debugging.

Constructor vs Method: The Core Difference

Feature Constructor Method
Name Must match the class name exactly Can be any valid identifier
Return type None, not even void Must declare a return type
Called by JVM automatically via new Explicitly by programmer
Purpose Initialise object state Define object behaviour
Inheritance Not inherited Inherited (if not private)

Constructor Syntax in Java

The syntax of a constructor in Java follows a straightforward pattern. The access modifier is optional but usually public. Then comes the class name, then the parameter list in parentheses, then the body in curly braces. There is no return type anywhere in that declaration.

  • AccessModifier ClassName(ParameterList) { body }
  • Access modifier: public, protected, private, or package-private
  • ClassName: must match the class declaration exactly, including capitalisation
  • ParameterList: zero or more comma-separated typed parameters
  • Body: any valid Java statements, typically field assignments

A Minimal Working Example

Imagine you’re building a student management system for a college, a common project in BCA and BSc CS programmes. You have a Student class with two fields: name and rollNumber.

The no-argument version: the constructor is named Student, takes no parameters, and assigns default values to both fields. When you write Student s = new Student();, Java calls that constructor and s immediately has name set to "Unknown" and rollNumber set to 0. The object is ready to use.

public class Student {
    String name;
    int rollNumber;

    // No-arg constructor
    public Student() {
        this.name = "Unknown";
        this.rollNumber = 0;
    }

    // Parameterised constructor
    public Student(String name, int rollNumber) {
        this.name = name;
        this.rollNumber = rollNumber;
    }
}

If you’re just starting out with compiled languages, it helps to understand how the compile-and-run cycle works. Our guide on how to write, compile and run a C program explains the underlying process in a way that transfers directly to Java.

Constructor Overloading

Java lets you define multiple constructors in the same class as long as their parameter lists differ. This is called constructor overloading. A Student class could have one constructor that takes no arguments, one that takes just a name, and one that takes both a name and a roll number. Java picks the right one based on what you pass to new.

The Stack Overflow Developer Survey 2024 shows Java remains a top-five most-used language among professional developers globally, with roughly 30% of respondents using it regularly. Constructor overloading is one of the first object-oriented concepts those developers learn, and for good reason: it makes your classes flexible without forcing the caller to supply data they don’t have yet.

According to the TIOBE Index (April 2025), Java consistently ranks among the top three programming languages worldwide, reflecting its continued dominance in enterprise and Android development. This makes constructor knowledge a near-universal requirement in technical hiring screens.

Parameterised Constructors

A parameter constructor in Java accepts one or more arguments so you can pass specific values at the moment of object creation. Instead of creating a blank object and then setting each field, you hand the data directly to the constructor and get a fully initialised object back in one step.

For the Student example: Student s = new Student("Priya Sharma", 1042); calls the two-argument constructor, which assigns "Priya Sharma" to name and 1042 to rollNumber inside its body. One line, done. Compare that to creating a blank object and calling two setters: three lines, three chances to forget a step.

Using this() for Constructor Chaining

When you have overloaded constructors and they share setup logic, you can call one constructor from another using this(). The call to this() must be the very first statement in the constructor body. This keeps your initialisation logic in one place and stops you from copying the same code across multiple constructors.

A practical tip from production codebases: always put your most complete constructor at the bottom and chain the simpler ones up to it. That way, adding a new field means editing one place, not hunting through four overloaded constructors. It’s the kind of discipline that separates clean, maintainable code from the kind that causes Java exceptions and common runtime errors six months after you wrote it.

The String Class Constructor in Java

The String class constructor in Java is a great real-world example of parameterised constructors in action. String has multiple constructors: one that takes a String literal, one that takes a char array, one that takes a byte array with a charset, and more. When you write new String("hello"), you’re calling the parameterised constructor that accepts a String argument. Most developers use string literals for performance reasons, but knowing the constructors exist matters when you’re converting byte streams from network sockets or file I/O.

Why We Use Constructors

The purpose of a constructor in Java goes beyond convenience. Constructors enforce the rule that an object can’t exist in an invalid state. If your BankAccount class requires an account number and an initial balance, you put both as required parameters in the constructor. There’s no way to create a BankAccount without them. That’s a guarantee no setter-based approach can match.

According to a 2023 analysis by JetBrains on Java usage patterns, improper object initialisation is among the top causes of NullPointerException bugs in production Java applications. Constructors, used correctly, eliminate entire categories of that problem before the code even compiles.

Constructors in Real Projects

In enterprise Java, frameworks like Spring and Hibernate use constructors heavily. Spring’s recommended style since version 4.3 is constructor injection for dependencies, meaning your service classes receive their dependencies through the constructor rather than through field-level annotations. This makes the code testable, explicit and easier to reason about during code review.

If you’re studying for a BSc Computer Science subjects and scope degree or planning your career path after an MCA, understanding constructors at this depth is what gets you through technical interviews. Hiring managers at Indian IT firms like Infosys, TCS and Wipro routinely ask candidates to write a parameterised constructor on a whiteboard and explain constructor chaining. According to AmbitionBox (2024), Java developers in India earn an average annual salary of Rs 5.5 to Rs 12 lakh depending on experience, with OOP proficiency listed as a core requirement across job postings at these firms.

Common Mistakes to Avoid

  • Adding a return type: Writing public void Student() makes it a method, not a constructor. The compiler won’t warn you; the object just won’t initialise as expected.
  • Forgetting the no-arg constructor: Once you add a parameterised constructor, the default disappears. Add it back explicitly if any framework or serialisation library needs it.
  • Doing too much work in the constructor: Heavy logic, database calls or file I/O inside a constructor makes testing painful and objects slow to create. Keep constructors lean.
  • Calling overridable methods from a constructor: If a subclass overrides that method, the parent constructor calls the child’s version before the child is fully initialised. That’s a subtle bug that bites hard.

Strong object-oriented fundamentals like these are also the foundation for secure coding practices. If you’re thinking about a career in cybersecurity or ethical hacking, the software development tools to learn first will directly support that path. Professionals exploring roles like full stack developer vs software developer will find Java constructor knowledge appears in both tracks.

For those eyeing postgraduate career options, check out what jobs and salary after MCA look like in the current market. Java skills, including a solid grip on OOP concepts like constructors, consistently appear in the job descriptions for the roles that pay best.

Frequently Asked Questions

What is a constructor in Java?

A constructor in Java is a special block of code with the same name as the class and no return type. It runs automatically when you create an object using the new keyword. Its job is to initialise the object’s fields so the object is in a valid, usable state from the moment it’s created.

What is the syntax of a constructor in Java?

The constructor syntax in Java is: AccessModifier ClassName(ParameterList) { body }. There is no return type, not even void. The class name must match exactly, including capitalisation. The parameter list can be empty for a no-arg constructor or contain one or more typed parameters for a parameterised constructor.

Why do we use constructors in Java?

We use constructors to guarantee that every object starts life in a valid state. They enforce mandatory fields, eliminate the need for repetitive setter calls after object creation, and prevent null-pointer bugs caused by uninitialised fields. Frameworks like Spring also use constructor injection to make dependencies explicit and code testable.

A Java constructor is like a method without what?

A Java constructor is like a method without a return type. It also differs from a regular method in that it must share its name with the class, is called automatically by the JVM when you use new, and is not inherited by subclasses. If you add a return type, Java treats the declaration as a method, not a constructor.

What is constructor overloading in Java?

Constructor overloading in Java means defining more than one constructor in the same class, each with a different parameter list. Java selects the correct constructor based on the arguments you pass to new. This lets you create objects with varying levels of detail without forcing callers to supply data they don’t have.

Can a constructor be private in Java?

Yes. A private constructor prevents any code outside the class from creating an instance directly using new. This pattern is used in the Singleton design pattern, where only one instance of a class should ever exist, and in utility classes that expose only static methods and should never be instantiated.

How do I create a constructor in Java?

To create a constructor in Java, write a block inside your class that has the same name as the class, no return type, and any parameters you need. Assign your field values inside the body. Then call it with new ClassName(arguments). If you need multiple versions, overload the constructor by varying the parameter list.

Constructors in Java are the foundation of clean, predictable object-oriented code. Get them right and you eliminate an entire class of bugs before they happen. Here are three things you can do this week to cement the concept:

  1. Write a BankAccount class with a no-arg constructor and a two-argument parameterised constructor, then use this() to chain them. Compile and run it.
  2. Read the Oracle Java tutorial on constructors to see the official specification and edge cases.
  3. If you want to apply Java and secure coding skills in a high-demand career, explore the CEH v13 AI online course at 3.0 University, or browse the 3.0 University online certification courses covering Ethical Hacking, AI, Blockchain and Web3. Programming fundamentals like what you’ve just read are the starting point for every one of those tracks.

Last updated: June 2025. Reviewed by the 3University editorial team.

We create, review, and maintain educational content covering Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain, Web3, and emerging technologies.

Read More Articles