0% found this document useful (0 votes)
6 views17 pages

CSW2 Assignment1 Soln

The document outlines a series of Java programming assignments, including the creation of classes such as Car, Rectangle, Point, Image, and a College Management System. Each assignment involves defining classes with attributes, constructors, and methods, demonstrating concepts like encapsulation, inheritance, and object manipulation. Additionally, it includes a library system that utilizes abstract classes and polymorphism to manage different types of library resources.

Uploaded by

humanoperator8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views17 pages

CSW2 Assignment1 Soln

The document outlines a series of Java programming assignments, including the creation of classes such as Car, Rectangle, Point, Image, and a College Management System. Each assignment involves defining classes with attributes, constructors, and methods, demonstrating concepts like encapsulation, inheritance, and object manipulation. Additionally, it includes a library system that utilizes abstract classes and polymorphism to manage different types of library resources.

Uploaded by

humanoperator8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

CSW ASSIGNMENT 1 (CHAPTER 12)

SOLUTIONS
--------------------------------------------------------------------------------
1. Write a Java program with a Car class having private fields (make, model), a
parameterized constructor, getter, and setter methods. In the CarTester class, instantiate
myCar1 with values and myCar2 with null. Print their initial details, update myCar2
using setters, and print the updated details.

Car.java:

package q1;
public class Car {
private String make;
private String model;
public Car(String make, String model) {
this.make = make;
this.model = model;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public void printDetails() {
System.out.println("Make: " + make + ", Model: " + model);
}
}

CarTester.java:

package q1;
public class CarTester {
public static void main(String[] args) {
Car myCar1 = new Car("Toyota", "Urban Cruiser");
Car myCar2 = new Car(null, null);
System.out.println("Initial details of myCar1:");
myCar1.printDetails();
System.out.println();
System.out.println("Initial details of myCar2:");
myCar2.printDetails();
myCar2.setMake("Maruti Suzuki");
myCar2.setModel("Fronx");
System.out.println();
System.out.println("Updated details of myCar2:");
myCar2.printDetails();
}
}

Prepared by MAJI, A.
2. Design a Java class called Rectangle with private attributes length and width. Include
a constructor to initialize these attributes, as well as setter and getter methods for each
attribute. Additionally, implement methods to calculate the area and perimeter of the
rectangle. Write a main method to create an object of the Rectangle class, set values for
its attributes, and display the area and perimeter.

Rectangle.java:

package q2;
public class Rectangle {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double calculateArea() {
return length * width;
}
public double calculatePerimeter() {
return 2 * (length + width);
}
public void printDetails() {
System.out.println("Length: " + length + ", Width: " + width);
}
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5.0, 3.0);
System.out.println("Initial details of rectangle:");
rectangle.printDetails();
System.out.println("Area: " + rectangle.calculateArea());
System.out.println("Perimeter: " + rectangle.calculatePerimeter());
rectangle.setLength(7.0);
rectangle.setWidth(4.0);
System.out.println();
System.out.println("Updated details of rectangle:");
rectangle.printDetails();
System.out.println("Area: " + rectangle.calculateArea());
System.out.println("Perimeter: " + rectangle.calculatePerimeter());
}
}

Prepared by MAJI, A.
3. Write a Java program that defines a Point class with attributes X and Y, and includes
a parameterized constructor to initialize these attributes. Implement a copy constructor
to create a new point object with the same attribute values. Ensure that modifications
made to one object do not affect the other. Utilize getter and setter methods to retrieve
and update the attribute values.

Point.java:

package q3;
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point(Point point) {
this.x = point.x;
this.y = point.y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void printDetails() {
System.out.println("X: " + x + ", Y: " + y);
}
public static void main(String[] args) {
Point point1 = new Point(3, 4);
Point point2 = new Point(point1);
System.out.println("Initial details of point1:");
point1.printDetails();
System.out.println();
System.out.println("Initial details of point2:");
point2.printDetails();
point1.setX(5);
point1.setY(6);
System.out.println();
System.out.println("Modified details of point1:");
point1.printDetails();
System.out.println();
System.out.println("Details of point2 after modifying point1:");
point2.printDetails();
}
}

Prepared by MAJI, A.
4. Write a program to create an Image class with attributes imageWidth, imageHeight,
and colorCode. Add the required constructor, set methods, get methods, and toString
method. Create the object of the image class using the default and parameterized
constructor and print the details of the object.

Image.java:

package q4;
public class Image {
private int imageWidth;
private int imageHeight;
private String colorCode;
public Image() {
this.imageWidth = 0;
this.imageHeight = 0;
this.colorCode = "#000000";
}
public Image(int imageWidth, int imageHeight, String colorCode) {
this.imageWidth = imageWidth;
this.imageHeight = imageHeight;
this.colorCode = colorCode;
}
public int getImageWidth() {
return imageWidth;
}
public int getImageHeight() {
return imageHeight;
}
public String getColorCode() {
return colorCode;
}
public void setImageWidth(int imageWidth) {
this.imageWidth = imageWidth;
}
public void setImageHeight(int imageHeight) {
this.imageHeight = imageHeight;
}
public void setColorCode(String colorCode) {
this.colorCode = colorCode;
}
public String toString() {
return "Image [Width: " + imageWidth + ", Height: " + imageHeight + ",
Color Code: " + colorCode + "]";
}
public static void main(String[] args) {
Image defaultImage = new Image();
System.out.println("Default Image Details: " + defaultImage.toString());
Image parameterizedImage = new Image(1920, 1080, "#FFFFFF");
System.out.println("Parameterized Image Details: " +
parameterizedImage.toString());
parameterizedImage.setImageWidth(1280);
parameterizedImage.setImageHeight(720);
parameterizedImage.setColorCode("#FF5733");
System.out.println("Updated Parameterized Image Details: " +
parameterizedImage.toString());
}
}

Prepared by MAJI, A.
5. Create an ImageLibrary, which contains a set of image objects (from Q4) and operations
such as searching an image, inserting an image, and getting an image. Create an
ImageController class to manage the program execution and call the methods to create
and manipulate images.

Image.java:

package q5;
public class Image {
private int imageWidth;
private int imageHeight;
private String colorCode;
public Image() {
this.imageWidth = 0;
this.imageHeight = 0;
this.colorCode = "#000000";
}
public Image(int imageWidth, int imageHeight, String colorCode) {
this.imageWidth = imageWidth;
this.imageHeight = imageHeight;
this.colorCode = colorCode;
}
public int getImageWidth() {
return imageWidth;
}
public int getImageHeight() {
return imageHeight;
}
public String getColorCode() {
return colorCode;
}
public void setImageWidth(int imageWidth) {
this.imageWidth = imageWidth;
}
public void setImageHeight(int imageHeight) {
this.imageHeight = imageHeight;
}
public void setColorCode(String colorCode) {
this.colorCode = colorCode;
}
public String toString() {
return "Image [Width: " + imageWidth + ", Height: " + imageHeight + ",
Color Code: " + colorCode + "]";
}
}

ImageLibrary.java:

package q5;
public class ImageLibrary {
private Image[] images;
private int size;
public ImageLibrary(int capacity) {
images = new Image[capacity];
size = 0;
}
public void insertImage(Image image) {
if (size < images.length) {
images[size++] = image;
} else {

Prepared by MAJI, A.
System.out.println("Image library is full.");
}
}
public Image searchImage(String colorCode) {
for (int i = 0; i < size; i++) {
if (images[i].getColorCode().equals(colorCode)) {
return images[i];
}
}
return null;
}
public Image getImage(int index) {
if (index >= 0 && index < size) {
return images[index];
}
return null;
}
public void displayAllImages() {
for (int i = 0; i < size; i++) {
System.out.println(images[i].toString());
}
}
}

ImageController.java:

package q5;
public class ImageController {
public static void main(String[] args) {
ImageLibrary imageLibrary = new ImageLibrary(10);
Image image1 = new Image(1920, 1080, "#FFFFFF");
Image image2 = new Image(1280, 720, "#FF5733");
imageLibrary.insertImage(image1);
imageLibrary.insertImage(image2);
System.out.println("All Images:");
imageLibrary.displayAllImages();
String searchColorCode = "#FF5733";
Image searchedImage = imageLibrary.searchImage(searchColorCode);
if (searchedImage != null) {
System.out.println("Searched Image: " + searchedImage.toString());
} else {
System.out.println("Image with color code " + searchColorCode + "
not found.");
}
int index = 0;
Image imageAtIndex = imageLibrary.getImage(index);
if (imageAtIndex != null) {
System.out.println("Image at Index " + index + ": " +
imageAtIndex.toString());
} else {
System.out.println("No image at index " + index);
}
}
}

Prepared by MAJI, A.
6. Develop a Java-based College Management System to model the relationship between
colleges and students. Create a College class with attributes collegeName and
collegeLoc, and a Student class with studentId, studentName, and a reference to a
College object. Implement a constructor in Student to initialize these attributes and a
displayStudentInfo() method to print student and college details. In the MainApp class,
instantiate at least two College and Student objects, enroll each student in one of the
colleges, and display all details using appropriate methods.

College.java:

package q6;
public class College {
private String collegeName;
private String collegeLoc;
public College(String collegeName, String collegeLoc) {
this.collegeName = collegeName;
this.collegeLoc = collegeLoc;
}
public String getCollegeName() {
return collegeName;
}
public void setCollegeName(String collegeName) {
this.collegeName = collegeName;
}
public String getCollegeLoc() {
return collegeLoc;
}
public void setCollegeLoc(String collegeLoc) {
this.collegeLoc = collegeLoc;
}
}

Student.java:

package q6;
public class Student {
private String studentId;
private String studentName;
private College college;
public Student(String studentId, String studentName, College college) {
this.studentId = studentId;
this.studentName = studentName;
this.college = college;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public College getCollege() {
return college;
}
public void setCollege(College college) {

Prepared by MAJI, A.
this.college = college;
}
public void displayStudentInfo() {
System.out.println("Student ID: " + studentId);
System.out.println("Student Name: " + studentName);
System.out.println("College Name: " + college.getCollegeName());
System.out.println("College Location: " + college.getCollegeLoc());
}
}

MainApp.java:

package q6;
public class MainApp {
public static void main(String[] args) {
College college1 = new College("ITER", "Bhubaneswar");
College college2 = new College("IMS", "Bhubaneswar");
Student student1 = new Student("S001", "Ajay", college1);
Student student2 = new Student("S002", "Rajan", college2);
student1.displayStudentInfo();
System.out.println();
student2.displayStudentInfo();
}
}

Prepared by MAJI, A.
7. Develop a Java program for a library system using encapsulation, abstraction, and
inheritance. Create an abstract LibraryResource class with private attributes (title,
author), a constructor, getters, setters, and an abstract displayDetails() method. Extend
it into Book, Magazine, and DVD classes, each adding a specific attribute (pageCount,
issueDate, duration), along with constructors, getters, setters, and overridden
displayDetails() methods. In the LibrarySystem class, instantiate various resources and
call displayDetails() to display their information.

LibraryResource.java:

package q7;
public abstract class LibraryResource {
private String title;
private String author;
public LibraryResource(String title, String author) {
this.title = title;
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public abstract void displayDetails();
}

Book.java:

package q7;
public class Book extends LibraryResource {
private int pageCount;
public Book(String title, String author, int pageCount) {
super(title, author);
this.pageCount = pageCount;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public void displayDetails() {
System.out.println("Book Title: " + getTitle());
System.out.println("Author: " + getAuthor());
System.out.println("Page Count: " + pageCount);
}
}

Prepared by MAJI, A.
Magazine.java:

package q7;
public class Magazine extends LibraryResource {
private String issueDate;
public Magazine(String title, String author, String issueDate) {
super(title, author);
this.issueDate = issueDate;
}
public String getIssueDate() {
return issueDate;
}
public void setIssueDate(String issueDate) {
this.issueDate = issueDate;
}
public void displayDetails() {
System.out.println("Magazine Title: " + getTitle());
System.out.println("Author: " + getAuthor());
System.out.println("Issue Date: " + issueDate);
}
}

DVD.java:

package q7;
public class DVD extends LibraryResource {
private int duration;
public DVD(String title, String author, int duration) {
super(title, author);
this.duration = duration;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public void displayDetails() {
System.out.println("DVD Title: " + getTitle());
System.out.println("Author: " + getAuthor());
System.out.println("Duration: " + duration + " minutes");
}
}

LibrarySystem.java:

package q7;
public class LibrarySystem {
public static void main(String[] args) {
LibraryResource book = new Book("The Great Gatsby", "F. Scott
Fitzgerald", 180);
LibraryResource magazine = new Magazine("Time", "Henry Luce", "January
2025");
LibraryResource dvd = new DVD("Inception", "Christopher Nolan", 148);
book.displayDetails();
System.out.println();
magazine.displayDetails();
System.out.println();
dvd.displayDetails();
}
}

Prepared by MAJI, A.
8. Develop a Java banking application using polymorphism with three classes: Account,
SavingsAccount, and CurrentAccount. The abstract Account class has private attributes
(accountNumber, balance) and abstract methods for deposit and withdrawal.
SavingsAccount adds an interestRate attribute, overrides deposit to calculate interest,
and ensures sufficient balance in withdrawal. CurrentAccount introduces an
overdraftLimit and overrides withdrawal to check this limit. In the BankingApp class,
instantiate both account types, perform transactions, and display account details to
demonstrate polymorphism.

Account.java:

package q8;
public abstract class Account {
private String accountNumber;
private double balance;
public Account(String accountNumber) {
this.accountNumber = accountNumber;
this.balance = 0.0;
}
public String getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
protected void setBalance(double balance) {
this.balance = balance;
}
public abstract void deposit(double amount);
public abstract void withdraw(double amount);
}

SavingsAccount.java:

package q8;
public class SavingsAccount extends Account {
private double interestRate;
public SavingsAccount(String accountNumber, double interestRate) {
super(accountNumber);
this.interestRate = interestRate;
}
public void deposit(double amount) {
double interest = (getBalance() + amount) * (interestRate / 100);
setBalance(getBalance() + amount + interest);
System.out.println("Deposited: " + amount + ", Interest: " + interest +
", New Balance: " + getBalance());
}
public void withdraw(double amount) {
if (amount <= getBalance()) {
setBalance(getBalance() - amount);
System.out.println("Withdrew: " + amount + ", New Balance: " +
getBalance());
} else {
System.out.println("Insufficient balance for withdrawal.");
}
}
}

Prepared by MAJI, A.
CurrentAccount.java:

package q8;
public class CurrentAccount extends Account {
private double overdraftLimit;
public CurrentAccount(String accountNumber, double overdraftLimit) {
super(accountNumber);
this.overdraftLimit = overdraftLimit;
}
public void deposit(double amount) {
setBalance(getBalance() + amount);
System.out.println("Deposited: " + amount + ", New Balance: " +
getBalance());
}
public void withdraw(double amount) {
if (amount <= getBalance() + overdraftLimit) {
setBalance(getBalance() - amount);
System.out.println("Withdrew: " + amount + ", New Balance: " +
getBalance());
} else {
System.out.println("Withdrawal exceeds overdraft limit.");
}
}
}

BankingApp.java:

package q8;
public class BankingApp {
public static void main(String[] args) {
Account savingsAccount = new SavingsAccount("SA123", 5.0);
Account currentAccount = new CurrentAccount("CA456", 200.0);
savingsAccount.deposit(1000);
savingsAccount.withdraw(200);
savingsAccount.withdraw(900);
System.out.println();
currentAccount.deposit(500);
currentAccount.withdraw(600);
currentAccount.withdraw(200);
}
}

Prepared by MAJI, A.
9. Write a Java program demonstrating interfaces, method overriding, and method
overloading. Define a Vehicle interface with abstract methods accelerate() and brake().
Implement Car and Bicycle classes that override these methods with specific messages
for acceleration and braking. Introduce method overloading in both classes by defining
multiple accelerate() methods with different parameters (e.g., speed, duration). In the
VehicleApp class, instantiate Car and Bicycle objects, test overridden methods, and
invoke overloaded accelerate() methods to showcase polymorphism.

Vehicle.java:

package q9;
public interface Vehicle {
void accelerate();
void brake();
}

Car.java:

package q9;
public class Car implements Vehicle {
public void accelerate() {
System.out.println("Car is accelerating.");
}
public void brake() {
System.out.println("Car is braking.");
}
public void accelerate(int speed) {
System.out.println("Car is accelerating to " + speed + " km/h.");
}
public void accelerate(int speed, int duration) {
System.out.println("Car is accelerating to " + speed + " km/h for " +
duration + " seconds.");
}
}

Bicycle.java:

package q9;
public class Bicycle implements Vehicle {
public void accelerate() {
System.out.println("Bicycle is accelerating.");
}
public void brake() {
System.out.println("Bicycle is braking.");
}
public void accelerate(int speed) {
System.out.println("Bicycle is accelerating to " + speed + " km/h.");
}
public void accelerate(int speed, int duration) {
System.out.println("Bicycle is accelerating to " + speed + " km/h for "
+ duration + " seconds.");
}
}

Prepared by MAJI, A.
VehicleApp.java:

package q9;
public class VehicleApp {
public static void main(String[] args) {
Vehicle car = new Car();
Vehicle bicycle = new Bicycle();
car.accelerate();
car.brake();
bicycle.accelerate();
bicycle.brake();
Car myCar = new Car();
myCar.accelerate(100);
myCar.accelerate(100, 10);
Bicycle myBicycle = new Bicycle();
myBicycle.accelerate(20);
myBicycle.accelerate(20, 5);
}
}

Prepared by MAJI, A.
10. Design a Java program for university student enrollment, ensuring loose coupling and
high cohesion. Create Student and Course classes, and an Enrollment class that
interacts with them through an EnrollmentSystem interface. Implement methods for
enrolling and dropping students from courses, and displaying enrollment details. In the
MainEnrollApp class, demonstrate functionality by managing student enrollments. Use
comments to explain how the design maintains loose coupling (by relying on interfaces)
and high cohesion (by keeping related functionalities within appropriate classes).

Student.java:

package q10;
public class Student {
private String studentId;
private String name;
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Course.java:

package q10;
public class Course {
private String courseId;
private String courseName;
private Student[] enrolledStudents;
private int studentCount;
public Course(int maxStudents) {
this.enrolledStudents = new Student[maxStudents];
this.studentCount = 0;
}
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public Student[] getEnrolledStudents() {
return enrolledStudents;
}
public int getStudentCount() {
return studentCount;
}
public boolean addStudent(Student student) {
if (studentCount < enrolledStudents.length) {

Prepared by MAJI, A.
enrolledStudents[studentCount++] = student;
return true;
}
return false;
}
public boolean removeStudent(Student student) {
for (int i = 0; i < studentCount; i++) {
if (enrolledStudents[i].equals(student)) {
enrolledStudents[i] = enrolledStudents[studentCount - 1];
enrolledStudents[--studentCount] = null;
return true;
}
}
return false;
}
}

Enrollment.java:

package q10;
interface EnrollmentSystem {
void enrollStudent(Student student, Course course);
void dropStudent(Student student, Course course);
void displayEnrollmentDetails(Course course);
}
public class Enrollment implements EnrollmentSystem {
public void enrollStudent(Student student, Course course) {
if (course.addStudent(student)) {
System.out.println(student.getName() + " has been enrolled in " +
course.getCourseName());
} else {
System.out.println("Enrollment failed: " + course.getCourseName() +
" is full.");
}
}
public void dropStudent(Student student, Course course) {
if (course.removeStudent(student)) {
System.out.println(student.getName() + " has been dropped from " +
course.getCourseName());
} else {
System.out.println("Drop failed: " + student.getName() + " is not
enrolled in " + course.getCourseName());
}
}
public void displayEnrollmentDetails(Course course) {
System.out.println("Enrollment details for " + course.getCourseName() +
":");
for (int i = 0; i < course.getStudentCount(); i++) {
Student student = course.getEnrolledStudents()[i];
if (student != null) {
System.out.println("- " + student.getName() + " (ID: " +
student.getStudentId() + ")");
}
}
}
}

Prepared by MAJI, A.
MainEnrollApp.java:

package q10;
public class MainEnrollApp {
public static void main(String[] args) {
Student student1 = new Student();
student1.setStudentId("S001");
student1.setName("ABC");
Student student2 = new Student();
student2.setStudentId("S002");
student2.setName("DEF");
Student student3 = new Student();
student3.setStudentId("S003");
student3.setName("PQR");
Course course1 = new Course(2);
course1.setCourseId("C001");
course1.setCourseName("Mathematics");
Course course2 = new Course(2);
course2.setCourseId("C002");
course2.setCourseName("Physics");
Enrollment enrollmentSystem = new Enrollment();
enrollmentSystem.enrollStudent(student1, course1);
enrollmentSystem.enrollStudent(student2, course1);
enrollmentSystem.enrollStudent(student3, course1);
enrollmentSystem.enrollStudent(student1, course2);
enrollmentSystem.displayEnrollmentDetails(course1);
enrollmentSystem.displayEnrollmentDetails(course2);
enrollmentSystem.dropStudent(student1, course1);
enrollmentSystem.displayEnrollmentDetails(course1);
}
}

To join 4ᵗʰ SEMESTER • ITER Community on WhatsApp, click below:

https://chat.whatsapp.com/Kku9PogGnpjDIpsTeEGEBd

Prepared by MAJI, A.

You might also like