Java Multithreading and Collections Lab
Java Multithreading and Collections Lab
1. Write a program in which multiple threads add and remove elements from a
java. [Link]. Demonstrate that the list is being corrupted
Your task is to design a class Customer that meets the following requirements:
Requirements:
Requirements:
Requirements:
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"
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
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.
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
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.
Exercise-IV
[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
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.
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
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
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.
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:
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:
Requirements:
Date : 20-08-2025
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
Rules:
InsufficientFundsException (User-defined).
(Built-in).
TransactionFailedException.
Do the Following
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.
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
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
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
(Generic Class with Single Type Parameter + Generic Method with Bounded
Type Parameter)
Scenario:
Tasks:
(Generic Class with Multiple Type Parameters + Generic Method to Print Any Type)
Scenario:
Tasks:
(Generic Class with Bounded Type Parameters + Generic Method with Type)
Scenario:
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:
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
interface. Introduce a hierarchical structure where both `Order` and `Cart` extend
`price`, `stock`) in the following contexts: Inside `Product` itself, Inside `Order` (different
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,
method overriding.
management.
The **base class** `Person` contains details like name and contact.
rooms.
appointments.
array.
Course is a superclass with details like course name, duration, and base fee.
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)`).
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:
2. A student profile can also be created by passing roll number, name, and
object, ensuring the copy has the same values. This should simulate the
6. Create and display at least three student objects: one using default constructor,
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
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
1. Write a Java program to count how many objects of a class Employee are
created using a static variable.
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
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.
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:
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.
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:
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,
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.
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.