Java Constructor Practice Questions with Solutions | Pivot Edu Unit

Java is one of the most popular programming languages, and understanding constructors in Java is essential for mastering Object-Oriented Programming (OOP). If you are preparing for Java interviewscollege exams, or simply want to improve your Java skills, this set of Java constructor practice questions will help you.

At Pivot Edu Unit, Dehradun, we provide hands-on Java training with real-world projects to enhance your programming expertise. Let’s dive into the best Java constructor questions to test and improve your coding skills.

What is a Constructor in Java?

constructor in Java is a special method that gets called automatically when an object of a class is created. Constructors help initialize objects and can be of different types: default constructors, parameterized constructors, copy constructors, and overloaded constructors.

1. Basic Constructor Questions

Create a class Student with attributes name and age. Use a constructor to initialize these attributes and display them.

12345678910111213classStudent {    String name;    intage;        Student(String name, intage) {        this.name = name;        this.age = age;    }        voiddisplay() {        System.out.println("Name: "+ name + ", Age: "+ age);    }}

Write a class Car with attributes brandmodel, and price. Implement a constructor to initialize the values and print the details.

1234567891011121314classCar {    String brand, model;    doubleprice;        Car(String brand, String model, doubleprice) {        this.brand = brand;        this.model = model;        this.price = price;    }        voiddisplay() {        System.out.println("Brand: "+ brand + ", Model: "+ model + ", Price: "+ price);    }}

Design a Book class for a library system with attributes titleauthor, and ISBN. Initialize these attributes using a constructor and display the book details.

123456789101112131415161718192021222324publicclassBook {    privateString title;    privateString author;    privateString ISBN;    // Constructor    publicBook(String title, String author, String ISBN) {        this.title = title;        this.author = author;        this.ISBN = ISBN;    }    // Method to display book details    publicvoiddisplayDetails() {        System.out.println("Title: "+ title);        System.out.println("Author: "+ author);        System.out.println("ISBN: "+ ISBN);    }    publicstaticvoidmain(String[] args) {        Book book = newBook("Effective Java", "Joshua Bloch", "978-0134685991");        book.displayDetails();    }}

Create a Patient class for a hospital management system with attributes nameage, and patientID. Use a constructor to initialize these attributes and display the patient’s information.

123456789101112131415161718192021222324publicclassPatient {    privateString name;    privateintage;    privateString patientID;    // Constructor    publicPatient(String name, intage, String patientID) {        this.name = name;        this.age = age;        this.patientID = patientID;    }    // Method to display patient information    publicvoiddisplayInfo() {        System.out.println("Patient Name: "+ name);        System.out.println("Age: "+ age);        System.out.println("Patient ID: "+ patientID);    }    publicstaticvoidmain(String[] args) {        Patient patient = newPatient("John Doe", 30, "P12345");        patient.displayInfo();    }}

2. Parameterized Constructor Questions

Develop a BankAccount class that requires an accountNumber and initialBalance upon creation. Ensure that the balance cannot be negative.

1234567891011121314151617181920212223242526publicclassBankAccount {    privateString accountNumber;    privatedoublebalance;    // Constructor    publicBankAccount(String accountNumber, doubleinitialBalance) {        this.accountNumber = accountNumber;        if(initialBalance >= 0) {            this.balance = initialBalance;        } else{            System.out.println("Initial balance cannot be negative. Setting balance to 0.");            this.balance = 0;        }    }    // Method to display account details    publicvoiddisplayAccountDetails() {        System.out.println("Account Number: "+ accountNumber);        System.out.println("Balance: $"+ balance);    }    publicstaticvoidmain(String[] args) {        BankAccount account = newBankAccount("123456789", 500.0);        account.displayAccountDetails();    }}

Create a Movie class for a cinema booking system that initializes with titlegenre, and duration (in minutes).

1234567891011121314publicclassMovie {privateString title;privateString genre;privateintduration; // in minutes// ConstructorpublicMovie(String title, String genre, intduration) {    this.title = title;    this.genre = genre;    this.duration = duration;}// Method to display movie detailspublicvoiddisplayMovieDetails() {    System.out.println("Title: "+ title);

Implement a LibraryBook class that takes titleauthor, and ISBN as parameters in a constructor and displays book details.

123456789101112131415161718192021publicclassLibraryBook {    privateString title;    privateString author;    privateString ISBN;    // Parameterized Constructor    publicLibraryBook(String title, String author, String ISBN) {        this.title = title;        this.author = author;        this.ISBN = ISBN;    }    publicvoiddisplayBookInfo() {        System.out.println("Title: "+ title + ", Author: "+ author + ", ISBN: "+ ISBN);    }    publicstaticvoidmain(String[] args) {        LibraryBook book = newLibraryBook("Effective Java", "Joshua Bloch", "978-0134685991");        book.displayBookInfo();    }}

Create a Flight class that accepts flightNumberdestination, and departureTime as parameters and prints flight details.

12345678910111213141516171819202122publicclassFlight {privateString flightNumber;privateString destination;privateString departureTime;// Parameterized ConstructorpublicFlight(String flightNumber, String destination, String departureTime) {    this.flightNumber = flightNumber;    this.destination = destination;    this.departureTime = departureTime;}publicvoiddisplayFlightInfo() {    System.out.println("Flight Number: "+ flightNumber +                        ", Destination: "+ destination +                        ", Departure Time: "+ departureTime);}publicstaticvoidmain(String[] args) {    Flight flight = newFlight("AI-202", "New York", "10:30 AM");    flight.displayFlightInfo();}

}

Develop a Product class where the constructor initializes productNamecategory, and price. Print product details.

1234567891011121314151617181920212223publicclassProduct {privateString productName;privateString category;privatedoubleprice;// Parameterized ConstructorpublicProduct(String productName, String category, doubleprice) {    this.productName = productName;    this.category = category;    this.price = price;}publicvoiddisplayProductInfo() {    System.out.println("Product Name: "+ productName +                        ", Category: "+ category +                        ", Price: $"+ price);}publicstaticvoidmain(String[] args) {    Product product = newProduct("Laptop", "Electronics", 999.99);    product.displayProductInfo();}}

Create a Movie class that takes titledirector, and releaseYear as parameters and prints the movie details.

12345678910111213141516171819202122publicclassMovie {privateString title;privateString director;privateintreleaseYear;// Parameterized ConstructorpublicMovie(String title, String director, intreleaseYear) {    this.title = title;    this.director = director;    this.releaseYear = releaseYear;}publicvoiddisplayMovieInfo() {    System.out.println("Title: "+ title +                        ", Director: "+ director +                        ", Release Year: "+ releaseYear);}publicstaticvoidmain(String[] args) {    Movie movie = newMovie("Inception", "Christopher Nolan", 2010);    movie.displayMovieInfo();}}

Constructor Overloading Questions with Solutions

Create a Vehicle class with overloaded constructors that allow creating a vehicle with only brand, with brand and model, and with brand, model, and price.

123456789101112131415161718192021222324252627282930313233343536373839publicclassVehicle {privateString brand;privateString model;privatedoubleprice;// Constructor with only brandpublicVehicle(String brand) {    this.brand = brand;    this.model = "Unknown";    this.price = 0.0;}// Constructor with brand and modelpublicVehicle(String brand, String model) {    this.brand = brand;    this.model = model;    this.price = 0.0;}// Constructor with brand, model, and pricepublicVehicle(String brand, String model, doubleprice) {    this.brand = brand;    this.model = model;    this.price = price;}publicvoiddisplayVehicleInfo() {    System.out.println("Brand: "+ brand + ", Model: "+ model + ", Price: $"+ price);}publicstaticvoidmain(String[] args) {    Vehicle car1 = newVehicle("Toyota");    Vehicle car2 = newVehicle("Honda", "Civic");    Vehicle car3 = newVehicle("BMW", "X5", 50000);    car1.displayVehicleInfo();    car2.displayVehicleInfo();    car3.displayVehicleInfo();}

}

Develop an Employee class with overloaded constructors that allow creating an employee with only name, with name and ID, and with name, ID, and salary.

1234567891011121314151617181920212223242526272829303132333435363738public class Employee {private String name;private int id;private double salary;// Constructor with only namepublic Employee(String name) {    this.name = name;    this.id = 0;    this.salary = 0.0;}// Constructor with name and idpublic Employee(String name, int id) {    this.name = name;    this.id = id;    this.salary = 0.0;}// Constructor with name, id, and salarypublic Employee(String name, int id, double salary) {    this.name = name;    this.id = id;    this.salary = salary;}public void displayEmployeeInfo() {    System.out.println("Name: " + name + ", ID: " + id + ", Salary: $" + salary);}public static void main(String[] args) {    Employee emp1 = new Employee("Alice");    Employee emp2 = new Employee("Bob", 101);    Employee emp3 = new Employee("Charlie", 102, 75000);    emp1.displayEmployeeInfo();    emp2.displayEmployeeInfo();    emp3.displayEmployeeInfo();}

}

Create a Hotel class with overloaded constructors to initialize hotelNamelocation, and rating. Allow object creation with different parameter sets.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051publicclassHotel {    privateString hotelName;    privateString location;    privateintrating;    // Constructor 1: Default Constructor    publicHotel() {        this.hotelName = "Unknown";        this.location = "Not Specified";        this.rating = 0;    }    // Constructor 2: Only hotel name    publicHotel(String hotelName) {        this.hotelName = hotelName;        this.location = "Not Specified";        this.rating = 0;    }    // Constructor 3: Hotel name and location    publicHotel(String hotelName, String location) {        this.hotelName = hotelName;        this.location = location;        this.rating = 0;    }    // Constructor 4: Hotel name, location, and rating    publicHotel(String hotelName, String location, intrating) {        this.hotelName = hotelName;        this.location = location;        this.rating = rating;    }    publicvoiddisplayHotelInfo() {        System.out.println("Hotel: "+ hotelName +                            ", Location: "+ location +                            ", Rating: "+ rating + " stars");    }    publicstaticvoidmain(String[] args) {        Hotel hotel1 = newHotel();        Hotel hotel2 = newHotel("Grand Hyatt");        Hotel hotel3 = newHotel("Taj Palace", "Mumbai");        Hotel hotel4 = newHotel("The Oberoi", "Delhi", 5);        hotel1.displayHotelInfo();        hotel2.displayHotelInfo();        hotel3.displayHotelInfo();        hotel4.displayHotelInfo();    }}

Create a Laptop class with overloaded constructors that allow creating a laptop with only brand, with brand and RAM size, and with brand, RAM size, and price.

123456789101112131415161718192021222324252627282930313233343536373839404142publicclassLaptop {    privateString brand;    privateintramSize;    privatedoubleprice;    // Constructor 1: Only brand    publicLaptop(String brand) {        this.brand = brand;        this.ramSize = 8; // Default RAM size        this.price = 0.0;    }    // Constructor 2: Brand and RAM size    publicLaptop(String brand, intramSize) {        this.brand = brand;        this.ramSize = ramSize;        this.price = 0.0;    }    // Constructor 3: Brand, RAM size, and price    publicLaptop(String brand, intramSize, doubleprice) {        this.brand = brand;        this.ramSize = ramSize;        this.price = price;    }    publicvoiddisplayLaptopInfo() {        System.out.println("Brand: "+ brand +                            ", RAM: "+ ramSize + "GB"+                            ", Price: $"+ price);    }    publicstaticvoidmain(String[] args) {        Laptop laptop1 = newLaptop("Dell");        Laptop laptop2 = newLaptop("HP", 16);        Laptop laptop3 = newLaptop("Apple", 32, 2500);        laptop1.displayLaptopInfo();        laptop2.displayLaptopInfo();        laptop3.displayLaptopInfo();    }}

Design a Restaurant class with overloaded constructors that allow creating an object with only name, with name and cuisine type, and with name, cuisine type, and average cost.

123456789101112131415161718192021222324252627282930313233343536373839404142publicclassRestaurant {    privateString name;    privateString cuisineType;    privatedoubleavgCost;    // Constructor 1: Only name    publicRestaurant(String name) {        this.name = name;        this.cuisineType = "Not Specified";        this.avgCost = 0.0;    }    // Constructor 2: Name and cuisine type    publicRestaurant(String name, String cuisineType) {        this.name = name;        this.cuisineType = cuisineType;        this.avgCost = 0.0;    }    // Constructor 3: Name, cuisine type, and average cost    publicRestaurant(String name, String cuisineType, doubleavgCost) {        this.name = name;        this.cuisineType = cuisineType;        this.avgCost = avgCost;    }    publicvoiddisplayRestaurantInfo() {        System.out.println("Restaurant: "+ name +                            ", Cuisine: "+ cuisineType +                            ", Average Cost: $"+ avgCost);    }    publicstaticvoidmain(String[] args) {        Restaurant rest1 = newRestaurant("Pizza Hut");        Restaurant rest2 = newRestaurant("Sushi House", "Japanese");        Restaurant rest3 = newRestaurant("Royal Dine", "Indian", 30);        rest1.displayRestaurantInfo();        rest2.displayRestaurantInfo();        rest3.displayRestaurantInfo();    }}

3. Copy Constructor Questions with Solutions

Create a Smartphone class with a copy constructor to duplicate an object’s attributes (brandmodelprice).

1234567891011121314151617181920212223242526272829publicclassSmartphone {privateString brand;privateString model;privatedoubleprice;// Parameterized ConstructorpublicSmartphone(String brand, String model, doubleprice) {    this.brand = brand;    this.model = model;    this.price = price;}// Copy ConstructorpublicSmartphone(Smartphone phone) {    this.brand = phone.brand;    this.model = phone.model;    this.price = phone.price;}publicvoiddisplaySmartphoneInfo() {    System.out.println("Brand: "+ brand + ", Model: "+ model + ", Price: $"+ price);}publicstaticvoidmain(String[] args) {    Smartphone phone1 = newSmartphone("Apple", "iPhone 14", 999);    Smartphone phone2 = newSmartphone(phone1); // Using Copy Constructor    phone1.displaySmartphoneInfo();    phone2.displaySmartphoneInfo();}

}

Implement a HotelRoom class with a copy constructor to clone a room’s attributes (roomNumberroomTypeprice).

1234567891011121314151617181920212223242526272829publicclassHotelRoom {privateintroomNumber;privateString roomType;privatedoubleprice;// Parameterized ConstructorpublicHotelRoom(introomNumber, String roomType, doubleprice) {    this.roomNumber = roomNumber;    this.roomType = roomType;    this.price = price;}// Copy ConstructorpublicHotelRoom(HotelRoom room) {    this.roomNumber = room.roomNumber;    this.roomType = room.roomType;    this.price = room.price;}publicvoiddisplayRoomInfo() {    System.out.println("Room Number: "+ roomNumber + ", Room Type: "+ roomType + ", Price: $"+ price);}publicstaticvoidmain(String[] args) {    HotelRoom room1 = newHotelRoom(101, "Deluxe", 120);    HotelRoom room2 = newHotelRoom(room1); // Copying details    room1.displayRoomInfo();    room2.displayRoomInfo();}

}

Create a Book class with a copy constructor that allows creating a duplicate book object.

123456789101112131415161718192021222324252627282930313233publicclassBook {    privateString title;    privateString author;    privatedoubleprice;    // Parameterized Constructor    publicBook(String title, String author, doubleprice) {        this.title = title;        this.author = author;        this.price = price;    }    // Copy Constructor    publicBook(Book other) {        this.title = other.title;        this.author = other.author;        this.price = other.price;    }    publicvoiddisplayBookInfo() {        System.out.println("Title: "+ title +                            ", Author: "+ author +                            ", Price: $"+ price);    }    publicstaticvoidmain(String[] args) {        Book book1 = newBook("Java Programming", "James Gosling", 40.5);        Book book2 = newBook(book1); // Copying book1 into book2        book1.displayBookInfo();        book2.displayBookInfo();    }}

Create a Person class with a copy constructor that copies personal details.

1234567891011121314151617181920212223242526272829publicclassPerson {    privateString name;    privateintage;    // Parameterized Constructor    publicPerson(String name, intage) {        this.name = name;        this.age = age;    }    // Copy Constructor    publicPerson(Person other) {        this.name = other.name;        this.age = other.age;    }    publicvoiddisplayPersonInfo() {        System.out.println("Name: "+ name +                            ", Age: "+ age);    }    publicstaticvoidmain(String[] args) {        Person person1 = newPerson("John Doe", 30);        Person person2 = newPerson(person1); // Copying person1 into person2        person1.displayPersonInfo();        person2.displayPersonInfo();    }}

Develop a BankAccount class where a copy constructor allows duplicating account details.

123456789101112131415161718192021222324252627282930313233publicclassBankAccount {    privateString accountHolder;    privateintaccountNumber;    privatedoublebalance;    // Parameterized Constructor    publicBankAccount(String accountHolder, intaccountNumber, doublebalance) {        this.accountHolder = accountHolder;        this.accountNumber = accountNumber;        this.balance = balance;    }    // Copy Constructor    publicBankAccount(BankAccount other) {        this.accountHolder = other.accountHolder;        this.accountNumber = other.accountNumber;        this.balance = other.balance;    }    publicvoiddisplayAccountInfo() {        System.out.println("Account Holder: "+ accountHolder +                            ", Account Number: "+ accountNumber +                            ", Balance: $"+ balance);    }    publicstaticvoidmain(String[] args) {        BankAccount acc1 = newBankAccount("Alice Brown", 123456, 5000.75);        BankAccount acc2 = newBankAccount(acc1); // Copying acc1 into acc2        acc1.displayAccountInfo();        acc2.displayAccountInfo();    }}

Implement a Movie class that supports copy constructor to create duplicate movie objects.

123456789101112131415161718192021222324252627282930313233publicclassMovie {    privateString title;    privateString genre;    privateintduration; // in minutes    // Parameterized Constructor    publicMovie(String title, String genre, intduration) {        this.title = title;        this.genre = genre;        this.duration = duration;    }    // Copy Constructor    publicMovie(Movie other) {        this.title = other.title;        this.genre = other.genre;        this.duration = other.duration;    }    publicvoiddisplayMovieInfo() {        System.out.println("Movie: "+ title +                            ", Genre: "+ genre +                            ", Duration: "+ duration + " min");    }    publicstaticvoidmain(String[] args) {        Movie movie1 = newMovie("Inception", "Sci-Fi", 148);        Movie movie2 = newMovie(movie1); // Copying movie1 into movie2        movie1.displayMovieInfo();        movie2.displayMovieInfo();    }}

Create a Laptop class with a copy constructor that copies laptop specifications.

123456789101112131415161718192021222324252627282930313233publicclassLaptop {    privateString brand;    privateintram;    privatedoubleprice;    // Parameterized Constructor    publicLaptop(String brand, intram, doubleprice) {        this.brand = brand;        this.ram = ram;        this.price = price;    }    // Copy Constructor    publicLaptop(Laptop other) {        this.brand = other.brand;        this.ram = other.ram;        this.price = other.price;    }    publicvoiddisplayLaptopInfo() {        System.out.println("Brand: "+ brand +                            ", RAM: "+ ram + "GB"+                            ", Price: $"+ price);    }    publicstaticvoidmain(String[] args) {        Laptop laptop1 = newLaptop("Dell", 16, 1200);        Laptop laptop2 = newLaptop(laptop1); // Copying laptop1 into laptop2        laptop1.displayLaptopInfo();        laptop2.displayLaptopInfo();    }}

4. Constructor Chaining Questions with Solutions

Design a Company class where constructor chaining initializes companyNamelocation, and totalEmployees in a hierarchical manner.

123456789101112131415161718192021222324252627282930313233343536373839publicclassCompany {privateString companyName;privateString location;privateinttotalEmployees;// Constructor 1publicCompany() {    this("Unknown Company");}// Constructor 2publicCompany(String companyName) {    this(companyName, "Unknown Location");}// Constructor 3publicCompany(String companyName, String location) {    this(companyName, location, 0);}// Constructor 4publicCompany(String companyName, String location, inttotalEmployees) {    this.companyName = companyName;    this.location = location;    this.totalEmployees = totalEmployees;}publicvoiddisplayCompanyInfo() {    System.out.println("Company: "+ companyName + ", Location: "+ location + ", Employees: "+ totalEmployees);}publicstaticvoidmain(String[] args) {    Company company1 = newCompany();    Company company2 = newCompany("Tech Corp");    Company company3 = newCompany("Innovate Ltd.", "New York", 500);    company1.displayCompanyInfo();    company2.displayCompanyInfo();    company3.displayCompanyInfo();}

}

Create an Employee class where constructor chaining initializes employee details.

1234567891011121314151617181920212223242526272829303132333435363738publicclassEmployee {    privateString name;    privateintid;    privatedoublesalary;    // Default Constructor    publicEmployee() {        this("Unknown", 0, 0.0); // Calls parameterized constructor    }    // Constructor with Name and ID    publicEmployee(String name, intid) {        this(name, id, 30000.0); // Calls full parameterized constructor    }    // Constructor with Name, ID, and Salary    publicEmployee(String name, intid, doublesalary) {        this.name = name;        this.id = id;        this.salary = salary;    }    publicvoiddisplay() {        System.out.println("Employee Name: "+ name +                            ", ID: "+ id +                            ", Salary: $"+ salary);    }    publicstaticvoidmain(String[] args) {        Employee emp1 = newEmployee();        Employee emp2 = newEmployee("Alice", 101);        Employee emp3 = newEmployee("Bob", 102, 50000);        emp1.display();        emp2.display();        emp3.display();    }}

Develop a Smartphone class that demonstrates constructor chaining.

1234567891011121314151617181920212223242526272829303132333435363738publicclassSmartphone {    privateString brand;    privateString model;    privatedoubleprice;    // Default Constructor    publicSmartphone() {        this("Unknown", "Unknown", 0.0);    }    // Constructor with Brand and Model    publicSmartphone(String brand, String model) {        this(brand, model, 10000.0); // Default price    }    // Constructor with Brand, Model, and Price    publicSmartphone(String brand, String model, doubleprice) {        this.brand = brand;        this.model = model;        this.price = price;    }    publicvoiddisplay() {        System.out.println("Brand: "+ brand +                            ", Model: "+ model +                            ", Price: $"+ price);    }    publicstaticvoidmain(String[] args) {        Smartphone phone1 = newSmartphone();        Smartphone phone2 = newSmartphone("Samsung", "Galaxy S21");        Smartphone phone3 = newSmartphone("Apple", "iPhone 15", 1200);        phone1.display();        phone2.display();        phone3.display();    }}

Create a Vehicle class where constructor chaining initializes vehicle details.

123456789101112131415161718192021222324252627282930313233343536373839404142434445publicclassVehicle {    privateString type;    privateString brand;    privateintwheels;    // Default Constructor    publicVehicle() {        this("Unknown", "Unknown", 4);    }    // Constructor with Type    publicVehicle(String type) {        this(type, "Unknown", 4);    }    // Constructor with Type and Brand    publicVehicle(String type, String brand) {        this(type, brand, 4);    }    // Constructor with Type, Brand, and Wheels    publicVehicle(String type, String brand, intwheels) {        this.type = type;        this.brand = brand;        this.wheels = wheels;    }    publicvoiddisplay() {        System.out.println("Vehicle Type: "+ type +                            ", Brand: "+ brand +                            ", Wheels: "+ wheels);    }    publicstaticvoidmain(String[] args) {        Vehicle v1 = newVehicle();        Vehicle v2 = newVehicle("Bike");        Vehicle v3 = newVehicle("Car", "Toyota");        Vehicle v4 = newVehicle("Truck", "Volvo", 18);        v1.display();        v2.display();        v3.display();        v4.display();    }}

Build a Hotel class that demonstrates constructor chaining for room booking.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546publicclassHotel {    privateString name;    privateString roomType;    privateintnights;    privatedoubleprice;    // Default Constructor    publicHotel() {        this("Default Hotel", "Standard", 1, 1000);    }    // Constructor with Name and Room Type    publicHotel(String name, String roomType) {        this(name, roomType, 1, 2000);    }    // Constructor with Name, Room Type, and Nights    publicHotel(String name, String roomType, intnights) {        this(name, roomType, nights, nights * 2000);    }    // Constructor with All Parameters    publicHotel(String name, String roomType, intnights, doubleprice) {        this.name = name;        this.roomType = roomType;        this.nights = nights;        this.price = price;    }    publicvoiddisplay() {        System.out.println("Hotel: "+ name +                            ", Room Type: "+ roomType +                            ", Nights: "+ nights +                            ", Total Price: $"+ price);    }    publicstaticvoidmain(String[] args) {        Hotel h1 = newHotel();        Hotel h2 = newHotel("Luxury Inn", "Deluxe");        Hotel h3 = newHotel("Grand Palace", "Suite", 3);        h1.display();        h2.display();        h3.display();    }}

Implement a University class where constructor chaining initializes student details.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546publicclassUniversity {    privateString studentName;    privateString course;    privateintduration; // in years    privatedoublefee;    // Default Constructor    publicUniversity() {        this("Unknown", "General Studies", 3, 50000);    }    // Constructor with Name and Course    publicUniversity(String studentName, String course) {        this(studentName, course, 3, 70000);    }    // Constructor with Name, Course, and Duration    publicUniversity(String studentName, String course, intduration) {        this(studentName, course, duration, duration * 70000);    }    // Constructor with All Parameters    publicUniversity(String studentName, String course, intduration, doublefee) {        this.studentName = studentName;        this.course = course;        this.duration = duration;        this.fee = fee;    }    publicvoiddisplay() {        System.out.println("Student: "+ studentName +                            ", Course: "+ course +                            ", Duration: "+ duration + " years"+                            ", Fee: $"+ fee);    }    publicstaticvoidmain(String[] args) {        University u1 = newUniversity();        University u2 = newUniversity("John Doe", "Computer Science");        University u3 = newUniversity("Alice", "Mechanical Engineering", 4);        u1.display();        u2.display();        u3.display();    }}

Mastering constructors in Java, including constructor chaining, overloading, and copy constructors, is essential for building robust and efficient Java applications. By practicing these real-world scenario-based questions, you can strengthen your OOP concepts and improve your coding skills for interviews and projects.

At Pivot Edu Unit, Dehradun, we offer industry-focused Java training with hands-on projects to help you become a proficient Java developer.

💡 Start your Java learning journey today! Visit Pivot Edu Unit and enhance your programming expertise. 🚀

Most Popular

Most Commonly Used Formulas in Tableau (With Sample Sheet and Examples)

July 4, 2025

Java Constructor Practice Questions with Solutions | Pivot Edu Unit

March 29, 2025

How to Analyze Data Like a Pro – A Beginner’s Guide to Excel

March 27, 2025

Top Digital Marketing Interview Questions & Answers for 2025

March 8, 2025

Social Media

Facebook-f Youtube Instagram

Categories

PrevPreviousA Comprehensive Guide to MySQL Queries

NextMost Commonly Used Formulas in Tableau (With Sample Sheet and Exampl

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *