0% found this document useful (0 votes)
9 views

Java Mid Lab

Uploaded by

ilyasshah6566
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Java Mid Lab

Uploaded by

ilyasshah6566
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

You are required to submit your semester project proposals according to the following

instructions:

1. Group Formation
o Form a group with a minimum of 1 and a maximum of 4 students.
o Collaborate effectively to ensure equal contribution from all group members.
2. Project Proposal Document
o Prepare a handwritten document of your project proposal.
o The document should include the following sections with clear headings:
▪ Problem Statement: Clearly define the problem your project aims to
address.
▪ Motivation: Explain the reasons for choosing this problem and its
significance.
▪ Requirement Specification: Detail the specific requirements and
objectives of your project.
▪ Programming Functionality: Describe the programming functionalities
and features you will implement.
▪ Flowchart: Provide a flowchart illustrating the workflow and logic of
your project.
3. Presentation
o Create a PowerPoint presentation (PPT) following good practices and
professional standards.
o Ensure the presentation covers all the sections mentioned in the project proposal
document.
o Be prepared to present your project effectively.
4. Viva Voce
o An individual viva will be conducted on Wednesday(6 November) based on
Warm-up Exercises 1 and 2.
o Each group member must be prepared to answer questions individually about
these exercises.
5. Task Submission
o Submit the following tasks in handwritten form:
▪ Motivation
▪ Specification
▪ Requirements
▪ Flowchart
▪ Code
o Additionally, execute your code on an Integrated Development Environment
(IDE) and upload it to the portal.

Submission Checklist:

• Handwritten project proposal document with all required sections.


• PowerPoint presentation prepared and ready.
• Handwritten tasks including motivation, specification, requirements, flowchart, and
code.
• Code executed and uploaded via the portal.
• Prepared for individual viva on Warm-up Exercises 1 and 2.

Important Notes:

• Adhere strictly to the submission deadlines.


• Ensure all work is original and properly cited if references are used.
• Maintain clear and legible handwriting in all submitted documents.
• Practice your presentation and viva to demonstrate a thorough understanding of your
project.
1. As a software engineer at a startup, you're tasked with designing a real-time messaging
application similar to WhatsApp or Telegram. The application must support the following
features: User Management: Users should be able to sign up, create profiles, and
manage their contacts. Messaging: Users can send text, images, and videos to individuals
or groups. Notifications: Real-time notifications should be delivered when a message is
received. Scalability: The system should handle millions of users and messages without
significant performance degradation. Maintainability: Future updates may include
adding voice calls, video calls, and integration with other services. Your development
team is proficient in both Object-Oriented Programming (OOP) and Modular/Structural
programming paradigms. However, there's a debate on which approach to adopt:

• Team A advocates for the Object-Oriented Approach, emphasizing encapsulation,


inheritance, and polymorphism to model users, messages, and notifications.
• Team B suggests the Modular/Structural Approach, focusing on breaking down the
system into functional modules for efficiency and simplicity.

Considering the requirements and future scalability, which programming approach should
you choose? Or is there a better solution that combines aspects of both? Provide a
detailed explanation of your choice, highlighting how it addresses the application's needs
more effectively than the alternative.

2. You are a software engineer tasked with designing a library management system for a
large university. The system must handle various types of media, including: Books:
Physical books with attributes like ISBN, title, author, and publication date. E-Books:
Digital versions of books with additional attributes such as file format and download link.
Magazines: Periodicals with volume and issue numbers. DVDs: Physical discs with
attributes like duration and director. Audio Books: Recordings of books with attributes
like narrator and audio length.

Requirements:

• Unified Catalog: All media types should be searchable through a unified catalog.
• Borrowing System: Users can borrow physical items (Books, DVDs) and check out
digital items (E-Books, Audio Books) online.
• Late Fees: Physical items incur late fees if not returned on time, calculated differently
based on the item type.
• Reservations: Users can reserve items that are currently checked out.
• Future Expansion: The system should easily accommodate new media types like Blu-
rays or online journals without significant code rewrites.

During development, you decide to use an Object-Oriented Approach to model the


system. You create a base class MediaItem and derive subclasses like Book, EBook,
Magazine, DVD, and AudioBook. Each subclass includes attributes and methods specific
to that media type.

However, as the project progresses, you encounter several issues:

• Code Duplication: Common functionalities like borrowing and reserving items are being
duplicated across subclasses.
• Inflexibility: Adding new media types requires altering existing classes, risking code
stability.
• Complexity: The inheritance hierarchy is becoming increasingly complex, making the
codebase hard to maintain.

Using Object-Oriented Concepts and Principles, how can you redesign your class
structure to address these issues? Provide a detailed explanation of your solution,
highlighting how it improves code reusability, maintainability, and extensibility
compared to your initial design.

3. You are required to design a class named BankAccount that represents a simple bank
account. The class should have the following:

Fields:
o accountNumber (String): The account number of the bank account.
o balance (double): The current balance of the account.

Methods:

o deposit(double amount): Adds the specified amount to the account balance.


o withdraw(double amount): Subtracts the specified amount from the account
balance, if sufficient funds are available.
o getBalance(): Returns the current balance of the account.

Define the BankAccount class with the specified fields and methods. Create an object of
BankAccount with an initial balance of $1,000 and account number "123456789".
Deposit $500 into the account. Withdraw $200 from the account. Print the final balance.

4. Create a class Rectangle that represents a rectangle shape. The class should include:
Fields:
o length (double)
o width (double)
Methods:
o calculateArea(): Returns the area of the rectangle.
o calculatePerimeter(): Returns the perimeter of the rectangle.
Define the Rectangle class with the specified fields and methods. Create an object of
Rectangle with a length of 5 units and a width of 3 units. Calculate and print the area and
perimeter of the rectangle.

5. Design a Student class that holds information about a student. The class should have:
Fields:
o name (String)
o studentID (String)
o grades (ArrayList<Double>)
Methods:
o addGrade(double grade): Adds a grade to the grades list.
o calculateAverage(): Calculates and returns the average grade.
o getGrades(): Returns the list of grades.
Define the Student class with the specified fields and methods. Create a Student object
for a student named "Alice" with ID "S1001". Add the grades 85.5, 90.0, and 78.0 to
Alice's grades. Calculate and print Alice's average grade.

6. Develop a Car class to represent a car in a simulation. The class should include:
Fields:
o make (String)
o model (String)
o fuelLevel (double): Current fuel level in liters.
o fuelConsumption (double): Fuel consumption rate in liters per kilometer.
Methods:
o drive(double distance): Simulates driving the car for a certain distance, reducing
the fuelLevel accordingly.
o refuel(double amount): Adds fuel to the fuelLevel.
o getFuelLevel(): Returns the current fuel level.
Define the Car class with the specified fields and methods. Create a Car object
representing a "Toyota Corolla" with a fuel level of 50 liters and a fuel consumption rate
of 0.05 liters/km. Drive the car for 200 kilometers. Refuel the car with 20 liters. Print the
final fuel level.

7. Create a LibraryBook class to manage books in a library system. The class should have:

Fields:

o title (String)
o author (String)
o isCheckedOut (boolean)

Methods:

o checkOut(): Sets isCheckedOut to true.


o returnBook(): Sets isCheckedOut to false.
o getStatus(): Returns "Checked out" or "Available" based on isCheckedOut.

Define the LibraryBook class with the specified fields and methods. Create a
LibraryBook object for "1984" by "George Orwell". Check out the book. Print the book's
status. Return the book. Print the book's status again.

8. You are asked to create a class named Person that represents an individual's basic
information. The class should include:

Fields:

o name (String)
o age (int)
o address (String)

Constructors:

o A default constructor that initializes the name to "Unknown", age to 0, and


address to "Not specified".
o An overloaded constructor that accepts only name and age, initializing address to
"Not specified".
o Another overloaded constructor that accepts name, age, and address.

Methods:

o displayInfo(): Prints out the person's name, age, and address.

Define the Person class with the specified fields, constructors, and method. In your Main
class:

o Create an instance of Person using the default constructor.


o Create another instance using the constructor that accepts name and age, with
values "Alice" and 30.
o Create a third instance using the constructor that accepts all fields, with values
"Bob", 25, and "123 Main St".

For each instance, call the displayInfo() method to print the person's information.

9. Design a class named Book that represents a book in a library system. The class should
include:

Fields:

o title (String)
o author (String)
o yearPublished (int)
o ISBN (String)

Constructors:

o A constructor that accepts only the title and author, setting yearPublished to -1
and ISBN to "Unknown".
o An overloaded constructor that accepts title, author, and yearPublished, setting
ISBN to "Unknown".
o Another overloaded constructor that accepts all fields: title, author, yearPublished,
and ISBN.

Methods:

o displayDetails(): Prints out the book's details.

Define the Book class with the specified fields, constructors, and method.
In your Main class:

o Create an instance of Book using the constructor that accepts only title and author,
with values "The Great Gatsby" and "F. Scott Fitzgerald".
o Create another instance using the constructor that accepts title, author, and
yearPublished, with values "1984", "George Orwell", and 1949.
o Create a third instance using the constructor that accepts all fields, with values
"To Kill a Mockingbird", "Harper Lee", 1960, and "978-0-06-112008-4".

For each instance, call the displayDetails() method to print the book's information.

10. You are developing a simple inventory management application for a retail store. You
need to create a class Product that represents items in the inventory. The class should
include:

Fields:

o productID (String)
o name (String)
o price (double)

Methods:

o displayProductInfo(): Prints the product's details.

Define the Product class with the specified fields and method. In your Main class:

o Create three Product objects: productA, productB, and productC.


▪ productA: "P001", "Laptop", $1,000
▪ productB: "P002", "Smartphone", $500
▪ productC: Assign it the reference of productA.

Print the memory addresses (references) of productA, productB, and productC. Modify
the price of productC to $900. Display the details of productA and productC using
displayProductInfo(). Explain how memory allocation and object references work in this
scenario.

11. You are writing a program that processes large amounts of data. To monitor resource
usage, you decide to create a class DataProcessor that performs computations and tracks
when objects are created and destroyed.

Fields:

o processorID (int)
o data (int[]): An array representing data to be processed.
Methods:

o processData(): Performs a simple computation on the data array.


o finalize(): Overrides the finalize() method to display a message when the object is
garbage collected.

Define the DataProcessor class with the specified fields and methods. In your Main class:

o Create a loop that creates DataProcessor objects with unique processorIDs from 1
to 5.
o Inside the loop, after creating each DataProcessor, set its reference to null.
Suggest a way to trigger garbage collection manually (note that calling
System.gc() is a request, not a guarantee). Explain how garbage collection works
in this context and the role of the finalize() method. Discuss the implications of
using finalize() in modern Java applications.

12. You are tasked with enhancing the security of a BankAccount class by properly
encapsulating its fields and controlling access to its members. The class should represent
a bank account with the following:

Fields:

o accountNumber (String)
o balance (double)
o accountHolderName (String)

Methods:

o deposit(double amount): Adds the specified amount to the balance.


o withdraw(double amount): Subtracts the specified amount from the balance if
sufficient funds are available.
o getBalance(): Returns the current balance.
o getAccountNumber(): Returns the account number.
o getAccountHolderName(): Returns the account holder's name.

Requirements:

1. Encapsulation:
o Make all fields private to prevent direct access from outside the class.
o Provide public getter methods for accountNumber, accountHolderName, and
balance.
o Do not provide any setter methods; the account details should be immutable after
creation, except for the balance which is modified through deposit and withdraw
methods.
2. Package Access:
o Assume the class is part of a package called banking. Any classes within the same
package should have access to the accountNumber for internal processing but
should not expose it publicly.

Define the BankAccount class with the specified fields and methods, applying
appropriate access modifiers. Explain how the access modifiers enforce encapsulation
and control visibility. Demonstrate, with code snippets, how another class within the
banking package can access the accountNumber, and how a class outside the package
cannot.

13. You are creating a class hierarchy for a role-playing game (RPG). The base class
Character represents a generic game character, and subclasses like Warrior and Mage
inherit from it.

Character Class:

o Fields:
▪ name (String)
▪ health (int)
▪ level (int)
o Methods:
▪ attack(): Abstract method.
▪ displayStatus(): Displays character's name, health, and level.

Requirements:

1. Encapsulation with protected:


o Declare health and level as protected, allowing subclasses to access and modify
them directly.
o Keep name as private, accessible only through methods.
2. Inheritance and Access:
o Implement subclasses Warrior and Mage that extend Character.
o In Warrior, create a method takeDamage(int damage) that reduces health when
the character is attacked.
o In Mage, create a method castSpell() that increases level by 1 when a spell is
successfully cast.
Define the Character class with the specified fields, methods, and access modifiers.
Implement the Warrior and Mage subclasses, demonstrating how protected members are
accessed and modified in subclasses. Explain the difference between private and
protected in the context of inheritance.

14. You are developing a library of mathematical functions divided into two packages:

Package mathlib.basic:

o Contains basic mathematical operations.


o Classes:
▪ Calculator: Provides addition, subtraction, multiplication, and division.

Package mathlib.advanced:

o Contains advanced mathematical operations.


o Classes:
▪ Statistics: Provides methods for calculating mean, median, and standard
deviation.
▪ Helper: Contains utility methods not intended for public use.

Requirements:

1. Access Control:
o Calculator and Statistics classes should be public, accessible to users of the
library.
o The Helper class should not be accessible outside the mathlib.advanced package.
o Methods inside Helper should be package-private.
2. Encapsulation:
o Ensure that internal workings of the classes are hidden from users.
o Only expose methods that are intended for public use.

Define the Calculator, Statistics, and Helper classes with appropriate access modifiers.
Demonstrate how a user can access Calculator and Statistics from outside the packages.
Show that the Helper class and its methods are not accessible outside mathlib.advanced.
Explain how package access and visibility modifiers help in designing a secure and well-
encapsulated library.

15. You are developing a class ComplexNumber to represent complex numbers in the form
a+bia + bia+bi, where aaa is the real part and bbb is the imaginary part.

Fields:
o real (double)
o imaginary (double)

Methods:

o add(ComplexNumber other): Adds another ComplexNumber to the current


instance and returns a new ComplexNumber with the result.
o subtract(ComplexNumber other): Subtracts another ComplexNumber from the
current instance and returns a new ComplexNumber with the result.
o display(): Prints the complex number in the form "a + bi".

Requirements:

1. Implement the ComplexNumber class with the specified fields and methods.
2. Use the this operator where appropriate to reference the current object's fields.
3. In your Main class:
o Create two ComplexNumber objects:
▪ num1 with real part 3.0 and imaginary part 2.0.
▪ num2 with real part 1.5 and imaginary part 4.5.
o Use the add method to add num2 to num1 and store the result in a new
ComplexNumber object sum.
o Use the subtract method to subtract num2 from num1 and store the result in a new
ComplexNumber object difference.
o Display num1, num2, sum, and difference.

Define the ComplexNumber class with appropriate use of the this operator. Demonstrate
passing and returning objects through methods. Explain how the this operator is used in
the context of the methods.

16. You are enhancing the Student class for a university system to include a copy
constructor. The class should represent a student with:

Fields:

o name (String)
o studentID (String)
o grades (ArrayList<Double>)

Methods:

o addGrade(double grade): Adds a grade to the student's list of grades.


o getGrades(): Returns the list of grades.
o displayInfo(): Displays the student's name, ID, and grades.
Requirements:

1. Implement the Student class with a copy constructor that creates a deep copy of a Student
object.
2. In your Main class:
o Create a Student object student1 and add grades 85.0 and 90.0.
o Use the copy constructor to create a new Student object student2 based on
student1.
o Add a new grade 95.0 to student2.
o Display the grades of both student1 and student2 to verify that they have
independent copies of the grades list.

Define the Student class with a copy constructor that performs a deep copy. Explain the
difference between a shallow copy and a deep copy in the context of copy constructors.
Demonstrate that modifying student2 does not affect student1.

17. You are asked to create a class Counter that keeps track of the number of Counter objects
created. Each Counter object also has an instance variable that holds its own unique
identifier.

• Fields:
oid (int): An instance variable representing the unique ID of each Counter object.
ocount (static int): A static variable that keeps track of the total number of Counter
objects created.
• Methods:
o Counter(): A constructor that increments the static count variable and assigns the
id based on the current value of count.
o getCount(): A static method that returns the current value of count.
o getId(): An instance method that returns the id of the Counter object.

Define the Counter class with the specified fields and methods. In your Main class:

o Create three Counter objects: c1, c2, and c3.


o Print the id of each Counter object.
o Use the static method getCount() to print the total number of Counter objects
created.

Explain how the static variable count and static method getCount() work in this context.

18. You are to create a utility class MathUtility that provides mathematical operations as
static methods. The class should include the following methods:
• Methods:
o factorial(int n): Returns the factorial of the given non-negative integer n.
o isPrime(int n): Returns true if the given integer n is a prime number, false
otherwise.
o gcd(int a, int b): Returns the greatest common divisor of integers a and b.

Requirements:

1. Implement the MathUtility class with all methods declared as public static.
2. In your Main class:
o Use the factorial method to calculate the factorial of 5.
o Use the isPrime method to check if 13 and 15 are prime numbers.
o Use the gcd method to find the greatest common divisor of 48 and 18.
3. Explain why it is appropriate to use static methods in the MathUtility class.

19. You are developing a program to store and analyze the test scores of a class of students.
There are 5 students, and you need to perform the following tasks: Declare an array of
integers named scores to hold the test scores of 5 students. Initialize the array with the
following scores: 85, 92, 76, 81, 95. Calculate and print the average score. Find and print
the highest score. Find and print the lowest score.

20. You are developing a seating chart for a theater. The theater has 3 rows, each with 4
seats. You need to: Declare a two-dimensional array seats of integers to represent the
seating chart. Initialize the array such that all seats are available (set to 0). Mark certain
seats as booked (set to 1): seat at row 1, column 2; seat at row 2, column 3; seat at row 3,
column 1. Print the seating chart in a readable format, showing available seats as A and
booked seats as B.

21. You need to write a program that can calculate the average of an array of double values.
The calculation should be performed in a separate method. Write a method
calculateAverage(double[] numbers) that accepts an array of doubles and returns the
average. In your Main class, create an array of double values: 10.5, 23.8, 5.7, 17.6, 9.0.
Call the calculateAverage method with the array and print the result.

22. You are working with an array of integers and need to perform various operations using
the Arrays utility class from java.util. Create an array numbers with the values: 42, 23,
16, 15, 8, 4. Use Arrays.sort() to sort the array in ascending order. Use
Arrays.binarySearch() to search for the value 15 in the sorted array. Use Arrays.fill() to
set all elements of the array to 0. Use Arrays.toString() to print the array after each
operation.

23. You need to create a copy of an array to modify the copy without affecting the original
array. Create an array originalArray with the values: 1, 2, 3, 4, 5. Create a copy of the
array using:

o The clone() method.


o Arrays.copyOf().

Modify the first element of each copied array to 99. Print all arrays to verify that the
original array remains unchanged.

24. You are tasked with explaining the concept of immutability using the String class in Java.
You need to demonstrate how strings behave when modified and the implications of their
immutability. Create a String variable original with the value "Hello". Concatenate "
World" to original and assign the result to a new variable modified. Print both original
and modified to show that original remains unchanged. Explain why the String class is
considered immutable and the benefits of this design choice.

25. Create an immutable class Point that represents a point in a 2D coordinate system with x
and y coordinates.

Requirements:

1. The class must have:


o Private final fields x and y of type double.
o A constructor to initialize x and y.
o Getter methods for x and y.
2. The class should not provide any setters or methods that modify the internal state.
3. Any methods that perform operations should return new Point instances.
4. Implement a method translate(double dx, double dy) that returns a new Point translated
by the given amounts.

Define the Point class as per the requirements. In your Main class:

o Create a Point object p1 at coordinates (2.0, 3.0).


o Use the translate method to create a new Point p2 by translating p1 by (1.0, -1.0).
o Print the coordinates of both p1 and p2 to show that p1 remains unchanged.

26. You need to illustrate the differences between mutable and immutable classes by
comparing two implementations of a Counter class.
Tasks:

1. Implement a mutable CounterMutable class with:


o A private field count (int).
o Methods increment() and getCount().
2. Implement an immutable CounterImmutable class with:
o A private final field count (int).
o A constructor to set count.
o A method increment() that returns a new CounterImmutable with an incremented
count.
o A method getCount().
3. In your Main class:
o Demonstrate how CounterMutable allows modification of its internal state.
o Demonstrate how CounterImmutable maintains immutability by returning new
instances.

27. You need to explain how the String Pool works in Java and how it relates to string
immutability. Create two String variables s1 and s2 initialized with the same string literal
"Java". Compare s1 and s2 using the == operator and equals() method. Create a new
String object s3 using new String("Java"). Compare s1 and s3 using the == operator and
equals() method. Explain the results and how the String Pool affects string comparisons.

28. You need to create an immutable class Employee that has a mutable field Date
representing the date of joining.

Requirements:

1. The Employee class must have:


o Private final fields name (String) and dateOfJoining (Date).
o A constructor to initialize the fields.
o Getter methods for name and dateOfJoining.
2. Ensure that the Employee class remains immutable despite having a mutable field.

Define the Employee class according to the requirements. In your Main class:

o Create an Employee object emp with name "John Doe" and date of joining as the
current date.
o Attempt to modify the dateOfJoining through the reference obtained from
getDateOfJoining().
o Show that the internal state of emp remains unchanged.
29. Discuss the benefits and potential drawbacks of using immutable classes in application
design. List at least three benefits of using immutable classes. List at least two potential
drawbacks or considerations when using immutable classes. Provide examples or
scenarios where immutability is advantageous and where it might be less suitable.

You might also like