1. Write a program that uses a parameterized constructor to initialize and display object values?
Algorithm :
- Start
- Class Declaration: A class named Demo is defined with two instance variables: id (int) and name (String).
- Constructor Definition: A parameterized constructor is created to accept and assign values to id and name.
- Display Method: The display() method is defined to print the values of id and name for a student object.
- Main Method Execution: The program starts executing from the main method.
- Object Creation (s1): The first Demo object s1 is created with the values 101 and “Alice”, which are passed to the constructor.
- Object Creation (s2): The second Demo object s2 is created with the values 102 and “Ram”, also passed to the constructor.
- Display Calls: The display() method is called on both s1 and s2, resulting in their respective details being printed.
- End
Program :
class Demo { int id; String name; Demo(int i, String n) { id = i; name = n; } void display() { System.out.println(“ID: ” + id + “, Name: ” + name); } public static void main(String[] args) { Student s1 = new Demo(101, “Alice”); Student s2 = new Demo(102, “Ram”); s1.display(); s2.display(); } } |
Output :
ID: 101, Name: Alice ID: 102, Name: Ram |
Explanation :
The program defines a Demo class with id and name as its attributes. A parameterized constructor is provided, allowing values to be passed during object creation. This constructor initializes the id and name fields with the given parameters. In the main method, two demo objects, s1 and s2, are instantiated using the constructor with different values. s1 is initialized with 101 and “Alice”, while s2 is initialized with 102 and “Ram”. When the display() method is called on each object, it prints the stored values. This demonstrates the use of parameterized constructors to assign different values to multiple instances. |
2. Write a program to show constructor overloading with different parameters?
Algorithm :
- Start
- Class Definition: A class Student is defined with two attributes: id (int) and name (String).
- Default Constructor: A constructor with no parameters initializes id to 0 and name to “Not assigned”.
- Parameterized Constructor: Another constructor takes two parameters (int i, String n) and assigns them to id and name.
- Display Method: A method display() prints the values of id and name.
- Main Method Begins: Execution starts in the main method.
- Creating Object s1: The default constructor is called, initializing s1 with id = 0 and name = “Not assigned”.
- Creating Object s2: The parameterized constructor is used to create s2 with id = 103 and name = “Charlie”.
- Calling display(): s1.display() and s2.display() print their respective values to the console.
- End
Program :
class Student { int id; String name; Student() { id = 0; name = “Ram”; } Student(int i, String n) { id = i; name = n; } void display() { System.out.println(“ID: ” + id + “, Name: ” + name); } public static void main(String[] args) { Student s1 = new Student(); Student s2 = new Student(103, “Charlie”); s1.display(); s2.display(); } } |
Output :
ID: 0, Name: Ram ID: 103, Name: Charlie |
Explanation :
This program defines a Student class with two constructors—one default and one parameterized. The default constructor initializes a student with id as 0 and name as “Not assigned”, used when no arguments are provided. The parameterized constructor is used when specific values are passed during object creation. In the main method, s1 is created using the default constructor, while s2 is created with the values 103 and “Charlie”. Each object has its own set of data depending on which constructor is used. The display() method is called for both objects to print their information. This illustrates how constructor overloading allows flexibility in object initialization. |
3. Write a program to demonstrate constructor chaining using this()?
Algorithm :
- Start
- Class Definition: The class Student is defined with instance variables id and name.
- Default Constructor: The default constructor uses this(104, “Default Name”) to call the parameterized constructor with predefined values.
- Parameterized Constructor: Accepts two parameters (int i, String n) and assigns them to id and name.
- Display Method: A method display() is defined to print the id and name.
- Main Method Begins: Execution starts from the main method.
- Creating Object s1: The default constructor is invoked, which internally calls the parameterized constructor with 104 and “Default Name”.
- Calling display(): The display() method prints ID: 104, Name: Default Name.
- End
Program :
class Student { int id; String name; Student() { this(104, “Default Name”); } Student(int i, String n) { id = i; name = n; } void display() { System.out.println(“ID: ” + id + “, Name: ” + name); } public static void main(String[] args) { Student s1 = new Student(); s1.display(); } } |
Output :
ID: 104, Name: Default Name |
Explanation :
The program defines a Student class with a default and a parameterized constructor. The default constructor does not directly assign values but instead uses this(104, “Default Name”) to call the parameterized constructor. This approach leverages constructor chaining, a technique to reuse constructor logic within the same class. When the main method executes, it creates an instance s1 using the default constructor. Internally, it forwards the control to the parameterized constructor, which sets id to 104 and name to “Default Name”. After object creation, the display() method is called. It prints the values of the object’s fields, confirming successful constructor chaining and initialization. |
4. Write a program that uses a no argument constructor to initialize and display object values?
Algorithm :
- Start
- Class Definition: The Student class is defined with two attributes: id (integer) and name (String).
- Constructor Declaration: A no argument constructor is created, which sets id = 1 and name = “John”.
- Display Method: The display() method prints the student’s id and name to the console.
- Main Method Starts: Execution begins in the main method.
- Object Creation: A new object s1 of the Student class is created. The default constructor is called automatically.
- Values Initialized: The constructor assigns the values id = 1 and name = “John” to the object s1.
- Method Call: s1.display() is called, printing ID: 1, Name: John to the console.
- End
Program :
class Student { int id; String name; Student() { id = 1; name = “John”; } void display() { System.out.println(“ID: ” + id + “, Name: ” + name); } public static void main(String[] args) { Student s1 = new Student(); s1.display(); } } |
Output :
ID: 1, Name: John |
Explanation :
The program begins with the definition of a class named Student, containing two member variables: id and name. A default constructor is used to assign the values 1 and “John” to these fields. The class also includes a display() method that prints the values of the object’s fields. In the main method, an instance s1 of the Student class is created. When the object is instantiated, the default constructor initializes the values. Then, the display() method is called on the object, resulting in the output being printed. The output confirms that the object was correctly initialized with the default constructor values. |
5. Write a program that counts how many objects are created of a class using a static variable in the constructor?
Algorithm :
- Start
- Class Definition: The Student class is defined with a static variable count initialized to 0.
- Constructor: The default constructor increments the static count variable by 1 every time a new object is created.
- Static Method showCount(): This method prints the total number of Student objects created using the count variable.
- Main Method Begins: Execution starts from the main method.
- Object Creation: Three objects (s1, s2, s3) are created sequentially, each triggering the constructor.
- Incrementing Count: With each object creation, the constructor increments count by 1 (so count becomes 3).
- Calling Static Method: The static method Student.showCount() is called, which prints Objects created: 3.
- End
Program :
class Student { static int count = 0; Student() { count++; } static void showCount() { System.out.println(“Objects created: ” + count); } public static void main(String[] args) { Student s1 = new Student(); Student s2 = new Student(); Student s3 = new Student(); Student.showCount(); } } |
Output :
Objects created: 3 |
Explanation :
This program demonstrates the use of a static variable and static method in the Student class. The static variable count keeps track of how many Student objects have been created. Every time a new object is instantiated, the constructor increments the count variable. Since count is static, it is shared among all instances of the class rather than being duplicated per object. In the main method, three objects are created, which increases count to 3. The static method showCount() is then called to display the total number of objects created. This method accesses the shared static variable and prints Objects created: 3, reflecting how static members function at the class level. |
6. Write a program that demonstrates a custom copy constructor?
Algorithm :
- Start
- Class Definition: The class Student is created with instance variables id and name.
- Parameterized Constructor: Initializes a student object with the values provided (int i, String n).
- Copy Constructor: Accepts another Student object s and copies its id and name values to the new object.
- Display Method: Prints the values of id and name for a student object.
- Main Method Execution Starts: Execution begins in the main method.
- Object Creation (s1): s1 is created using the parameterized constructor with id = 105 and name = “David”.
- Copy Constructor Call (s2): s2 is created using the copy constructor, which copies the values from s1.
- Calling display(): Both s1.display() and s2.display() print ID: 105, Name: David.
- End
Program :
class Student { int id; String name; Student(int i, String n) { id = i; name = n; } Student(Student s) { id = s.id; name = s.name; } void display() { System.out.println(“ID: ” + id + “, Name: ” + name); } public static void main(String[] args) { Student s1 = new Student(105, “David”); Student s2 = new Student(s1); // Copy constructor s1.display(); s2.display(); } } |
Output :
ID: 105, Name: David ID: 105, Name: David |
Explanation :
This program illustrates how a copy constructor works in Java. A parameterized constructor is used to initialize a Student object (s1) with specific values. A second constructor, known as the copy constructor, takes another Student object and copies its id and name. In the main method, s1 is created with id = 105 and name = “David”, and then s2 is created by copying s1. This ensures that s2 contains the same data as s1, demonstrating object duplication. The display() method prints the values stored in both objects. Since both refer to identical values, the output confirms the copy was successful. This is useful when you need to duplicate an object without affecting the original. |
7. Write a program that shows the order in which constructors are called in a class hierarchy using inheritance?
Algorithm :
- Start
- Parent Class Definition: A class named Parent is defined with a constructor that prints “Parent constructor called”.
- Child Class Definition: The Child class extends Parent, meaning it inherits from it.
- Child Constructor: The constructor of the Child class prints “Child constructor called”.
- Main Method Starts: Program execution begins in the main method.
- Object Creation (c): A new object of the Child class is created.
- Constructor Chain Execution: When Child is instantiated, Java automatically calls the Parent class constructor first (implicit super() call).
- Output Generation: The Parent constructor runs and prints its message, followed by the Child constructor, which prints its message.
- End
Program :
class Parent { Parent() { System.out.println(“Parent constructor called”); } } class Child extends Parent { Child() { System.out.println(“Child constructor called”); } public static void main(String[] args) { Child c = new Child(); } } |
Output :
Parent constructor called Child constructor called |
Explanation :
This Java program demonstrates constructor chaining in inheritance. The Child class extends the Parent class, meaning it inherits all accessible features of the Parent. When an object of the Child class is created, the Parent class constructor is called first, even though it’s not explicitly invoked—Java does this implicitly through super(). The Parent constructor prints “Parent constructor called”, and then the Child constructor prints “Child constructor called”. This shows that in an inheritance hierarchy, base class constructors are always executed before subclass constructors. It ensures proper initialization of the base part of the object. Thus, the output reflects the order of constructor calls from parent to child. |
8. Write a program that uses a private constructor to prevent external object creation (used in Singleton pattern)?
Algorithm :
- Start
- Class Definition: The Singleton class is defined with a private static variable instance to hold a single instance of the class.
- Private Constructor: The constructor is marked private to prevent direct instantiation from outside the class.
- Static Method getInstance(): This method checks if instance is null. If yes, it creates a new object and assigns it to instance.
- Main Method Begins: Execution starts from the main method.
- First Call (obj1): Singleton.getInstance() is called. Since instance is null, a new object is created and the constructor prints “Singleton instance created”.
- Second Call (obj2): Singleton.getInstance() is called again. This time, instance is not null, so the existing instance is returned.
- No New Object Created: The constructor is not called a second time, confirming only one instance exists.
- End
Program :
class Singleton { private static Singleton instance; private Singleton() { System.out.println(“Singleton instance created”); } public static Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; } public static void main(String[] args) { Singleton obj1 = Singleton.getInstance(); Singleton obj2 = Singleton.getInstance(); } } |
Output :
Singleton instance created |
Explanation :
This program demonstrates the Singleton design pattern in Java, which ensures that only one instance of a class is created throughout the application’s lifecycle. The constructor is private, preventing direct object creation from outside the class. A static method getInstance() manages object access. When getInstance() is called for the first time, it creates a new instance and prints a message. Subsequent calls to getInstance() return the same instance without re-creating it. In the main method, obj1 and obj2 both refer to the same Singleton object. This pattern is useful for scenarios like configuration managers or logging systems where only one instance should exist. |
9. Write a program that shows the use of super to call a superclass constructor?
Algorithm :
- Start
- Animal Class Definition: The base class Animal is defined with a constructor that takes a String type and prints “Animal type: ” + type.
- Dog Class Definition: The Dog class extends Animal, meaning it inherits from it.
- Dog Constructor: The constructor in Dog calls the superclass constructor using super(“Dog”), passing “Dog” as the argument.
- Superclass Constructor Execution: The Animal constructor runs first and prints “Animal type: Dog”.
- Child Constructor Execution: After the superclass constructor completes, the Dog constructor prints “Dog constructor called”.
- main() Method Execution: Execution starts in the main() method.
- Object Creation (d): A Dog object is created, triggering the constructor chain described above.
- End
Program :
class Animal { Animal(String type) { System.out.println(“Animal type: ” + type); } } class Dog extends Animal { Dog() { super(“Dog”); System.out.println(“Dog constructor called”); } public static void main(String[] args) { Dog d = new Dog(); } } |
Output :
Animal type: Dog Dog constructor called |
Explanation :
This Java program demonstrates how constructor chaining works with inheritance when parameters are involved. The Animal class has a constructor that takes a string to describe the type of animal. The Dog class extends Animal and calls the parent constructor using super(“Dog”), which ensures the base class is initialized properly with the value “Dog”. When an object of Dog is created in the main method, the Animal constructor executes first and prints “Animal type: Dog”. After that, the Dog constructor runs and prints “Dog constructor called”. This flow confirms that superclass constructors must be called before subclass constructors in an inheritance hierarchy. |
10. Write a program to create a class that shows a clear difference between a constructor and a method?
Algorithm :
- Start
- Class Definition: The class Car is defined with a string instance variable model.
- Constructor Definition: A constructor takes a String m and assigns it to model, printing “Constructor called”.
- display() Method: This method prints the value of the model variable.
- Main Method Starts: Execution begins from the main method.
- Object Creation: A Car object c is created using the constructor with the value “Tesla”.
- Constructor Execution: The constructor is invoked, model is set to “Tesla”, and “Constructor called” is printed.
- Calling display(): The display() method is called on object c, printing “Model: Tesla”.
- End
Program :
class Car { String model; Car(String m) { model = m; System.out.println(“Constructor called”); } void display() { System.out.println(“Model: ” + model); } public static void main(String[] args) { Car c = new Car(“Tesla”); c.display(); } } |
Output :
Constructor called Model: Tesla |
Explanation :
This program defines a class named Car that includes a constructor and a method to display information. The constructor accepts a String argument, assigns it to the model field, and prints a confirmation message when called. When the program runs, the main method creates a Car object c and passes “Tesla” as an argument to the constructor. The constructor is then executed, setting the model and displaying “Constructor called”. After the object is created, the display() method is called, which prints “Model: Tesla”. This program shows how constructors initialize object data and how methods can be used to access and display that data. |
11. Write a program to store multiple objects created using a constructor in an array?
Algorithm :
- Start
- Class Definition: A class Student is defined with instance variables id and name.
- Constructor: A parameterized constructor initializes these variables using values passed during object creation.
- Display Method: A method display() is defined to print the student’s id and name.
- Main Method Starts: Execution begins in the main method.
- Array Declaration: An array students of type Student with size 3 is declared.
- Object Creation: Three Student objects are created with different values and stored in the array.
- Enhanced For Loop: A for-each loop iterates over the array, calling display() for each Student object to print their details.
- End
Program :
class Student { int id; String name; Student(int i, String n) { id = i; name = n; } void display() { System.out.println(“ID: ” + id + “, Name: ” + name); } public static void main(String[] args) { Student[] students = new Student[3]; students[0] = new Student(1, “Amar”); students[1] = new Student(2, “Ram”); students[2] = new Student(3, “Charlie”); for (Student s : students) { s.display(); } } } |
Output :
ID: 1, Name: Amar ID: 2, Name: Ram ID: 3, Name: Charlie |
Explanation :
This Java program demonstrates how to manage multiple objects using an array of class instances. The Student class includes a constructor to initialize each student’s ID and name and a method to display that information. In the main method, an array of Student objects is created with a size of three. Each index of the array is then assigned a new Student object with unique data. A for-each loop is used to iterate through the array and call the display() method on each object. This prints the ID and name of all three students: Amar, Ram, and Charlie. |
12. Write a Java program to accept user input in the constructor using Scanner?
Algorithm :
- Start
- Import Scanner: The program begins by importing the Scanner class from java.util to handle user input.
- Class Definition: The Employee class is defined with two instance variables: id (integer) and name (string).
- Constructor Execution:
- A Scanner object sc is created to read input from the user.
- The user is prompted to enter an id, which is read and stored.
- sc.nextLine() is used to consume the newline character left by nextInt().
- The user is then prompted to enter a name, which is read and stored.
- Display Method: The display() method prints the id and name of the employee.
- Main Method Starts: Program execution begins in the main method.
- Object Creation: An Employee object e1 is created, triggering the constructor to accept user input.
- Output: The display() method is called to show the entered data.
- End
Program :
import java.util.Scanner; class Employee { int id; String name; Employee() { Scanner sc = new Scanner(System.in); System.out.print(“Enter ID: “); id = sc.nextInt(); sc.nextLine(); // consume newline System.out.print(“Enter Name: “); name = sc.nextLine(); } void display() { System.out.println(“ID: ” + id + “, Name: ” + name); } public static void main(String[] args) { Employee e1 = new Employee(); e1.display(); } } |
Output :
Enter ID: 101 Enter Name: John ID: 101, Name: John |
Explanation :
This Java program demonstrates how to take user input through the console using the Scanner class within a constructor. The Employee class has two fields: id and name, which are initialized interactively by prompting the user. When the Employee object e1 is created in the main method, the constructor executes and collects the id and name from the user. After the input is received, the display() method is called to print the values. This example is a good demonstration of constructor-based initialization with real-time input. It also includes a line to handle input buffer issues (sc.nextLine() after nextInt()). This ensures the program reads strings correctly after reading numbers. |
13. Write a program to show how constructors work in abstract classes in Java?
Algorithm :
- Start
- Abstract Class Definition (Vehicle): An abstract class Vehicle is defined with a constructor that prints “Vehicle constructor called” and an abstract method run().
- Subclass Definition (Car): The Car class extends Vehicle and provides an implementation for the abstract method run().
- Car Constructor: The constructor of Car prints “Car constructor called”.
- Main Method Starts: Program execution begins in the main method.
- Object Creation (c): A new object of class Car is created. This triggers constructor chaining.
- Superclass Constructor Execution: Since Car extends Vehicle, the Vehicle constructor runs first and prints “Vehicle constructor called”.
- Car Constructor Execution: After the base constructor completes, the Car constructor prints “Car constructor called”.
- Calling run(): The run() method is called on the Car object, printing “Car is running…”.
- End
Program :
abstract class Vehicle { Vehicle() { System.out.println(“Vehicle constructor called”); } abstract void run(); } class Car extends Vehicle { Car() { System.out.println(“Car constructor called”); } void run() { System.out.println(“Car is running…”); } public static void main(String[] args) { Car c = new Car(); c.run(); } } |
Output :
Vehicle constructor called Car constructor called Car is running… |
Explanation :
This Java program demonstrates inheritance with an abstract class. The abstract class Vehicle contains a constructor and an abstract method run(), which must be implemented by any subclass. The Car class extends Vehicle and provides the concrete implementation for the run() method. When an object of the Car class is created in the main method, the constructor of the abstract superclass Vehicle is executed first, followed by the Car constructor. This constructor chaining ensures that the base part of the object is initialized before the subclass. Finally, the run() method is invoked, and it prints a custom message from the Car class. |
14. Write a program to create a class with multiple constructors having different data types?
Algorithm :
- Start
- Class Definition (Demo): The class Demo is defined with three overloaded constructors:
- A no-argument constructor that prints “No-arg constructor”.
- A constructor with an int parameter that prints “Integer constructor: ” followed by the value.
- A constructor with a String parameter that prints “String constructor: ” followed by the string.
- Main Method Begins: The program execution starts in the main method.
- Object d1 Creation: new Demo() is called, triggering the no-argument constructor, which prints “No-arg constructor”.
- Object d2 Creation: new Demo(50) is called, triggering the integer constructor, which prints “Integer constructor: 50”.
- Object d3 Creation: new Demo(“Hello”) is called, triggering the string constructor, which prints “String constructor: Hello”.
- End
Program :
class Demo { Demo() { System.out.println(“No-arg constructor”); } Demo(int x) { System.out.println(“Integer constructor: ” + x); } Demo(String s) { System.out.println(“String constructor: ” + s); } public static void main(String[] args) { Demo d1 = new Demo(); Demo d2 = new Demo(50); Demo d3 = new Demo(“Hello”); } } |
Output :
No-arg constructor Integer constructor: 50 String constructor: Hello |
Explanation :
This Java program demonstrates the concept of constructor overloading, where multiple constructors are defined with different parameter lists. The class Demo includes a no-argument constructor, an integer constructor, and a string constructor. In the main method, three objects are created using these different constructors. When d1 is created, the no-argument constructor runs and prints a simple message. Then, creating d2 with an integer triggers the second constructor, and d3 with a string calls the third. Each constructor behaves differently based on the type of argument provided. This program shows how Java allows constructor overloading to handle multiple initialization scenarios in a single class. |