0% found this document useful (0 votes)
10 views50 pages

Java Multithreading and Collections Lab

The document outlines various Java programming exercises focused on multithreading, collections, arrays, exception handling, and inheritance. It includes tasks such as creating multithreaded applications, managing customer data, and implementing classes with specific functionalities. Additionally, it emphasizes the use of Java's built-in features like the Collections Framework and exception handling mechanisms.

Uploaded by

viralvortex379
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)
10 views50 pages

Java Multithreading and Collections Lab

The document outlines various Java programming exercises focused on multithreading, collections, arrays, exception handling, and inheritance. It includes tasks such as creating multithreaded applications, managing customer data, and implementing classes with specific functionalities. Additionally, it emphasizes the use of Java's built-in features like the Collections Framework and exception handling mechanisms.

Uploaded by

viralvortex379
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

CS23304 –Java Programming Laboratory – N batch

Multithreading and Collections Interface – on the spot


Exercise-IX
Date: 24.9.25 marks: 10 marks

1. Write a program in which multiple threads add and remove elements from a
java. [Link]. Demonstrate that the list is being corrupted

2. Write a program to sort a list/array of 10 integers, using two separate threads,


with each thread sorting half of the list and let the main thread wait and get
the two, sorted lists/arrays and resort them for the final sorted list. Print the
final sorted list in the class with the main() method
SIMPLE JAVA PROGRAMS
USING JAVA BASIC CONSTRUCTS

1. Write a Program Read and Print an Integer value in Java


2. Java Program to Multiply two Floating-Point Numbers
3. Java Program to Swap Two Numbers
4. Java Program to Check if a Given Integer is Odd or Even
5. Java Program to Find the Largest of three Numbers
6. Java Program to Display All Prime Numbers from 1 to N
7. Java Program to Check whether given number is Armstrong
Number
8. Java Program for factorial of a number
9. Java Program to Calculate Simple & Compound Interest
10. Java Program to display grade of a student
11. Java Program to check whether a number is divisible by 2 and
3, whether a number is divisible by 2 or 3, and whether a
number is divisible by 2 or 3 but not both:
12. Java Program to determine leap year.
13. Java Program to Check Whether the Character is Vowel or
Consonant.
14. Java Program to Print Left Triangle Star Pattern
15. Java Program to Find Sum of Fibonacci Series Numbers of
First N Even Indexes
JAVA LAB – Q Batch
SPOT Question – dated 16.07.2025

1. Some websites impose certain rules for passwords. Write a method


that checks whether a string is a valid password. Suppose the password
rules are as follows:
 A password must have at least ten characters.
 A password consists of only letters and digits.
 A password must contain at least three digits.
Write a program that prompts the user to enter a password and displays
Valid Password if the rules are followed or Invalid Password otherwise.
ARRAYS-CONSTRUCTOR-STATIC-THIS

1. A utility company is developing a Java-based electricity billing system. Each customer


has a name, customer ID, and monthly units consumed. The tariff rate is the same for
all customers and is stored as a static variable. The company also maintains a static
counter to track the number of customers created in the system.

Your task is to design a class Customer that meets the following requirements:

Requirements:

1. The class should have:


o Instance variables: name, customerId, unitsConsumed
o Static variables: tariffRate (price per unit), customerCount
2. A constructor to initialize each customer and increment the static
customerCount.
3. A static method to update the tariffRate.
4. A method calculateBill() that returns the total bill for the customer using the
formula:

totalBill = unitsConsumed * tariffRate

5. A static method getCustomerCount() that returns the total number of


customers created.

2. A university is developing a Student Enrollment System in Java. Each student has a


name, roll number, and course. Sometimes, the method parameters have the same
names as the instance variables. The development team decides to use the this keyword to
resolve naming conflicts and improve code clarity.

Requirements:

1. Create a class Student with the following instance variables:


o String name
o int rollNumber
o String course
2. Create a constructor that takes parameters (name, rollNumber, course) and
assigns them to the instance variables using the this keyword.
3. Create a method displayDetails() to print the student’s information.
4. Create another method enroll(Student s) that prints:
"Enrolling student: " + [Link]
5. Inside the main() method:
o Create two student objects.
o Use this to pass the current object to the enroll() method.
o Call displayDetails() for each student.
3. A school is building a system to manage student marks across different subjects. Each
student may have a different number of subjects, depending on their stream or
electives. Therefore, a ragged (jagged) array is needed to represent the marks.

You are tasked with developing a program that:

1. Stores marks of n students, where each student has a different number of


subjects.
2. Calculates and displays the total and average marks for each student.

Requirements:

1. Accept the number of students.


2. For each student:
o Ask for the number of subjects.
o Input marks for each subject.
3. Use a ragged array (int[][] marks) to store the data.
4. Calculate and display:
o All subject marks for each student
o Total marks
o Average marks (rounded to 2 decimal places)
STRING & DATE AND TIME API
1. Design a system to evaluate and score passwords based on the following criteria:
 Contains both upper and lower case letters (+2 points)
 Contains at least one digit (+2 points)
 Contains at least one special character (!@#$%^&*()_+) (+2 points)
 Length >= 12 (+2 points), Length >= 8 (+1 point)
 Does not contain any repeated substring of length ≥ 3 (–2 points)
Print each password’s score and whether it is "Strong" (≥6 points), "Moderate" (4–5),
or "Weak" (<4).
Sample Run
Pass123! - Score: 5 - Moderate
password - Score: 1 - Weak
Secur3P@ssword123 - Score: 8 - Strong
abcabcabc - Score: 0 - Weak
A1b2C3d4! - Score: 6 – Strong

2. You are given a compressed pattern string that may include numbers indicating
repeated characters, e.g., "a3b2" means "aaabb". Write a method that decompresses it and
checks if a target string matches the decompressed version.
3. Design a program that receives employee login and logout timestamps for a given day
and calculates:
Total hours worked.
Whether the employee was late (expected login time is 9:00 AM).
Whether the employee left early (expected logout time is 6:00 PM).
Sample Run
Login Time: "2025-07-28T09:15:00"
Logout Time: "2025-07-28T17:30:00"
Total worked hours: 8 hours 15 minutes
Late: Yes
Left Early: Yes
ARRAYS-CONSTRUCTOR-STATIC-THIS
SPOT QUESTION:

An educational platform offers various online courses. Each student can enroll in a different
number of courses, and their marks for each course need to be stored and analyzed. The system
also keeps track of how many students have been registered using a static counter. The
developers want to ensure good design using the this keyword where appropriate.

Requirements
Class: Student
1. Instance variables:
o String name
o int studentId
o int[] marks – stores marks in multiple courses
2. Static variables:
o int studentCount – total number of students created
3. Constructor:
o Accepts name, studentId, and an array of marks (use this to assign them).
o Increments studentCount each time a student is created.
4. Methods:
o double calculateAverage() – returns the average of that student's marks.
o void displayDetails() – prints name, ID, marks, and average.
o static int getStudentCount() – returns total students created.
STRING & DATE AND TIME API

SPOT

You are building a Log Analyzer for a server. Each log entry is a string in the format:
"[2025-07-28 14:30:00] - User 'john_doe' logged in"

Write a program that:


1. Parses a list of such log entries.
2. Extracts the timestamp and username from each entry.
3. Counts how many users logged in during business hours (9:00 AM to 6:00 PM).
4. Finds the earliest and latest login time.
CS23304 –Java Programming Laboratory – N batch
Multithreading and Collections Interface –Preparatory
Exercise-IX
Date: 24.9.25 marks: 15 marks
1. Create an abstract class called Account that has datamembers: accno(int),
accname(String) and balance(double), contactAddress(Address). The
member methods are: parameterized constructor and toString method. abstract
methods : void deposit(double amt) and double withdraw(double amt)
a. Derive two classes from class Account: SavingsAccount and
CheckingsAccount. The members of SavingsAccount are
noofTransactions(int), parameterized constructor, overridden methods
toString(), deposit(double amt) that increments balance with amt,
withdraw(double amt) that decrements the balance by amt and
noofTransactions is incremented by 1 inside deposit() and
withdraw().The members of CheckingAccount are parameterized
constructor, overridden methods deposit(double amt) that increments
balance with amt, withdraw(double amt) that decrements the balance
by amt only if the balance is above 1000 after decrementation and
toString().
b. Define TestAccount that creates two threads using Executor service
Framework and one each for deposit and withdraw. Make the methods
deposit and withdraw as syncronised.
(note: write only the definition of deposit and withdraw and
TestAccount in the Observation)
2. Write a program that creates a thread in addition to the main thread and runs
a code for converting temperature in centigrade to Fahrenheit and vice-versa.
Implement this using in both the ways (one using Thread class and using
Runnable Interface) in two separate programs.

3. Write a program that creates a LinkedList object of 10 characters, then creates


a second LinkedList object containing a copy of the first list, but in reverse
order

4. Write a Java program to create and start multiple (4 nos.) threads (either by
extending the Thread class or implementing the Runnable Interface) that
read and write from a shared text file concurrently. Display the state of each
thread with its name while running.
CS23304 –Java Programming Laboratory – N batch
Files and Serialization – on the spot
Exercise-VII
Date: 10.9.25 marks: 10 marks

1. Make the following modifications:


a. The constructor must Throw an exception if the format is not valid.

b. Allow the user to either add or delete one telephone number. Write the
modified data on the text file, replacing its original contents. Then read and
display the numbers from the modified file.
CS23304 –Java Programming Laboratory – N batch
Files and Serialization - preparatory
Exercise-VII
Date: 10.9.25 marks: 15 marks

1. Write a program that will record the maximum marks of a question paper. For
each question, read from the keyboard a question number, its subparts, and
the marks allotted to each part. Compute the marks of each question (subparts
times marks allotted) and write all this data to a text file. Also, display this
information and the maximum marks of the total questions on the screen.
After all questions have been entered, write the maximum marks to both the
screen and the file. Since we want to remember all the questions entered, you
should append new data to the end of the file.

2. Write a class TelephoneNumber that will hold a telephone number. An object


of this class will have the attributes
• areaCode—a three-digit integer
• exchangeCode—a three-digit integer
• number—a four-digit integer

the get and set methods and

• TelephoneNumber(aString)—a constructor that creates and returns anew


instance of its class, given a string in the form xxx–xxx–xxxx or, if the area
code is missing, xxx–xxxx.

• toString—returns a string in either of the two formats shown previously for


the constructor.

Using a text editor, create a text file of several telephone numbers, using the
two formats described previously.
Write a program to do the following
i. reads this file, displays the data on the screen, and creates an
array/arraylist whose base type is TelephoneNumber.
ii. Search for the given phone number if it exists return true, else false
Exception handling, String Builder
03/09/2025

1. Write a Java program that:

i. Takes two numbers from the user.


ii. Divides the first number by the second.
iii. Handles the following exceptions:
o ArithmeticException (e.g., divide by zero).
o InputMismatchException (if the user enters something other than a
number).
o A generic Exception for anything unexpected.
iv. Finally, prints "Program finished" no matter what happens.

2. Write a Java program with a method:

 calculateSquareRoot(double num)
o If num is negative, throw an IllegalArgumentException with the
message "Number cannot be negative".
o Otherwise, return the square root of the number.

In the main method: Ask the user for a number, Call calculateSquareRoot(), Handle
the exception properly.

3. Write a Java program

i. Take a string input from the user.

ii. Perform the following operations using StringBuilder:

o Append another string " - Java Lab" to it.


o Display the number of characters after appending the string.
o Insert "Programming" after the first word.
o Reverse the entire string.
o Replace the first 3 characters with "XYZ".

iii. Print the results after each operation.


CS23304 –Java Programming Laboratory – N batch

Inheritance and interfaces – on the Spot

Exercise-IV

Date: 20.8.25 marks: 10 marks

[Link] a class called Salesperson from Abstract class Person whose data members are:
age(integer), name(String), number of sales(integer), salary(double). The member functions are:
constructor with three arguments to initialise member variables age, name and salary and number
of sales is initialised always initialised to zero, addSale(double saleAmount) – method to
increment the number of sales for the amount of sale made, int getSales() – to return the sales
made by the Salesperson, display() – to display the details of the Salesperson, double getBonus()
– to return the bonus of Salesperson based on the following table:
Sales range Bonus amount

10-20 1000

20 – 40 2000

 40 5000

Create an Interface Tax with method calculateTax and static variable tax initialised with value
0.15. Implement this interface in class SalesPerson. Write a main program to print the
SalesPerson who has paid highest tax by implementing Comparator Interface.

Write a driver program to create object of Salesperson and test all methods.
CS23304 –Java Programming Laboratory – N batch

Inheritance

Exercise-V

Date: 13.8.25 [Link]: 15 marks

(10 marks for execution + 5 marks for observation)

1. Design a class named Person with fields for holding a Person’s name, address and
telephone number,emailid. Create a class named Customer, which extends the Person
class. The Customer class should have a field for a customer number(int) and a boolean
field indicating whether the customer wishes to be on a mailing list. Design a class named
PreferredCustomer, which extends the Customer class The PreferredCustomer class
should have fields for the amount of the customer’s purchases and the customer’s discount
level.

A retail store has a PreferredCustomer plan where customers can earn discounts on all
their purchases. The amount of a customer’s discount is determined by the amount of the
Customer’s cumulative purchases in the store as follows:

i. When a preferred customer spends Rs1,000, he or she gets a 7 percent discount on all
future purchases.
ii. When a preferred customer spends Rs 2,000 or more, he or she gets a 10 percent
discount on all future purchases.
Include constructors with arguments and appropriate set and get methods, toString() for each
of the class. Write a Test program to create an array objects of the Person and store the
Customer and Preferred Customer and invoke the methods of the classes.
CS23304 –Java Programming Laboratory – N batch
Class and Comparator/Comparable interface
Exercise-III
Date: 6.8.25 [Link]: 15 marks
(10 marks for execution + 5 marks for observation)
1. Define class called Employee with data members: firstName(String),
secondName(String), empId(int), salary(double), designation(String) and
dateofJoining(Date). The member functions are constructor with four
arguments, toString(), set and get methods. Include member variable
experience(Date), setExperience() – which will initialize the experience based
on the difference between the dateofJoining and current Date.

2. Implement interface Comparable<Employee> and override method


CompareTo – for comparing employees based on their experience

Implement interface Comparator <Employee> and override method compare


– for comparing objects of Employee based on salary

3. Create a Test class to create an arraylist of Employee Objects and sort the
objects based on experience and print it.
Make use of Lambda expressions to compare the Employee Objects based on
designation and then salary.
CS23304 –Java Programming Laboratory – N batch
Class and Class String – on the Spot
Exercise-II
Date: 30.7.25 marks: 10 marks
1. Make the following modifications in the TestBook class:
a. Include a function int countBook(ArrayList <Book>, String) – which
receives arraylist of Book and authorName, finds the number of books
authored by the given authorName and returns the same
b. Include a function ArrayList<Book> findBook(ArrayList <Book>,
String) – which receives arraylist of Book and authorName, creates an
arraylist of Books authored by the given authorName and returns the
same
c. Sort the arraylist<Book> returned by the function findBook in the
increasing order of year of publication
CS23304 –Java Programming Laboratory – N batch
Class and Class String – on the Spot
Exercise-II
Date: 30.7.25 marks: 10 marks
1. Make the following modifications in the TestBook class:
a. Include a function int countBook(ArrayList <Book>, String) – which
receives arraylist of Book and authorName, finds the number of books
authored by the given authorName and returns the same
b. Include a function ArrayList<Book> findBook(ArrayList <Book>,
String) – which receives arraylist of Book and authorName, creates an
arraylist of Books authored by the given authorName and returns the
same
c. Sort the arraylist<Book> returned by the function findBook in the
increasing order of year of publication
CS23304 –Java Programming Laboratory – N batch
Class and class String
Exercise-III
Date: 30.7.25 marks: 15 marks
1. The double helix of DNA is composed of two complementary strands.
Because the base pairs are formed by pairing A with T and G with C, we can
easily find the complement of a given DNA strand by simple substitutions.
For example, the complement of GATTCGATC is CTAAGCTAG. Write a
program that outputs the complement of a given DNA strand. Repeat the
operation until an empty string is entered.
2. Make the following modifications to class Book:
a. Include a data member number of copies (int)
b. Include bool issue(String) - which searches for the given title of the
Book in the arraylist of books and if found, decrements the number of
copies. Successful issue function returns True otherwise False
c. Include bool return(String) - which searches for the given title of the
Book in the arraylist of books and if found, increments the number of
copies. Successful return function returns True otherwise False
3. Define class called Employee with data members: name(String), empId(int),
salary(double) and designation(String). The member functions are constructor
with four arguments, void display(). Create a Test class to create an arraylist
of Employee and test the functions
CS23304 –Java Programming Laboratory – N batch
ArrayList and Class – on the Spot
Exercise-II
Date: 23.7.25 marks: 10 marks
1. Make the following modifications in the Time class:
a. Modify constructor with arguments to check whether hour, min and
sec in the range of 24 hour clock
b. Modify the display function to print the Time object as 12 hour clock
with a.m or p.m as suffix
2. Make the following modifications in the Book class:
a. void setBookTitle(String)- to initialize the title of the Book
b. void setPrice(double) - to initialize the prize of the Book
c. void setAuthorName(String) - to initialize the author name of the
Book
d. void getYearofPublication(int) - to initialize the year of publication of
the Book
e. String getBookTitle()- to return the title of the Book
f. double getPrice() - to return the prize of the Book
g. String getAuthorName() - to return the author name of the Book
h. int getYearofPublication() - to return the year of publication of the
Book
CS23304 –Java Programming Laboratory – N batch
ArrayList and Class
Exercise-II
Date: 23.7.25 marks: 15 marks
1. Define a class called Time with data members: hour(int), min(int),sec(int).
The member functions are: default constructor, constructor with three
integer arguments to initialize data members of Time object and void
display() – that displays the details about the Time object. Write a Test class
in which the objects of Time are created and methods called.
2. Create an arraylist<String> that consists of subjects enrolled by student.
Perform the following :
a. Initially the list is empty and add the subjects to
the list in the order of student attended.
b. Remove a subject
c. Check whether the student has enrolled for a
particular subject and if so return the position of
the subject
d. Find out how many subjects he/she had enrolled
e. Find out what was the last subject he/she had
enrolled
f. Find out whether the given subject was taken as
the fourth subject
3. Define class called Book with data members: bookTitle(String),
price(double), publisherName(String) and yearofPublication(int). the
member functions are: constructor with four arguments to initialize data
members of Book object and void display() – that displays the details about
the Book object. Write a Test class in which the objects of Book are created
and methods called.
CS23304 –Java Programming Laboratory – N batch
Introduction to Java Basics
Exercise-I – ON THE SPOT
Date: 16.7.25
Marks: 10 marks
1. Use a one-dimensional array to solve the following problem: A company pays
its salespeople on a commission basis. The salespeople receive $200 per
week plus 9% of their gross sales for that week. For example, a salesperson
who grosses $5,000 in sales in a week receives $200 plus 9% of $5,000, or a
total of $650. Write an application (using an array of counters) that
determines how many of the salespeople earned salaries in each of the
following ranges (assume that each salesperson’s salary is truncated to an
integer amount):

a) $200–299
b) $300–399
c) $400–499
d) $500–599
e) $600–699
f) $700–799
g) $800–899
h) $900–999
i) $1,000 and over

Summarize the results in tabular format.

2. Drivers are concerned with the mileage their automobiles get. One driver has
kept track of several trips by recording the miles driven and gallons used for
each tankful. Develop a Java application that will input the miles driven and
gallons used (both as integers) for each trip. The program should calculate and
display the miles per gallon obtained for each trip and print the combined
miles per gallon obtained for all trips up to this point. All averaging calculations
should produce floating-point results. Use class Scanner and sentinel-
controlled repetition to obtain the data from the user.
INTERFACE, DOWNCASTING and FINAL CLASS

1. Create two interfaces, Printer and Scanner. Both interfaces have a


default method called connect():
 Printer’s connect() prints "Connecting to printer".
 Scanner’s connect() prints "Connecting to scanner".
Create a class AllInOneDevice that implements both interfaces.
Override the connect() method to resolve the conflict by printing:
"Connecting to all-in-one device".
Also, inside the overridden method, call both interfaces' default
connect() methods.

2. You are designing a secure banking system. One of the core


components is an immutable class called BankAccount which
represents a customer's bank account. This class must be final to
prevent subclassing and alteration of critical account behavior.
Requirements:
Create a final class BankAccount with the following properties:
o Private final fields: accountNumber (String),
accountHolderName (String), and balance (double).
o A constructor to initialize these fields.
o Only getter methods, no setters, to ensure immutability.
Implement methods:
o deposit(double amount) returns a new BankAccount instance
with updated balance.
o withdraw(double amount) returns a new BankAccount
instance with updated balance if sufficient funds exist.
o Override toString() to print account details.
Demonstrate in your main program:
o Attempting to subclass BankAccount and explain the error.
o Create an account instance.
o Perform a deposit and withdrawal showing immutability by
returning new instances rather than modifying the existing
object.
o Show that the original instance remains unchanged after
operations.
3. You are developing a media player application that handles
different types of media files: Audio, Video, and Image. All these
media types extend a base class Media.
Requirements:
1. Create a base class Media with:
o A method play() that prints "Playing media".
2. Create three subclasses:
o Audio overriding play() to print "Playing audio file".
o Video overriding play() to print "Playing video file".
o Image overriding play() to print "Displaying image file".
3. In your media player, you store all media objects in an array of
Media references.
4. Write a method processMedia(Media m) that:
o Calls play() on the media.
o Uses downcasting to check the actual media type at runtime.
o If the media is an instance of Video, cast it to Video and call
a unique method displaySubtitle() (which you need to add in
the Video class, printing "Displaying subtitles").
o If the media is an instance of Audio, cast it to Audio and call
a unique method adjustVolume() (which prints "Adjusting
audio volume").
o If the media is an Image, cast it to Image and call a unique
method applyFilter() (which prints "Applying filter to
image").
5. Demonstrate the following in your main program:
o Create objects of each media type and store them in a
Media[] array.
o Iterate over the array and call processMedia() for each item.
POLYMORPHISM-METHOD OVERLOADING AND OVERRIDING

Q1. Design a class named Person and its two subclasses named Student and Employee. Make
Faculty and Staff subclasses of Employee. A person has a name, address, phone number,
and e-mail address. A student has a class status (freshman, sophomore, junior, or senior).
Define the status as a constant. An employee has an office, salary, and date hired. A faculty
member has office hours and a rank. A staff member has a title. Override the toString
method in each class to display the class name and the person’s name.

Write a test program that creates a Person, Student, Employee, Faculty, and Staff, and
invokes their toString() methods.

Q2. Design a simulation of a Multi-Mode Payment System that supports different payment
methods: CreditCard, DebitCard, UPI, and NetBanking.

Each payment method has:

 A unique transaction fee logic.


 A way to authorize a payment.
 Custom initialization messages using static and instance initializer blocks.

Requirements:
1. Create a base class PaymentMethod with:
o A double amount field.
o A constructor to set the amount.
o A method double calculateFee() — to be overridden.
o A method void authorize() — to be overridden.
2. Create 4 subclasses:
o CreditCard
o DebitCard
o UPI
o NetBanking
Each subclass should:
o Override calculateFee() and authorize() with its own logic.
o Include a static block to print "Class [ClassName] loaded".
o Include an instance initializer block to print "Instance of
[ClassName] created".
3. Create a PaymentProcessor class:
o Has a method void process(PaymentMethod method) that:
 Calls authorize() and calculateFee() polymorphically.
o In the main method:
 Randomly choose one of the four payment types.
 Create an instance (with random amount ₹500 to ₹5000).
 Upcast to PaymentMethod.
 Call process()
Q3. Design a Custom Calculator that demonstrates the full depth of method overloading

You must overload the calculate() method for different operations and data types. The
program should highlight how Java resolves overloaded methods based on:

 Number of arguments
 Argument types
 Type promotion
 Varargs
 Ambiguity in overloads

Requirements:

1. Create a class CustomCalculator with at least 6 overloaded versions of a method


named calculate():
o int calculate(int a, int b) – returns sum
o double calculate(double a, double b) – returns product
o long calculate(long a, int b) – returns difference
o float calculate(float a, float b, float c) – returns average
o int calculate(int... values) – uses varargs to return total
o void calculate(short a, short b) – just prints "Short version called"
2. In the main() method of a separate class:
o Call all the overloaded versions of calculate() with appropriate arguments.
o Intentionally call the method with values like calculate(10, 10) and observe
which version is called.
o Call calculate(10L, 10) and calculate(10, 10L) – and explain the results.
o Attempt to call calculate(10, 10) when both int and short versions are
available, and observe ambiguity.
o Resolve ambiguity explicitly using type casting.
LAB RE-TEST
Q1. You are tasked with designing an online shopping system in Java. The system includes
various types of users and products, and must handle different error conditions using user-
defined exceptions. (15)

Requirements:

1. Class Hierarchy:
o Create a base class User with common attributes like userId, name, and email.
o Derive subclasses Customer and Admin from User.
 Customer has attributes like cart (a list of Product objects) and methods
to add or remove products from the cart.
 Admin has additional privileges such as adding or removing products from
the product catalog.
2. Product Hierarchy:
o Create a base class Product with attributes like productId, name, and price.
o Create subclasses such as Electronics, Clothing, and Books, each with
additional specific attributes.
3. User-Defined Exceptions:
o Define the following user-defined exceptions:
 ProductNotFoundException — thrown when a product is not found in
the catalog.
 InsufficientStockException — thrown when the customer tries to buy
a quantity greater than available stock.
 UnauthorizedAccessException — thrown when a user attempts an
action they are not authorized to perform (e.g., Customer trying to remove
a product from catalog).
4. Functionality:
o Implement methods for:
 Customers to add products to their cart and checkout.
 Admins to add or remove products from the catalog.
o During these operations, relevant exceptions should be thrown and properly
handled.

Tasks:

 Design the class hierarchy using inheritance.


 Define the user-defined exceptions.
 Write code demonstrating:
o Adding and removing products by Admin.
o Adding products to cart by Customer.
o Checking out and handling exceptions such as InsufficientStockException
and ProductNotFoundException.
o Handling unauthorized actions with UnauthorizedAccessException.
Q2. Implement a Java class StringManipulator with the following functionalities that work only
with Strings and primitive data types: (10)

Requirements:

1. Find First Non-Repeating Character:


o Write a method char firstNonRepeatingChar(String input) that returns the
first character in the string that does not repeat anywhere else.
o If all characters repeat, return a special character such as '\0'.
o Do not use arrays, lists, or maps.
2. Reverse Words in a Sentence:
o Write a method String reverseWords(String sentence) that reverses the
order of words in a sentence, but not the characters in the words themselves.
o For example, "Hello World from Java" → "Java from World Hello".
o Do not use any collection types or split methods that return arrays.
3. Check if String is a Rotation of Another:
o Write a method boolean isRotation(String s1, String s2) that returns
true if s2 is a rotation of s1.
o For example, "abcd" and "cdab" are rotations.
o Use only string concatenation and basic string operations, no arrays or collections.
SPOT Question

Date : 20-08-2025

Implement a class BankAccount with:

 A private double balance field.


 A constructor that initializes the balance.
 Methods:
o void deposit(double amount) — adds the amount to balance but throws
NegativeAmountException if amount is negative.
o void withdraw(double amount) — subtracts the amount from balance but:
 Throws NegativeAmountException if amount is negative.
 Throws InsufficientFundsException if amount > balance.

In the main method:

 Create a BankAccount instance with an initial balance.


 Simulate a series of deposits and withdrawals by calling the respective methods.
 Use nested try-catch blocks to:
o Handle InsufficientFundsException specifically.
o Handle NegativeAmountException.
o Handle any other unexpected exceptions.
 Ensure that after every transaction, the program prints the current balance.
 Ensure that resources like scanner or any I/O are properly closed in a finally block.
EXCEPTION HANDLING
1.a. Using the two arrays shown below, write a program that prompts the user to enter an integer
between 1 and 12 and then displays the months and its number of days corresponding to the
integer entered. Your program should display “wrong number” if the user enters a wrong number
by catching ArrayIndexOutOfBoundsException.

1. [Link] previous program works well as long as the user enters an integer. Otherwise, you may
get another kind of exception. For instance, if you use nextInt() of Scanner, you could have an
InputMismatchException. Modify it to prevent users entering anything other than an integer.
2. a. Write hex2Dec(String hexString) method, which converts a hex string into a decimal
number. Implement the hex2Dec method to throw a NumberFormatException if the string is not
a hex string.
2. b. Define a custom exception called HexFormatException. Implement the hex2Dec method to
throw a HexFormatException if the string is not a hex string.

3. Write a Java program to create a method that takes an integer as a parameter and throws an
exception if the number is odd.

4. Write a Program to Print all Permutations of a String and throws an exception if the string
length is greater than 10.

5. Write a Java program that reads a list of integers from the user and throws an exception if any
numbers are duplicates.
SPOT: Expt. No. 5 Implementation of Exception Handling

A bank application manages customer transactions (withdrawals and deposits).

 Rules:

1. When a user tries to withdraw more than balance, throw

InsufficientFundsException (User-defined).

2. If the withdraw amount is negative, throw IllegalArgumentException

(Built-in).

3. Chain exceptions → When a withdrawal fails, wrap it inside a custom

TransactionFailedException.

4. Use an assertion to ensure balance >= 0 after every transaction.

 Do the Following

1. Create a BankAccount class with methods deposit() and withdraw().

2. Implement InsufficientFundsException and TransactionFailedException.

3. Demonstrate exception chaining (cause parameter in constructor).

4. Use assertions to check that account balance never goes negative.

5. Write test cases for all conditions (valid transaction, insufficient balance,

invalid input).
SPOT for [Link]. 6

A smart city project requires managing traffic at an intersection with four roads (North,

South, East, West). Each road has cars (threads) approaching the intersection. To

avoid accidents, only one road should have the green light at a time, and cars from

other roads must wait. The system should dynamically switch traffic lights after a

certain time interval while allowing waiting cars to move when their road is green.

Model cars as threads approaching from different directions. Implement a

synchronized mechanism (like a monitor/lock) to ensure only one direction has the

green light at a time. Introduce a TrafficController thread that periodically changes the

traffic light. Avoid deadlocks (e.g., cars waiting indefinitely). Extend the solution to

prioritize emergency vehicles (like an ambulance) which should bypass normal

synchronization rules.
SPOT for Expt. No. 7

An online exam system generates student results and stores them in a file (StudentID, Name,

Subject, Marks). The university needs to analyze the data for performance reports: Generate a

rank list in descending order of marks. Find all students scoring above average. Allow random

updates of marks in case of re-evaluation. Use BufferedReader/Writer or

FileInputStream/FileOutputStream to store and retrieve student results sequentially. Use

RandomAccessFile to update a student’s marks after re-evaluation. Apply Streams API to: Sort

students by marks. Calculate average marks and filter students scoring above average. Generate

a report of top 5 [Link] the final report to a new output file.


Library Management System

(Generic Class with Single Type Parameter + Generic Method with Bounded
Type Parameter)

Scenario:

A library maintains different types of resources such as Books, Magazines, and


Journals. The library wants a generic container to hold resources of any type.
Additionally, it requires a method to compare the number of pages between two
resources to determine which one is larger.

Tasks:

1. Create a generic class LibraryResource<T> where T can be any resource


type (Book, Magazine, etc.).
o Include methods to add and retrieve a resource.
2. Implement a generic method getLarger(T a, T b) with a bounded type
parameter (T extends Comparable<T>) to compare two resources and return
the one with more pages.
3. In the driver program:
o Create objects of Book and Magazine classes (both implement
Comparable).
o Use the LibraryResource class to store them.
o Call the generic method to compare the two and determine which has
more pages.
Employee Performance Tracker

(Generic Class with Multiple Type Parameters + Generic Method to Print Any Type)

Scenario:

A company wants to track employee performance across different departments.


Each record should hold an Employee ID (Integer) and a Performance Score
(Double). The company also wants the ability to print out lists of employees,
departments, or scores using a single reusable method.

Tasks:

1. Create a generic class EmployeeRecord<K, V> where:


o K = Employee ID (Integer).
o V = Performance Score (Double).
o Include methods to retrieve ID and score.
2. Implement a generic method printList(T[] items) that prints any type of
array (employee IDs, department names, or scores).
3. In the driver program:
o Create multiple employee records.
o Use the EmployeeRecord class to store their IDs and scores.
o Use the generic method to print arrays of employee IDs, department
names, and performance scores.
Student Grade Analyzer

(Generic Class with Bounded Type Parameters + Generic Method with Type)

Scenario:

A university is developing a system to analyze student grades. Each course may


use different numeric types to represent marks (e.g., Integer for whole numbers,
Double for decimal grades). The system should only accept numeric values (no
strings or other data types).

The university also requires a method to calculate the average grade of a group of
students, regardless of whether grades are stored as integers or doubles.

Tasks:

1. Create a generic class Grade<T extends Number> that:


o Stores a grade of type T.
o Provides a method getGrade() to retrieve the grade.
2. Implement a generic method calculateAverage(T[] grades) with a return
type double, which:
o Accepts an array of numeric grades (Integer[], Double[]).
o Returns the average value of the grades.
3. In the driver program:
o Create an array of Grade<Integer> and Grade<Double> objects.
o Demonstrate calculating the average grade using the generic method.
o Print the results for both integer-based and double-based grades.
SPOT Expt. No. 4c. Types of Inheritance and Different Accessibility of Packages

An E-Commerce Platform has multiple modules for products, users, and

payments. The Product class is in the `[Link]` package with attributes:

`productId` (private), `productName` (public), `price` (protected), `stock` (default). The

Order class is in the `[Link]` package and extends `Product`. The Cart class

is in the `[Link]` package but does not extend `Product`. The SpecialOrder

class is in `[Link]` package and extends `Order`.

Apply hierarchical inheritance where `Order` and `SpecialOrder` inherit from

`Product`. Create an interface `Discountable with methods like `applyDiscount()`. Let

`Order` and `SpecialOrder` implement it. → Demonstrates multiple inheritance via

interface. Introduce a hierarchical structure where both `Order` and `Cart` extend

`Product`. Build a multilevel inheritance chain: `SpecialOrder` extends `Order`, which

extends `Product`. Apply hybrid inheritance by having a `FlashSaleProduct` class that

extends `Product` and implements two interfaces `Discountable` and `Sharable`.

Students must analyze **accessibility of attributes** (`productId`, `productName`,

`price`, `stock`) in the following contexts: Inside `Product` itself, Inside `Order` (different

package subclass), Inside `Cart` (different package non-subclass), Inside

`SpecialOrder` (multilevel inheritance across packages), Students should simulate

object creation in a `Main` class and show which members can be accessed directly,

and which are restricted due to **access specifiers and package rules.
Exp. No.: 4b SPOT - Implementation of simple inheritance, static nested class,

inner class, abstract class, upcasting, downcasting, ,method overloading and

method overriding.

Hospital Management System - A hospital requires a digital system for patient-doctor

management.

 The **base class** `Person` contains details like name and contact.

 Subclasses `Doctor` and `Patient` extend it.

 A **static nested class** `[Link]` manages the assignment of hospital

rooms.

 An **inner class** inside `Doctor` called `Schedule` represents daily

appointments.

 An **abstract class** `Treatment` defines `provideTreatment()` to be

implemented differently by `Surgery` and `Therapy`.

 Demonstrate **method overloading** in `Doctor` with multiple versions of

`prescribeMedicine()` (by drug name, by drug name + dosage).

 Demonstrate **method overriding** in `Patient` to show how `getDetails()` is

implemented differently from `Person`.

 Use **upcasting** when storing patients and doctors in a common `Person[]`

array.

 Use **downcasting** when accessing patient-specific medical history.

Write Java program to simulate a doctor scheduling appointments, a patient getting

treatment, and hospital admin assigning rooms.


Expt. No.: 4a) SPOT: Implementation of Inheritance, Static Nested Class,
Method Overloading and Overriding

An e-learning platform offers courses in various domains.

 Course is a superclass with details like course name, duration, and base fee.

 ProgrammingCourse and DesignCourse are subclasses that override the

calculateFee() method to include extra lab or design kit charges.

 Implement method overloading in EnrollStudent() to allow enrollment with

only name, or name plus discount code.

 Use a static nested class in Platform to manage platform policies like

maximum allowed students per course.

 Use a member inner class in Course to represent CourseMaterial.

Write Java code to:

1. Apply overloading for student enrollment.

2. Apply overriding to customize fee calculation.

3. Use static nested class for platform policies.

4. Use inner class for course materials.


SPOT for Expt. No. 3b: Leave Management Tracker

A startup company wants to build an internal Java application to help its employees
track their leave history. Each employee applies for leave by specifying a start date and
end date. The application should Accept start and end dates using the appropriate Java
Date and Time API classes, Calculate the total number of days of leave taken, Check if
the leave overlaps with a weekend (Saturday or Sunday). Display the day of the week
on which the leave starts and ends. Format the leave dates in a user-friendly format like
`"dd MMM yyyy (E)"` (e.g., `15 Aug 2025 (Fri)`).

Spot for Expt. No. 3a Library Notification System

A university library system wants to implement a notification module that automatically


sends customized reminders to students about their borrowed books. The system
should generate messages with student names, book titles, due dates, and action items
(like returning or renewing the book). You are assigned the task of developing this
module using Java Strings, ensuring efficient string processing and proper formatting.
The message should be generated in this format: `"Hello [StudentName], the book
'[BookTitle]' is due on [DueDate]. Please return or renew it soon.", All student names
must be properly capitalized regardless of input, If the book is overdue (compare current
date and due date as strings), append, Your book is overdue! check for specific user
responses like `"return"` or `"renew"`. Demonstrates at least **five different String
methods**. Shows a comparison of two strings created using both `==` and `.equals()`.
EduTrack – A Student Performance Monitoring System

You are hired by a startup developing an academic tracking tool named EduTrack,
which monitors and manages student performance across different courses. The
application is designed to count how many student records have been created, maintain
a list of grading utilities like GPA calculation and provide global constants like the
maximum GPA or passing grade that do not change. As the lead Java developer, you
are tasked with designing the Student and GradeUtils classes in a way that uses
static keyword effectively
1. Use Case 1: Counter for Number of Students (Static Variable)
o Every time a new Student object is created, the system should increment
a static counter studentCount.
o The counter should be accessible without creating an object of the class.
2. Use Case 2: Utility Methods (Static Method)
o You need to provide a utility method calculateGPA() that calculates a
student’s GPA based on an array of marks.
o This method should be placed in a separate utility class and be accessible
globally without instantiating the class.
3. Use Case 3: Application Constants (Static Final Constants)
o Define constants like MAX_GPA = 4.0 and PASS_GRADE = 35 that are
shared across the system.
o These constants should be unchangeable and referenced throughout the
app.
Design a small-scale Java application that includes:
 A Student class with instance fields like name, studentId, marks[], and a static
variable studentCount.
 A static block to initialize static variables if needed.
 A GradeUtils class with static methods such as calculateGPA() and static
constants like MAX_GPA and PASS_GRADE.
 Demonstrate usage of static methods, static variables, and constants inside a
main() method or test class.
SmartLibrary – Personalized Book Management System

Imagine you are part of a development team at a company building an application called
SmartLibrary, which helps users manage their personal library of books. The system
should allow a user to store details of each book, compare books, and generate
personalized messages for book reviews.
Each Book should have:
 title (String)
 author (String)
 price (double)
The company also wants to ensure that:
 Constructors can handle input values with the same names as instance
variables.
 Users can update book details.
 Book comparison and review generation should use the same Book object,
passed between methods.
 Method chaining is used to build personalized review messages.
You are required to:
 Design a Book class using all six applications of the this keyword.
 Use constructor overloading to create book objects with default values and
parameterized values.
 Write a method to update book details, resolving variable shadowing.
 Include a method to compare the price of two books by passing the current
object to another method.
 Demonstrate returning this from a method to allow method chaining (e.g.,
[Link]().setAuthor().setPrice()).
 Show how this can invoke another method of the same class internally.
SPOT – Expt. 2a. "Student Profile Management System"

A university plans to build a basic Student Profile Management System in Java. Each

student has a unique roll number, name, and GPA. The administration requires a

system where:

1. A new student profile can be created using a default constructor (where

default values are assigned).

2. A student profile can also be created by passing roll number, name, and

GPA using a parameterized constructor.

3. There should be a way to duplicate an existing student profile into another

object, ensuring the copy has the same values. This should simulate the

behavior of a copy constructor.

4. The rollNumber should be private (for security), name should be protected,

and GPA can be public.

5. Include a method to display student details that adheres to access restrictions.

6. Create and display at least three student objects: one using default constructor,

one using parameterized constructor, and one using copy constructor.


EXPT. NO.2 PROGRAMS TO ILLUSTRATE CONCEPT OF CLASS AND STATIC
CLASSES AND METHODS

2a. Programs using JAVA Class and Objects, Constructors and Access Specifiers

1. Student Record System - Create a Java program with a class Student that holds
data: rollNo, name, and department.
 Use a constructor to initialize the data
 Apply access specifiers appropriately to secure data
 Provide getter methods for accessing private fields
 Display the details using a separate method

2. Online Product Inventory - Develop a class Product with productId,


productName, and price.
 Use constructor overloading to allow both default and parameterized
initialization
 Use private variables with get and set methods
 Write a method to display products under ₹500

3. Hospital Patient Management - Implement a class Patient with fields name, age,
and disease.
 Use constructor to assign data
 Apply protected access to disease and private for age
 Create methods to display patient details
 Demonstrate access from another class in the same package

2b. Programs to illustrate static classes and methods

1. Write a Java program to count how many objects of a class Employee are
created using a static variable.

2. Create a utility class MathUtils with static methods to calculate:


 Square of a number
 Cube of a number
 Factorial of a number

3. Design a class Student with a static variable for collegeName. Create three
objects and change the college name using a static method.
SPOT for Expt 1a

1Marks Percentage and Grade Calculator

A student appears for five subjects in an exam. You are asked to create a Java code
segment that stores the marks of all five subjects using appropriate data types and
variables, calculates the total and percentage, and then prints the result. Use
expressions and operators appropriately.

Mobile Recharge System

A mobile service provider wants to build a basic billing system to compute the final
amount a customer has to pay after recharging. The system should take into account
the base recharge amount, applicable taxes, and a promotional discount. Write a Java
program that:

Declares appropriate variables to store:


o Base recharge amount (e.g., ₹199)
o Tax rate (e.g., 18%)
o Promotional discount (e.g., ₹20)
Uses Java data types appropriately (e.g., int, float, double).
Applies arithmetic operators to compute:
o Tax amount
o Total cost before and after discount
Displays the breakdown:
o Base amount
o Tax amount
o Discount
o Final amount to be paid

SPOT for Expt 1b

Voting System Summary

In a local election, 5 candidates receive votes from different polling booths. Write a
Java program that Stores vote counts for each candidate in an array.
Calculates and displays the total votes.
Identifies the winning candidate (max votes).
Displays the percentage of votes each candidate received.

Sales Performance Tracker

A company records the monthly sales of a salesperson for 12 months. Create a Java
program that:
🔹 Stores sales values in a 1D array.
🔹 Calculates total and average sales.
🔹 Displays months with sales above average.
🔹 Finds the best-performing month (highest sales).
Expt. No. 1a:

Develop Programs using Java Basic Constructs (Data Types, Variables,

Operators & Expressions) using ECLIPSE

i. Mobile Recharge Application

A mobile recharge application calculates the final amount to be paid after applying a

flat discount. The user enters the recharge amount as an integer, and the discount as

a percentage (e.g., 10.0). Write a Java program segment that declares appropriate

variables using suitable data types, applies the discount using arithmetic operators,

and prints the final amount to be paid.

ii. Electricity Bill Calculator

An electricity board charges customers based on their monthly usage. The first 100

units are charged at ₹1.50 per unit, and units above 100 are charged at ₹2.50 per unit.

Create a Java code snippet that takes the number of units consumed as input, uses

suitable data types and variables, and calculates the total bill using expressions and

operators.

iii. BMI Calculator

You are designing a health app that calculates the Body Mass Index (BMI) of a user.

The user provides height in meters and weight in kilograms. Write a Java code snippet

using appropriate data types, variables, and expressions to compute BMI using the

formula BMI = weight / (height * height). Also, print the BMI result.

You might also like