0% found this document useful (0 votes)
3 views67 pages

BCS-452 (Object Oriented Programming Using Java Lab)

The document is a lab manual for the Object Oriented Programming using Java course (BCS-452) at PSIT, outlining the vision and mission statements of the institute and department, program educational objectives, outcomes, evaluation guidelines, syllabus, lab plan, and a list of experiments. It emphasizes the development of students into competent professionals capable of adapting to industry needs and includes a detailed correlation matrix between course outcomes and program outcomes. The manual serves as a comprehensive guide for students in their practical learning and assessment in the course.

Uploaded by

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

BCS-452 (Object Oriented Programming Using Java Lab)

The document is a lab manual for the Object Oriented Programming using Java course (BCS-452) at PSIT, outlining the vision and mission statements of the institute and department, program educational objectives, outcomes, evaluation guidelines, syllabus, lab plan, and a list of experiments. It emphasizes the development of students into competent professionals capable of adapting to industry needs and includes a detailed correlation matrix between course outcomes and program outcomes. The manual serves as a comprehensive guide for students in their practical learning and assessment in the course.

Uploaded by

Anmol Gamers
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Lab Manual

Object Oriented
Programming using Java
Lab

BCS-452

Semester: IV Year: Second


Session: 2023-24
Department of Computer Science and Engineering

PSIT-Pranveer Singh Institute of Technology


Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Table of Contents

 Vision and Mission Statements of the Institute

 Vision and Mission Statements of the Department

 PEOs, POs, PSOs of the Department

 Evaluation Scheme and Guidelines

 Syllabus

 Lab Plan

 Course Objective and Outcomes

 CO-PO & CO-PSO Correlation Matrix

 List of Experiments

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Vision Statement of the Institute

To achieve excellence in professional education and create an ecosystem for the holistic
development of all stakeholders.

Mission Statement of the Institute

To provide an environment of effective learning and innovation transforming students into


dynamic, responsible and productive professionals in their respective fields, who are
capable of adapting to the changing needs of the industry and society.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Vision Statement of the Department

To be a recognized department of Computer Science & Engineering that produces


versatile computer engineers, capable of adapting to the changing needs of computer and
related industry.

Mission Statements of the Department

1. To provide broad based quality education with knowledge and attitude to succeed in
Computer Science & Engineering careers.
2. To prepare students for emerging trends in computer and related industry.
3. To develop competence in students by providing them skills and aptitude to foster
culture of continuous and life-long learning.
4. To develop practicing engineers who investigate research, design and find workable
solutions to complex engineering problems with awareness & concern for society as
well as environment.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Program Educational Objectives (PEOs)


PEOs Description
The graduates will be efficient leading professionals with the knowledge of
PEO1 Computer Science & Engineering discipline that enables them to pursue
higher education and/or successful careers in various domains.
Graduates will possess capability of designing successful innovative solutions
PEO2 to real life problems that are technically sound, economically viable and
socially acceptable.
Graduates will be competent team leaders, effective communicators and
PEO3 capable of working in multidisciplinary teams following ethical values.
The graduates will be capable of adapting to new technologies/tools,
PEO4 constantly upgrading their knowledge and skills with an attitude for lifelong
learning.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Program Outcomes (POs)


POs Graduate Attributes Description
PO1 Engineering Apply the knowledge of mathematics, science and
Knowledge Computer Science & Engineering fundamentals to the
solution of complex engineering problems.
PO2 Problem Analysis Identify, formulate, review research literature, and
analyze complex Computer Science & Engineering
problems reaching substantiated conclusions using
principles of mathematics, natural sciences, and
engineering
PO3 Design/ Design solutions for Computer Science & Engineering
Development of and allied fields related complex engineering problems
and design system components or processes that meet the
Solutions
specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and
environmental considerations.
PO4 Investigation Use research-based knowledge of Computer Science &
Engineering and research methods including design of
experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.

PO5 Modern Tool Usage Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including
prediction and modeling to complex Computer Science &
Engineering activities with an understanding of the
limitations.
PO6 The Engineering Apply reasoning informed by the contextual knowledge
and Society to assess societal, health, safety, legal and cultural issues
and the consequent responsibilities relevant to the
professional engineering practice in the field of
Computer Science & Engineering.
PO7 Environment and Understand the impact of the professional Computer
Sustainability Science & Engineering solutions in societal and
environmental contexts, and demonstrate the knowledge

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

of, and need for sustainable development


PO8 Ethics Apply ethical principles and commit to professional
ethics and responsibilities and norms of the Computer
Science & Engineering practice
PO9 Individual and Function effectively as an individual, and as a member or
Team Work leader in diverse teams, and in multidisciplinary settings.
PO10 Communication Communicate effectively on complex Computer Science
& Engineering activities with the engineering community
and with society at large, such as, being able to
comprehend and write effective reports and design
documentation, make effective presentations, and give
and receive clear instructions.
PO11 Project Demonstrate knowledge and understanding of the
Management and Computer Science & Engineering and management
principles and apply these to one’s own work, as a
Finance
member and leader in a team, to manage projects and in
multidisciplinary environments.
PO12 Life-long Learning Recognize the need for and have the preparation and
ability to engage in independent and life-long learning in
the broadest context of technological change.

Program Specific Outcomes (PSOs)


PSOs Description
Use algorithms, data structures/management, software design, concepts of
PSO1
programming languages and computer organization and architecture.
Understand the processes that support the delivery and management of
PSO2
information systems within a specific application environment.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Evaluation Guideline and Scheme

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

CT: Class Test


TA: Teacher Assessment
L-T-P: Lecture - Tutorial - Practical

Evaluation Scheme Marks Sub-Total


Performance 20
Viva 10
Internal 25
Lab Record 10
Attendance 10
External University Exam 50 25
Grand Total 50

Syllabus
Following table outline the syllabus for Python Language Programming Lab (BCS-452) as
prescribed by Dr. A.P.J. Abdul Kalam Technical University, Uttar Pradesh, Lucknow.
The Syllabus can also seen on the university website:
[Link]
B.Tech_2nd_Yr_CSE_v3.pdf

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

LAB PLAN

SUBJECT NAME: Object Oriented Programming using Java Lab


SUBJECT CODE: BCS-452
Lab Schedule: As per the time table
i) Course Objective:
Students shall be able to design and implement efficient algorithms of various
computational problems along with their analysis in terms of its time complexity.

ii) Course Outcomes


*Level of Bloom’s Level to be *Level of Bloom’s Level to be
Taxonomy met Taxonomy met
L1: Remember 1 L2: Understand 2
L3: Apply 3 L4: Analyze 4
L5: Evaluate 5 L6: Create 6

CO Number Course Outcome


Define [1. Remember] various OOP concepts, programming
BCS-452.1 structures in Java.

Describe [2. Understand] objects, classes, interfaces, collection


BCS-452.2 framework, and libraries from Spring.

Apply [3. Application] various concepts of Java programming,


BCS-452.3 collection and Spring framework.

Compare [4. Analyze] various Java programming constructs,


BCS-452.4 such as constructors and methods etc., and APIs from Spring
framework.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

CO-PO & CO-PSO Correlation Matrix

Mapping of Course Outcomes with Program Outcomes and Program


Specific Outcomes:
Program Outcomes PSO
COs 1 2 3 4 5 6 7 8 9 10 11 12 1 2
BCS-452.1 3 - - - - - - - - - - 3 3 -
BCS-452.2 3 - - 3 3 - - - - - - - 3 -
BCS-452.3 - 3 3 3 - - - - - - - - 3 -
AVG 3 3 3 3 3 - - - - - - 3 3 -

Justification of CO-PO Mapping:


PO1: KCS452.1 is substantially mapped as student will be able to have
KCS452.1 knowledge about various built-in functions and data structures with its
associated methods.
with PO1 PO12: KCS452.1 is substantially mapped as student will be able to
and PO12 Design the solution of various problems by identifying which built-in
functions and data structures with its associated methods to be used for
implementing it in various projects like, ML, DL and Data Science
PO1: KCS452.2 is substantially mapped as student will be able to
apply knowledge of various available and third party modules in
KCS452.2
solving real-life complex problems easily.
with PO1, PO4: KCS452.2 is substantially mapped as student will be able to
investigate the problems according to the usage of appropriate data
PO4 and
structures to conclude towards the solution.
PO5 PO5: KCS452.2 is substantially mapped as student will be able to use
available or newly introduced module as a tool like pygame to model a
solution of complex problem easily.
PO2: KCS452.3 is substantially mapped as student will be able to
identify and formulate appropriate algorithm and data structure to be
KCS452.3
used after analyzing the type of the problem to be solved.
with PO2, PO3: KCS452.3 is substantially mapped as student will be able to
implement the chosen algorithms which in turn will implement the
PO3 and
solution of the problem with their programming skills.
PO4 PO4: KCS452.3 is substantially mapped as student will be able to
investigate various algorithms/functions available to appropriately
choose the correct and optimized solution of the given problem.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Justification of CO-PSO Mapping:


KCS452. PSO1:The students will be enabled with the knowledge of various built-in
1 with data structures, like string, list, tuple, set and dictionary and useful built-in
PSO1 so that can use it appropriately to find solution of real life problems.
KCS452.
PSO1: The students will be able to analyze and search appropriate module
2 with
for the design of optimal solution of the problem under consideration.
PSO1
KCS452. PSO1: The students will be able to investigate and use various algorithms,
3 with their complexity and different data structures of python to optimally solve
PSO1 the problem under consideration.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

List of Experiments

Lab Lab Experiment Corresponding CO


No.
Write a program to track 10 employees in the project and
their salaries, and also find out the average of their salaries.
They also want to find the number of employees who get a
salary greater than the average salary and those who get
lesser. Consider that the salaries are stored in an array of
double variables as given below: double salary[] =
{23500.0, 25080.0, 28760.0, 22340.0, 19890.0, 23555.0,
1
25980.0, 29760.0, 23340.0, 29890.0} Create a class
EmployeeRecord and write a program to implement the
above requirement. Refer to the output given below: The
average salary of the employee is : XXXXXX The number
of employees having salary greater than the average is : Y
The number of employees having salary lesser than the
average is : Z
2 Create a class Chocolate, with a parameterized constructor
and a default constructor. Also, use the "this" keyword
while initializing member variables within the
parameterized constructor. Every chocolate which is
manufactured will be with a default weight and cost. The
cost and weight might be modified later based on business
needs. Constructor Description: Chocolate( int barCode,
String name, double weight, double cost): In the
constructor initialize the member variables, barCode,
name, weight, and cost, according to the table given below:

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Attributes Values
barCode 1001
name Cadbury
weight 15
cost 50

Use setter methods to modify the values as given below:


Attributes Values
barCode 1002
name Hersheys
weight 30
cost 95

Use the below skeleton code for the Tester class main
method and do the required implementation. public class
ChocolateTester{ public static void main (String[] args)
{ //Create an object of chocolate //Use getter methods to
display the values //Use setter methods to modify the
values //Use getter methods to display the modified
values } }
A company wants to keep a record of the employees
working in it. There are permanent employees as well as
contract employees. Contract employees work on an
hourly basis whereas permanent employees are paid
3 monthly salary. The class diagrams are as given below:
Employee:

Employee
 empId : int

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

 name : String
 salary : double
 getSalary() : double
 setSalary(salary:double) : void
 getEmpId() : int
 setEmpId(empId :int) : void
 getName() : String
 setName(name : String) : void

A record of the employee name, salary, and the employee


Id has to be maintained for each employee.
PermanentEmployee:
PermanentEmployee
 basicPay : double
 hra : double
 experience : int
 getBasicPay() : double
 setBasicPay(salary:double) : void
 getHra() : double
 setHra(empId :double) : void
 getExperience() : int
 setExperience(name : int) : void
 calculateSalary() : void

Method Description:
calculateSalary():This method calculates the salary using the
formula as given below:
Salary = variable component + Basic pay +HRA
The condition for calculating variable component is given
below:

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Experience (in years) % of Basic pay


<5 0
>= 5 and < 7 5
>= 7 and < 12 10
>= 12 15

ContractEmployee:
ContractEmployee
 wages : double
 hours : int
 getWages(): double
 setWages(wages: double): void
 getHours(): int
 setHours(hours: int): void
 calculateSalary(): void

Method Description:
calculateSalary():This method calculates the salary
using the formula as given below: Salary = total
hours * wages

Implementation Details:
Create a class
EmployeeRecords and
implement the main method:
public class EmployeeRecords {

Public static void main(String str[]){


{

}
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Provide the following inputs:


Input (For PermanentEmployee):
Attributes Values
Name Abc
Employee Id 1001
Basic Pay 12500
HRA 3500
Experience 6

Output: Permanent Employee: Your Salary is : XXXX


Input (For ContractEmployee):
Attributes Values
Name Xyz
Employee Id 7001
Wages 750
Hours 15

Output: Contract Employee: Your Salary is : XXXX


Note:- You call setter and getter method of salary of
Employee class using an instance of both Permanent as
well as Contract Employee. The getter and setter method of
instance variable in parent class can be reused by child
classes as it is inherited from parent and hence need not be
created again.

The Provider as interface, provides an efficient way for


students to calculate their overall percentage of all the
4 courses. The totalMaximumMarks for all courses is 8000.
Intern studied in Institute A, where each semester comprises
of 1000 marks, in which 900 marks are for courses and 100
marks are kept for co- curricular activities (graceMarks).
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Whereas Trainee studied in Institute B where each semester


comprises of 1000 marks for courses.

Provider (interface)
+ totalMaximumMarks: int
+ calcPercentage(): void
Intern: This class for interns who completed their course in
Institute A.
Intern (class)
- marksSecured: int
- graceMarks: int
+ Intern(marksSecured:int, graceMarks: int)
+ calcPercentage(): void

Method Description: calcPercentage(): This method will


calculate the total marks of the intern which is the sum of
grace marks and the marks secured by the intern,
and hence calculate the percentage on the
totalMaximumMarks.

Trainee: This class is for trainees who completed their course


in Institute B.

Trainee (class)
- marksSecured: int
+ Trainee(marksSecured: int)
Method +calcPercentage(): void
Description:
calcPercentage(): calculates the overall percentage of the
marks of the trainee.
Input (For Intern):

Attribute Values
Marks Secure 4500
Output: The Grace Marks 400 total aggregate
percentage secured is [Link] Input (For Trainee):

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Attributes Values
Marks Secured 5500

Output: The total aggregate percentage secured is [Link]


Input (For Intern):

Attributes Values
Marks Secured 8000
Grace Marks 500

Output: Please enter the correct marks

1. Create a class "Employee" with data members


“empName",“empAge",“empSalary".
2. Add appropriate getter/setter methods for the data
members.
3. Create an Exception class “EmpSalaryException"
with an appropriate constructor.
4. Create a class Service with the main() method.
5. Write a method checkEmployeeSalary(Employee
5
emp) in Service, which checks if empSalary<1000
then throws EmpSalaryException.
6. In the Service class main() method:
A. Create five objects of employee class by passing
appropriate values to all the data members.
B. Call checkEmployeeSalary() method for each of
the five Employee objects being passed and
handle the EmpSalaryException.
C. Print the empName where the Salary is < 1000.
Create a Java program that adds Student objects into a
HashSet. The Student class has name, course and
6 rollNumber as its attributes and a toString() method. If we
add two Student objects having the same rollNumber to the
HashSet, it should be considered as duplicate and should
not get added.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Student (class)
- name: String
- course : String
- rollNumber : int
+ Student(name: String, course: String, rollNumber:int)
+ toString() : String
+ add() : boolean

Write a Java program that creates a “XYZBank” saving


account with concurrent deposits and withdrawals using
threads.

The XYZBank class represents a bank saving account with a


balance. For deposit() and withdrawal() methods, different
threads can execute them concurrently without conflict.

In the deposit() method, the lock is acquired before


updating the balance with the deposited amount. The lock is
7
acquired in the withdraw() method before checking the
balance and completing the withdrawal. If withdraw
amount is greater than balance amount then show
insufficient balance message.
The main method creates an instance of XYZBank and
starts four threads: two for deposits and two for
withdrawals. Each thread invokes the corresponding
method on the BankAccount instance, simulating
concurrent deposits and withdrawals.

8 Write a code using lambda expressions to display the


name of all the employees and their gender.
Create an application to display the details of the Student on
9 the console. A Model class “Student” has the following
properties.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Student (class)
- name: String
- course : String
- rollNumber : int
+ Student(name: String, course: String, rollNumber:int)

According to question 9, use annotations for the


configuration, instead of the xml. Also, add the init
10
method, destroy method. Implement these methods with
the logic to show the current system date and time.

Create a Spring Boot Application based on the below


requirement:

A. The application should support two RestFull URLs.


B. The first Restfull URL should display the student name
as a String.
C. The second restfull URL should display the address of
11 the student as String.
D. We would also be interested to see the list of
all the default beans that were created by
SpringBoot automatically in the console.
Test the application by executing and viewing the console
to see the list of beans and also test both the URLs to
verify that they return and display data as expected.
12 Amit wants to start a payment service portal for making
payments for the credit card bill and online shopping. He
will need a base class (MyPaymentServices) to store
balance and customer ID information. He will use two
classes- CreditCardPayment and ShoppingPayment for
paying Credit card bills and shopping bills respectively. The

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

bill payment and id generation is different for both payment


modes.

Class Description:
MyPaymentServices: This is the base class for
CreditCardPayment and ShoppingPayment classes. It will
store the amount to be paid by the user in the instance
variable balance of the class.

MyPaymentService
-balance:double
-customerId:int
+MyPaymentService(balance:double, customerId:int)
+setBalance(balance:double):void
+getBalance():doublie
+getCustomerId():int
+payBill(amount:double):void

Method Description:
payBill(double amount): This is an abstract method that has
to be implemented by the child classes of
MyPaymentServices.

ShoppingPayment:
This class is a child class of MyPaymentServices. It has a
static variable counter, to set the paymentID. The class
diagram is shown below:

ShoppingPayment
- static counter: int
- pymentId:String
+ ShoppingPayment(balance:double, customerId:int)
+ getPaymentId(): String
+ payBill(amount: double): void

Method DeSscription:
payBill(double amount): For a shopping bill payment, the
payment id should start with 'S' followed by a four digit
integer number. If the user enters an amount not equal to the
balance which is due, an appropriate error message should
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

be displayed and the id should get generated only for valid


payments.
CreditCardPayment:
This class is another child class of MyPaymentServices.
It has a static variable counter, to generate the
paymentID. The class diagram is shown below:

CreditCardPayment
- static conter:int
- paymentId:String
- cashBack: double
- balanceDue: double
+ CreditCardPayment(balance:double, customerId:int)
+ getPaymentId(): String
+ getCashBack(): double
+ getBalanceDue(): double
+ payBill(amount:double):void

Method Description:
payBill(double amount): For credit card bill payment, if a
user enters an amount more than the amount to be paid, the
excess amount should be stored as cashBack. The payBill
method is used to pay the bill and generate
the transaction id. The id should start with 'C' followed by a
four-digit integer number. In case the user enters an amount
less than the amount to be paid, then the remaining amount
should be stored in the instance variable balanceDue of
class CreditCardPayment.
 Use a Tester class to test your code and display the
payment information.
 The balanceDue after the payment should be
communicated to the user.

Some outputs with different inputs are given below for your
reference.

Input1 (For credit Attributes Values card)


Balance 10000.56
Customer Id 5001
Paid Amount 15000.00
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Output
Congratulations: You have successfully made a
payment of Rs. 15000 .Payment details are:-
Customer Id: 5001
Payment Id: 1001
Previous Due: 10000.56
Remaining Due: 0
Cash Back Wallet Balance: 4999.44

Input2 (For credit card)

Attributes Values
Balance 10000.56
Customer Id 5001
Paid Amount 0

Output
Congratulations: You have successfully made a
payment of Rs. 0.0 .Payment details are:-
Customer Id: 5001
Payment Id: C1002
Previous Due: 10000.56
Remaining Due: 10000.56
Cash Back Wallet Balance : 0.0

Input3 (For Shopping)

Attributes Values

Output: Balance 10000.56


Customer Id 5001
Paid Amount 5000

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Congratulations: You have successfully made a


payment of Rs. 5000.0 .Payment details are:-
Customer Id: 5001
Payment Id: C1001
Previous Due: 10000.56
Remaining Due: 5000.56

Input 4(For Shopping)

Attributes Values
Balance 5000.56
Customer Id 561328
Paid Amount 5000.00

Output
Congratulations: You have successfully made a payment
of Rs. 0.0 with Payment Id: s1001

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Experiment No. 1
Objective:. Write a program to track of 10 employees in the project and their salaries,
and also find out the average of their salaries. They also want to find the number of
employees who get a salary greater than the average salary and those who get lesser.
Consider that the salaries are stored in an array of double variables as given below:
double salary[] = {23500.0, 25080.0, 28760.0, 22340.0, 19890.0, 23555.0, 25980.0,
29760.0, 23340.0, 29890.0} Create a class EmployeeRecord and write a program to
implement the above requirement. Refer to the output given below: The average salary of
the employee is : XXXXXX The number of employees having salary greater than the
average is : Y The number of employees having salary lesser than the average is : Z.

Program:

public class EmployeeRecord {


public static void main(String[] args) {
double[] salaries = {23500.0, 25080.0, 28760.0, 22340.0, 19890.0, 23555.0,
25980.0, 29760.0, 23340.0, 29890.0};
// Calculate total salary and average salary
double totalSalary = 0;
for (double salary : salaries) {
totalSalary += salary;
}
double averageSalary = totalSalary / [Link];
// Count employees with salary greater than average and those with salary lesser
than average
int aboveAverageCount = 0;
int belowAverageCount = 0;
for (double salary : salaries) {
if (salary > averageSalary) {
aboveAverageCount++;
} else if (salary < averageSalary) {

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

belowAverageCount++;
}
}
// Output results
[Link]("The average salary of the employees is: " + averageSalary);
[Link]("The number of employees having salary greater than the
average is: " + aboveAverageCount);
[Link]("The number of employees having salary lesser than the average
is: " + belowAverageCount);
}
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Experiment No. 2
Objective:. Create a class Chocolate, with a parameterized constructor and a default
constructor. Also, use the "this" keyword while initializing member variables within the
parameterized constructor. Every chocolate which is manufactured will be with a default
weight and cost. The cost and weight might be modified later based on business needs.
Constructor Description: Chocolate( int barCode, String name, double weight, double
cost): In the constructor initialize the member variables, barCode, name, weight, and cost,
according to the table given below:
Attributes Values
barCode 1001
name Cadbury
weight 15
cost 50

Use setter methods to modify the values as given below:


Attributes Values
barCode 1002
name Hersheys
weight 30
cost 95

Use the below skeleton code for the Tester class main method and do the required
implementation. public class ChocolateTester{ public static void main (String[] args)
{ //Create an object of chocolate //Use getter methods to display the values //Use setter
methods to modify the values //Use getter methods to display the modified values } }

Program:
public class Chocolate {
// Member variables

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

private int barCode;


private String name;
private double weight;
private double cost;
// Default constructor
public Chocolate() {
[Link] = 1001;
[Link] = "Cadbury";
[Link] = 15;
[Link] = 50;
}
// Parameterized constructor
public Chocolate(int barCode, String name, double weight, double cost) {
[Link] = barCode;
[Link] = name;
[Link] = weight;
[Link] = cost;
}
// Getter methods
public int getBarCode() {
return barCode;
}
public String getName() {
return name;
}
public double getWeight() {
return weight;
}
public double getCost() {
return cost;
}
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

// Setter methods
public void setBarCode(int barCode) {
[Link] = barCode;
}
public void setName(String name) {
[Link] = name;
}
public void setWeight(double weight) {
[Link] = weight;
}
public void setCost(double cost) {
[Link] = cost;
}
}
public class ChocolateTester {
public static void main(String[] args) {
// Create an object of chocolate using default constructor
Chocolate chocolate1 = new Chocolate();

// Display default values using getter methods


[Link]("Default Values:");
[Link]("Bar Code: " + [Link]());
[Link]("Name: " + [Link]());
[Link]("Weight: " + [Link]() + "g");
[Link]("Cost: $" + [Link]());
// Modify values using setter methods
[Link](1002);
[Link]("Hershey's");
[Link](30);
[Link](95);
// Display modified values using getter methods
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

[Link]("\nModified Values:");
[Link]("Bar Code: " + [Link]());
[Link]("Name: " + [Link]());
[Link]("Weight: " + [Link]() + "g");
[Link]("Cost: $" + [Link]());
}
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Experiment No. 3

Objective:. A company wants to keep a record of the employees working in it. There are
permanent employees as well as contract employees. Contract employees work on an
hourly basis whereas permanent employees are paid monthly salary. The class diagrams
are as given below: Employee:

Employee
empId : int
name : String
salary : double
getSalary() : double
setSalary(salary:double) : void
getEmpId() : int
setEmpId(empId :int) : void
getName() : String
setName(name : String) : void

A record of the employee name, salary, and the employee Id has to be maintained for
each employee. PermanentEmployee:
PermanentEmployee
basicPay : double
hra : double
experience : int
getBasicPay() : double
setBasicPay(salary:double) : void
getHra() : double
setHra(empId :double) : void
getExperience() : int
setExperience(name : int) : void
calculateSalary() : void

Method Description:
calculateSalary():This method calculates the salary using the formula as given below:
Salary = variable component + Basic pay +HRA
The condition for calculating variable component is given below:
Experience (in years) % of Basic pay
<5 0
>= 5 and < 7 5
>= 7 and < 12 10

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

>= 12 15

ContractEmployee:

ContractEmployee
wages : double
hours : int
getWages(): double
setWages(wages: double): void
getHours(): int
setHours(hours: int): void
calculateSalary(): void

Method Description:
calculateSalary():This method calculates the salary using the formula as given below:
Salary = total hours * wages
Implementation Details:
Create a class EmployeeRecords and implement the main method: public class
EmployeeRecords {
Public static void main(String str[]){
{
}
}
Provide the following inputs:
Input (For PermanentEmployee):
Attributes Values
Name Abc
Employee Id 1001
Basic Pay 12500
HRA 3500
Experience 6
Output: Permanent Employee: Your Salary is : XXXX
Input (For ContractEmployee):
Attributes Values
Name Xyz
Employee Id 7001
Wages 750
Hours 15
Output: Contract Employee: Your Salary is : XXXX
Note:- You call setter and getter method of salary of Employee class using an instance of
both Permanent as well as Contract Employee. The getter and setter method of instance

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

variable in parent class can be reused by child classes as it is inherited from parent and
hence need not be created again.

Program:

class Employee {
// Member variables
private String name;
private int employeeId;
private double salary;
// Constructor
public Employee(String name, int employeeId) {
[Link] = name;
[Link] = employeeId;
}
// Getter and setter methods
public double getSalary() {
return salary;
}

public void setSalary(double salary) {


[Link] = salary;
}
}
class PermanentEmployee extends Employee {
// Additional member variables for permanent employees
private double basicPay;
private double HRA;
private int experience;
// Constructor
public PermanentEmployee(String name, int employeeId, double basicPay, double
HRA, int experience) {
super(name, employeeId);
[Link] = basicPay;
[Link] = HRA;
[Link] = experience;
}
// Method to calculate salary for permanent employees
public void calculateSalary() {
double variableComponent;
if (experience < 5)
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

variableComponent = 0;
else if (experience < 7)
variableComponent = 0.05 * basicPay;
else if (experience < 12)
variableComponent = 0.10 * basicPay;
else
variableComponent = 0.15 * basicPay;

double salary = variableComponent + basicPay + HRA;


setSalary(salary);
}
}

class ContractEmployee extends Employee {


// Additional member variables for contract employees
private double wages;
private int hours;

// Constructor
public ContractEmployee(String name, int employeeId, double wages, int hours) {
super(name, employeeId);
[Link] = wages;
[Link] = hours;
}
// Method to calculate salary for contract employees
public void calculateSalary() {
double salary = wages * hours;
setSalary(salary);
}
}
public class EmployeeRecords {
public static void main(String[] args) {
// Creating a PermanentEmployee object and calculating salary
PermanentEmployee permanentEmployee = new PermanentEmployee("Abc",
1001, 12500, 3500, 6);
[Link]();
[Link]("Permanent Employee: Your Salary is: $" +
[Link]());
// Creating a ContractEmployee object and calculating salary
ContractEmployee contractEmployee = new ContractEmployee("Xyz", 7001,
750, 15);
[Link]();
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

[Link]("Contract Employee: Your Salary is: $" +


[Link]());
}
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Experiment No. 4
Objective:. The Provider as interface, provides an efficient way for students to calculate their
overall percentage of all the courses. The total Maximum Marks for all courses is 8000. Intern
studied in Institute A, where each semester comprises of 1000 marks, in which 900 marks are for
courses and 100 marks are kept for co-curricular activities (grace Marks). Whereas Trainee
studied in Institute B where each semester comprises of 1000 marks for courses.

Provider (interface)
+ totalMaximumMarks: int
+ calcPercentage(): void

Intern: This class for interns who completed their course in Institute A.
Intern (class)
- marksSecured: int
- graceMarks: int
+ Intern(marksSecured:int, graceMarks: int)
+ calcPercentage(): void

Method Description: calcPercentage(): This method will calculate the total marks of the intern
which is the sum of grace marks and the marks secured by the intern, and hence
calculate the percentage on the totalMaximumMarks.
Trainee: This class is for trainees who completed their course in Institute B.

Trainee (class)
- marksSecured: int
+ Trainee(marksSecured: int)
+calcPercentage(): void

Method Description: calcPercentage(): calculates the overall percentage of the marks of the
trainee.

Attribute Values
Output: The total aggregate Marks Secure 4500 percentage secured is [Link] Input
(For Trainee): Grace Marks 400

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Attributes Values
Marks Secured 5500

Program:
> [Link]
public class Employee { private String empName; private int empAge; private double empSalary;

public Employee(String empName, int empAge, double empSalary) {


[Link] = empName;
[Link] = empAge; [Link] = empSalary;
}

// Getters and setters


public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {


[Link] = empName;
}

public int getEmpAge() {


return empAge;
}

public void setEmpAge(int empAge) {


[Link] = empAge;
}

public double getEmpSalary() {

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

return empSalary;
}

public void setEmpSalary(double empSalary) {


[Link] = empSalary;
}
}

>[Link]

public class EmpSalaryException extends Exception {


public EmpSalaryException(String message) {
super(message);
}
}

> [Link]
public class Service {
public static void checkEmployeeSalary(Employee emp) throws EmpSalaryException {
if ([Link]() < 1000) {
throw new EmpSalaryException("Salary is less than 1000 for employee:
" + [Link]());
}
}

public static void main(String[] args) {


Employee emp1 = new Employee("Alice", 30, 1500);
Employee emp2 = new Employee("Bob", 25, 900);
Employee emp3 = new Employee("Charlie", 28, 1200);
Employee emp4 = new Employee("David", 22, 800);
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Employee emp5 = new Employee("Eve", 35, 1100);


Employee[] employees = { emp1, emp2, emp3, emp4, emp5 };
for (Employee emp : employees) {
try {
checkEmployeeSalary(emp);
}
catch (EmpSalaryException e) {
[Link]([Link]());
}
}
}
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Experiment No. 6

Objective:. Create a Java program that adds Student objects into a HashSet. The Student
class has name, course and rollNumber as its attributes and a toString() method. If we add
two Student objects having the same rollNumber to the HashSet, it should be considered as
duplicate and should not get added.

Student (class)
- name: String
- course : String
- rollNumber : int
+ Student(name: String, course: String, rollNumber:int)
+ toString() : String
+ add() : boolean

Program:

import [Link]; import [Link];


class Student {
private String name; private String course; private int rollNumber;
public Student(String name, String course, int rollNumber) { [Link] = name;
[Link] = course; [Link] = rollNumber;
}

@Override
public String toString() { return "Student{" +
"name='" + name + '\'' +
", course='" + course + '\'' +
", rollNumber=" + rollNumber + '}';
}

@Override
public boolean equals(Object o) { if (this == o) return true;
if (o == null || getClass() != [Link]()) return false; Student student = (Student) o;
return rollNumber == [Link];

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

@Override
public int hashCode() {
return [Link](rollNumber);
}
}

public class Main {


public static void main(String[] args) {
HashSet<Student> studentHashSet = new HashSet<>();

Student student1 = new Student("Alice", "Math", 101); Student student2 = new Student("Bob",
"Science", 102);
Student student3 = new Student("Charlie", "Math", 101); // Duplicate rollNumber

// Adding students to the HashSet

[Link]("Adding student1: " + [Link](student1)); // Should print true


[Link]("Adding student2: " + [Link](student2)); // Should print true
[Link]("Adding student3: " + [Link](student3)); // Should print false
(duplicate rollNumber)

// Printing the HashSet


for (Student student : studentHashSet) {
[Link](student);
}
}
}

public class Employee { private String empName; private int empAge; private double empSalary;

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

public Employee(String empName, int empAge, double empSalary) {


[Link] = empName;
[Link] = empAge; [Link] = empSalary;
}

// Getters and setters


public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {


[Link] = empName;
}

public int getEmpAge() {


return empAge;
}

public void setEmpAge(int empAge) {


[Link] = empAge;
}

public double getEmpSalary() { return empSalary;


}

public void setEmpSalary(double empSalary) { [Link] = empSalary;


}
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Experiment No. 7

Objective:. Write a Java program that creates a “XYZBank” saving account with
concurrent deposits and withdrawals using threads.

The XYZBank class represents a bank saving account with a balance. For deposit() and
withdrawal() methods, different threads can execute them concurrently without conflict.

In the deposit() method, the lock is acquired before updating the balance with the
deposited amount. The lock is acquired in the withdraw() method before checking the
balance and completing the withdrawal. If withdraw amount is greater than balance
amount then show insufficient balance message.
The main method creates an instance of XYZBank and starts four threads: two for
deposits and two for withdrawals. Each thread invokes the corresponding method on the
BankAccount instance, simulating concurrent deposits and withdrawals.

Program:

import [Link];
import [Link];

class XYZBank {
private double balance;
private final Lock lock = new ReentrantLock();

public XYZBank(double initialBalance) {


[Link] = initialBalance;
}

public void deposit(double amount) {


[Link]();
try {
if (amount > 0) {
balance += amount;
[Link]([Link]().getName() + " deposited " + amount
+ ". New balance: " + balance);
}
} finally {
[Link]();
}
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

public void withdraw(double amount) {


[Link]();
try {
if (amount > 0) {
if (balance >= amount) {
balance -= amount;
[Link]([Link]().getName() + " withdrew " +
amount + ". New balance: " + balance);
} else {
[Link]([Link]().getName() + " attempted to
withdraw " + amount + ". Insufficient balance: " + balance);
}
}
} finally {
[Link]();
}
}
}

public class BankAccountSimulator {


public static void main(String[] args) {
XYZBank account = new XYZBank(1000.00);

Runnable depositTask = () -> {


for (int i = 0; i < 5; i++) {
[Link](100);
try {
[Link](100); // Simulate time taken for deposit
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
};

Runnable withdrawTask = () -> {


for (int i = 0; i < 5; i++) {
[Link](50);
try {
[Link](100); // Simulate time taken for withdrawal
} catch (InterruptedException e) {
[Link]().interrupt();
}
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

}
};

Thread depositThread1 = new Thread(depositTask, "DepositThread1");


Thread depositThread2 = new Thread(depositTask, "DepositThread2");
Thread withdrawThread1 = new Thread(withdrawTask, "WithdrawThread1");
Thread withdrawThread2 = new Thread(withdrawTask, "WithdrawThread2");

[Link]();
[Link]();
[Link]();
[Link]();

try {
[Link]();
[Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]().interrupt();
}

[Link]("Final balance: " + [Link]);


}
}

Experiment No. 8
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Objective:. Write a code using lambda expressions to display the name of all
the employees and their [Link] the following Employee class:

class Employee {
public int id;
public String
name; private int
salary;
private double yearsInOrg;
private String role;
private String gender;

public Employee(int id, String name, int salary, double years, String role, String
gender) { [Link] = id;
[Link] = name;
[Link] = salary;
[Link] = years;
[Link] = role;
[Link] = gender;
}
// Getters and setters
}
class LambdaExercise {
public static void main(String[] args) {
Employee e1 = new Employee(1069001, "John", 100000, 1.0, "Manager", "M");
Employee e2 = new Employee(1069002, "Mike", 50000, 1.7, "Systems Engineer",
"M"); Employee e3 = new Employee(1069003, "Harvey", 75000, 6.9, "Manager",
"M"); Employee e4 = new Employee(1069004, "Jessica", 25000, 3.1, "Trainee",
"F");
Employee e5 = new Employee(1069005, "Rachel", 53000, 2.0, "Support", "F");
ArrayList<Employee> employeeArr = new
ArrayList<>(); [Link](e1);
[Link](e2);
[Link](e3);
[Link](e4);
[Link](e5);
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

// Write your code here


}

Program:

### Part 1: Using Lambda Expressions to Display Employee Names and Genders

Let's start with the first part of your request, which involves using lambda expressions to
display the names and genders of employees from a list. The `Employee` class will have
getters for the `name` and `gender` properties, and we'll utilize lambda expressions to
print these details.

Here's how you can achieve this:

1. **Modify the `Employee` class to include getters:**


```java
import [Link];
import [Link];

class Employee {
public int id;
public String name;
private int salary;
private double yearsInOrg;
private String role;
private String gender;

public Employee(int id, String name, int salary, double years, String role, String
gender) {
[Link] = id;
[Link] = name;
[Link] = salary;
[Link] = years;
[Link] = role;
[Link] = gender;
}

public String getName() {


return name;
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

public String getGender() {


return gender;
}
}

public class LambdaExercise {


public static void main(String[] args) {
Employee e1 = new Employee(1069001, "John", 100000, 1.0, "Manager", "M");
Employee e2 = new Employee(1069002, "Mike", 50000, 1.7, "Systems
Engineer", "M");
Employee e3 = new Employee(1069003, "Harvey", 75000, 6.9, "Manager", "M");
Employee e4 = new Employee(1069004, "Jessica", 25000, 3.1, "Trainee", "F");
Employee e5 = new Employee(1069005, "Rachel", 53000, 2.0, "Support", "F");

List<Employee> employeeArr = new ArrayList<>();


[Link](e1);
[Link](e2);
[Link](e3);
[Link](e4);
[Link](e5);

// Using lambda expressions to display the name and gender of each employee
[Link](e -> [Link]("Name: " + [Link]() + ",
Gender: " + [Link]()));
}
}
```

### Part 2: Creating a Spring Application for a Student Model

For the second part, let's create a Spring application to display the details of a `Student`
on the console. This involves creating a `Student` class, a Spring XML configuration file,
and a main application class to load the context and display the student details.

1. **Define the `Student` class:**


```java
public class Student {
private String name;
private String course;
private int rollNumber;

public Student(String name, String course, int rollNumber) {


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

[Link] = name;
[Link] = course;
[Link] = rollNumber;
}

public String getName() {


return name;
}

public String getCourse() {


return course;
}

public int getRollNumber() {


return rollNumber;
}

@Override
public String toString() {
return "Student{name='" + name + "', course='" + course + "', rollNumber=" +
rollNumber + "}";
}
}
```

2. **Create the Spring XML configuration file (`[Link]`):**


```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]

<bean id="student" class="[Link]">


<constructor-arg value="Alice"/>
<constructor-arg value="Computer Science"/>
<constructor-arg value="101"/>
</bean>

</beans>
```

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

3. **Create the main application class to load the context and display the student
details:**
```java
import [Link];
import [Link];

public class StudentApp {


public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("[Link]");

Student student = (Student) [Link]("student");


[Link](student);
}
}
```

To run this Spring application:


1. Ensure your project has the Spring framework dependencies.
2. Place the `[Link]` file in the classpath (e.g., in the `src/main/resources` directory).
3. Run the `StudentApp` class to see the student details printed on the console.

By following these steps, you can display the names and genders of employees using
lambda expressions and create a Spring application to display student details on the
console.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Experiment No. 9

Objective:. Create an application to display the details of the Student on the console. A
Model class “Student” has the below properties.

Student (class)
- name: String
- course : String
- rollNumber : int
+ Student(name: String, course: String, rollNumber:int)

Create a spring xml configuration file to create a bean entry for the Movie object with
some sample property values.
Program:
### Step 1: Define the `Student` Class

```java
public class Student {
private String name;
private String course;
private int rollNumber;

public Student(String name, String course, int rollNumber) {


[Link] = name;
[Link] = course;
[Link] = rollNumber;
}

// Getters
public String getName() {
return name;
}

public String getCourse() {


return course;
}

public int getRollNumber() {


return rollNumber;
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

@Override
public String toString() {
return "Student{name='" + name + "', course='" + course + "', rollNumber=" + rollNumber +
"}";
}
}
```

### Step 2: Define the `Movie` Class

```java
public class Movie {
private String title;
private String genre;
private int duration; // duration in minutes

public Movie(String title, String genre, int duration) {


[Link] = title;
[Link] = genre;
[Link] = duration;
}

// Getters
public String getTitle() {
return title;
}

public String getGenre() {


return genre;
}

public int getDuration() {


return duration;
}

@Override
public String toString() {
return "Movie{title='" + title + "', genre='" + genre + "', duration=" + duration + " minutes}";
}
}
```

### Step 3: Create the Spring XML Configuration File (`[Link]`)

```xml
<?xml version="1.0" encoding="UTF-8"?>
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]

<!-- Bean for Student -->


<bean id="student" class="[Link]">
<constructor-arg value="Alice"/>
<constructor-arg value="Computer Science"/>
<constructor-arg value="101"/>
</bean>

<!-- Bean for Movie -->


<bean id="movie" class="[Link]">
<constructor-arg value="Inception"/>
<constructor-arg value="Science Fiction"/>
<constructor-arg value="148"/>
</bean>

</beans>
```

### Step 4: Create the Main Application Class to Load the Context and Display the Details

```java
import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("[Link]");

// Fetch and display the Student bean


Student student = (Student) [Link]("student");
[Link](student);

// Fetch and display the Movie bean


Movie movie = (Movie) [Link]("movie");
[Link](movie);
}
}
```

### Running the Application

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

1. Ensure your project includes Spring framework dependencies. For example, if you are using
Maven, include the following dependencies in your `[Link]`:

```xml
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.10</version>
</dependency>
</dependencies>
```

2. Place the `[Link]` file in the classpath, typically in the `src/main/resources` directory.

3. Run the `MainApp` class to see the student and movie details printed on the console.

### Output Example

```
Student{name='Alice', course='Computer Science', rollNumber=101}
Movie{title='Inception', genre='Science Fiction', duration=148 minutes}
```

This setup creates a Spring application that loads the context from an XML configuration file,
instantiates `Student` and `Movie` beans with sample values, and prints their details on the
console.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Experiment No. 10
Objective:. According to question 9, use annotations for the configuration, instead of the
xml. Also, add the init method, destroy method. Implement these methods with the logic
to show the current system date and time.

Program:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link]; import [Link];

@Component

public class Student {


private String name;
private String course;
private int rollNumber;

@Autowired

public Student(@Value("${[Link]}")
String name, @Value("${[Link]}")
String course, @Value("${[Link]}")
int rollNumber()
{
[Link] = name;
[Link] = course;
[Link] = rollNumber;
}
}

@PostConstruct
public void init() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd
HH:mm:ss"); String currentDateAndTime = [Link](new Date());
[Link]("Initialization method called. Current system date and time: " +
currentDateAndTime);

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

@PreDestroy

public void destroy() {

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


String currentDateAndTime = [Link](new Date());
[Link]("Destruction method called. Current system date and time: " +
currentDateAndTime);

// Getters and setters public String getName() {


return name;

public void setName(String name) {


[Link] = name;
}

public String getCourse() { return


course;
}

public void setCourse(String course)


{[Link] = course;
}

public int getRollNumber() { return


rollNumber;
}

public void setRollNumber(int rollNumber) {


[Link] = rollNumber;
}
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Experiment No. 11

Objective:. Create a Spring Boot Application based on the below requirement:

E. The application should support two RestFull URLs.


F. The first Restfull URL should display the student name as a String.
G. The second restfull URL should display the address of the student as String.
H. We would also be interested to see the list of all the default beans that
were created by SpringBoot automatically in the console.
Test the application by executing and viewing the console to see the list of beans and also
test both the URLs to verify that they return and display data as expected.

Programs:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@SpringBootApplication

public class StudentApplication {

public static void main(String[] args) {

ApplicationContext context = [Link]([Link],


args);

// List all default beans

String[] beanNames =
[Link](); for
(String beanName : beanNames) {
[Link](beanName);

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

@RestController

class StudentController {

@Autowired
private Student student;

@Autowired
private Address address;

@GetMapping("/
student/name") public
String
getStudentName() {
return "Student Name: " + [Link]();

}
@GetMapping("/
student/address")
public String
getStudentAddress() {
return "Student Address: " + [Link]();

}
}

class Student {
private String name;
public String getName() { return name;
}

public void setName(String name) { [Link] = name;


}
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

class Address {
private String address;
public String getAddress() {
return address;
}

public void setAddress(String address) {


[Link] = address;
}
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Experiment No. 12

Objective:. Amit wants to start a payment service portal for making payments for the credit
card bill and online shopping. He will need a base class (MyPaymentServices) to store balance
and customer ID information. He will use two classes- CreditCardPayment and
ShoppingPayment for paying Credit card bills and shopping bills respectively. The bill
payment and id generation is different for both payment modes.

Class Description:
MyPaymentServices: This is the base class for CreditCardPayment and ShoppingPayment
classes. It will store the amount to be paid by the user in the instance variable balance of the
class.

MyPaymentService
-balance:double
-customerId:int
+MyPaymentService(balance:double, customerId:int)
+setBalance(balance:double):void
+getBalance():doublie
+getCustomerId():int
+payBill(amount:double):void

Method Description:
payBill(double amount): This is an abstract method that has to be implemented by the child
classes of MyPaymentServices.

ShoppingPayment:
This class is a child class of MyPaymentServices. It has a static variable counter, to set the
paymentID. The class diagram is shown below:

ShoppingPayment
- static counter: int
- pymentId:String
+ ShoppingPayment(balance:double, customerId:int)
+ getPaymentId(): String
+ payBill(amount: double): void

Method Description:
payBill(double amount): For a shopping bill payment, the payment id should start with 'S'

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

followed by a four digit integer number. If the user enters an amount not equal to the balance
which is due, an appropriate error message should be displayed and the id should get generated
only for valid payments.
CreditCardPayment:
This class is another child class of MyPaymentServices. It has a static variable counter,
to generate the paymentID. The class diagram is shown below:

CreditCardPayment
- static conter:int
- paymentId:String
- cashBack: double
- balanceDue: double
+ CreditCardPayment(balance:double, customerId:int)
+ getPaymentId(): String
+ getCashBack(): double
+ getBalanceDue(): double
+ payBill(amount:double):void

Method Description:
payBill(double amount): For credit card bill payment, if a user enters an amount more than the
amount to be paid, the excess amount should be stored as cashBack. The payBill method is used
to pay the bill and generate
the transaction id. The id should start with 'C' followed by a four-digit integer number. In case
the user enters an amount less than the amount to be paid, then the remaining amount should be
stored in the instance variable balanceDue of class CreditCardPayment.
 Use a Tester class to test your code and display the payment information.
 The balanceDue after the payment should be communicated to the user.

Some outputs with different inputs are given below for your reference. Input1 (For credit card)

Attributes Values
Balance 10000.56
Customer Id 5001
Paid Amount 15000.00

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Output
Congratulations: You have successfully made a payment
of Rs. 15000 .Payment details are:-
Customer Id: 5001
Payment Id: 1001
Previous Due:
10000.56
Remaining Due: 0
Cash Back Wallet Balance: 4999.44

Input2 (For credit card)

Attributes Values
Balance 10000.56
Customer Id 5001
Paid Amount 0

Output
Congratulations: You have successfully made a
payment of Rs. 0.0 .Payment details are:-
Customer Id: 5001
Payment Id: C1002
Previous Due: 10000.56
Remaining Due: 10000.56
Cash Back Wallet
Balance : 0.0

Input3 (For Shopping)

Attributes Values
Balance 10000.56
Customer Id 5001
Paid Amount 5000

Output:

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Congratulations: You have successfully made a


payment of Rs. 5000.0 .Payment details are:-
Customer Id: 5001
Payment Id: C1001
PreviousDue: 10000.56
Remaining Due: 5000.56

Input 4(For Shopping)

Attributes Values
Balance 5000.56
Customer Id 561328
Paid Amount 5000.00

 Output
Congratulations: You have successfully made a payment of Rs. 0.0 with Payment Id: s1001

Program:

public abstract class MyPaymentServices { private double balance;


private int customerId;

public MyPaymentServices(double balance, int customerId) {


[Link] = balance; [Link] = customerId;
}

public void setBalance(double balance) { [Link] = balance;


}

public double getBalance() { return balance;


}

public int getCustomerId() { return customerId;


}

public abstract void payBill(double amount);


}

public class ShoppingPayment extends MyPaymentServices {


private static int counter = 1000; private String paymentId;

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

public ShoppingPayment(double balance, int customerId) {


super(balance, customerId); counter++;
paymentId = "S" + counter;
}

public String getPaymentId() { return paymentId;


}

@Override
public void payBill(double amount) { if (amount != getBalance()) {
[Link]("Error: Amount should be equal to the balance.");
return;
}
[Link]("Congratulations: You have successfully made a
payment of Rs. " + amount + ". Payment details are:-");
[Link]("Customer Id: " + getCustomerId());
[Link]("Payment Id: " + getPaymentId());
[Link]("Previous Due: " + getBalance());
setBalance(0); [Link]("Remaining Due: " + getBalance());
}
}

public class CreditCardPayment extends MyPaymentServices {


private static int counter = 1000; private String paymentId; private double
cashBack; private double balanceDue;

public CreditCardPayment(double balance, int customerId) {


super(balance, customerId); counter++;
paymentId = "C" + counter;
}

public String getPaymentId() { return paymentId;


}

public double getCashBack() { return cashBack;


}

public double getBalanceDue() { return balanceDue;


}

@Override
public void payBill(double amount) { if (amount > getBalance()) {

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

cashBack = amount - getBalance(); amount = getBalance();


} else if (amount < getBalance()) { balanceDue = getBalance() -
amount;
}

[Link]("Congratulations: You have successfully made a


payment of Rs. " + amount + ". Payment details are:-");
[Link]("Customer Id: " + getCustomerId());
[Link]("Payment Id: " + getPaymentId());
[Link]("Previous Due: " + getBalance());
setBalance(balanceDue);
[Link]("Remaining Due: " + getBalance());
[Link]("Cash Back Wallet Balance: " + getCashBack());
}
}

public class PaymentTester {


public static void main(String[] args) {
// Testing Credit Card Payment [Link]("Credit Card
Payment:");
CreditCardPayment creditCardPayment = new CreditCardPayment(10000.56,
5001);
[Link](15000.00);
[Link]();

CreditCardPayment creditCardPayment2 = new CreditCardPayment(10000.56,


5001);
[Link](0);
[Link]();

// Testing Shopping Payment [Link]("Shopping Payment:");


ShoppingPayment shoppingPayment = new ShoppingPayment(10000.56,
5001);
[Link](5000);
[Link]();

ShoppingPayment shoppingPayment2 = new ShoppingPayment(5000.56,


561328);
[Link](5000);
}
}

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452

You might also like