Breakdown of Your Code

Let’s analyze the structure of the parameterized constructor you provided:

Java

 
class Student {
    String name;
    int age;

    // Parameterized Constructor
    Student(String n, int a) { 
        name = n; // "n" is assigned to the object's name
        age = a;  // "a" is assigned to the object's age
    }
}
  • String n, int a: These are the parameters. They act as “placeholders” for the data you will send.

  • Assignment: The code inside the {} takes the values from the parameters and stores them in the class variables (name and age).


2. How to Use It (The Main Method)

When using a parameterized constructor, you provide the values inside the parentheses of the new statement.

Java

 
public class Main {
    public static void main(String[] args) {
        // One-line creation and initialization
        Student s1 = new Student("Ali", 15);
        Student s2 = new Student("Sara", 18);

        System.out.println(s1.name + " is " + s1.age); // Output: Ali is 15
        System.out.println(s2.name + " is " + s2.age); // Output: Sara is 18
    }
}

3. Advantages for Students

Using this type of constructor is standard practice in Java for several reasons:

  1. Efficiency: You don’t need to write s1.name = "Ali"; and s1.age = 15; on separate lines. It saves time and space.

  2. Mandatory Data: You can force a rule that “No student can be created without a name.” If someone tries to write new Student();, the code will not compile, preventing “empty” data errors.

  3. Multiple Objects: It makes it very easy to initialize hundreds of objects in a loop or an array.


4. Important Rule: The “Disappearing” Default Constructor

This is a very common Multiple Choice Question (MCQ) in university exams:

Rule: Once you define any parameterized constructor in your class, Java stops providing the automatic Default Constructor.

If you want to be able to create a student both ways—with data and without data—you must manually write both constructors in your class. This is called Constructor Overloading.


5. Summary Table

FeatureDefault ConstructorParameterized Constructor
ArgumentsNo arguments (Empty).Has one or more arguments.
ValuesAssigns default values (0, null).Assigns values provided by the user.
CreationProvided by Java automatically.Must be written by the programmer.
PurposeTo create a blank object.To create an object with specific data.

Practice Scenario:

Imagine you are building a Library System. You have a class Book.

  • Attributes: title, author.

  • Task: Create a parameterized constructor so you can create a book like this:

    Book b1 = new Book(“Java Basics”, “James Gosling”)