0% found this document useful (0 votes)
32 views87 pages

Object Oriented Programming Lab Manual

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 87

BUDGE BUDGE INSTITUTE OF TECHNOLOGY

Affiliated to MAKAUT(formerly WBUT)& Approved by AICTE, NAAC Accredited


Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

DEPARTMENT
OF
COMPUTER SCIENCE & ENGINEERING

LAB MANUAL
DETAILS OF THE COURSE
COURSE
COURSE TITLE OBJECT ORIENTED PROGRAMMING LAB PCC CS 593
CODE

DEPARTMENT COMPUTER SCIENCE AND ENGINEERING

SEMESTER 5TH

YEAR 3RD

COURSE TYPE CORE COURSE ELECTIVE COURSE


COURSE
2
CREDIT
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Course Contents

SL NO. Topics PAGE NO.

1 Vision and Mission of the Department 3


2 Lab Course Details 4
3 Program Outcomes (PO’s) 5
4 Program Specific Outcomes (PSO’s) 7
5 Program Educational Objectives (PEO’s) 8
6 Lab Course Outcomes (CO’s) 9
7 Mapping of CO’s with PO’s and PSO’s 9
8 Do’s and Don’ts of Laboratory 10
9 List of Experiments 11

10 Hardware and Software Specification for the Laboratory 14


11 Assessment Method for University Lab Examination 15
Annexure
A Lab Experiments Conducted

2|Page
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Vision of the Department

To impart quality technical education amongst the individuals, emphasizing on the needs of
industry and to contribute to the society.

Mission of the Department

M1: To prepare Computer Science & Engineering students with competence in basic science &
engineering.
M2: To make the students have a good command on software and hardware development so that
they can succeed in industry or pursue higher studies or become an entrepreneur.
M3: To inculcate the concept of corporate social responsibility among the student community

3|Page
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Details of the Course

COURSE NAME OBJECT ORIENTED PROGRAMMING LAB

PAPER CODE PCC CS 593

CONTACT HOURS 4 HOURS/WEEK

CREDITS 2

Pre-requisite

1 Understanding of fundamental programming concepts.

2. Familiarity with control structures (loops, conditionals), data types, and basic syntax.

3 Exposure to writing and debugging simple programs.

4 Familiarity with using an integrated development environment (IDE) or a text editor for
writing code.

4|Page
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Program Outcomes (PO’s)

PROGRAM PROGRAM OUTCOME DETAILS


OUTCOME
Engineering knowledge: Apply the knowledge of Mathematics, Science,
Engineering fundamentals, and an engineering specialization to the solution
PO1
of complex engineering problems..
Problem analysis: Identify, formulate, research literature, and analyze
complex engineering problems reaching substantiated conclusions using first
PO2
principles of mathematics, natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified
PO3 needs with appropriate consideration for the public health and safety, and the
cultural, societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based
knowledge and research methods including design of experiments, analysis
PO4
and interpretation of data, and synthesis of the information to provide valid
conclusions.
Modern tool usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and
PO5 modeling to complex engineering activities with an understanding of the
limitations.
The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
PO6
consequent responsibilities relevant to the professional engineering practice.
Environment and sustainability: Understand the impact of the professional

PO7 engineering solutions in societal and environmental contexts, and demonstrate

5|Page
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

PROGRAM PROGRAM OUTCOME DETAILS


OUTCOME
the knowledge of, and need for sustainable development
Ethics: Apply ethical principles and commit to professional ethics and

PO8 responsibilities and norms of the engineering practice.

Individual and team work: Function effectively as an individual, and as a

PO9 member or leader in diverse teams, and in multidisciplinary settings.

Communication: Communicate effectively on complex engineering activities


with the engineering community and with society at large, such as, being able
PO10 to comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions.
Project management and finance: Demonstrate knowledge and
understanding of the engineering and management principles and apply these
PO11
to one’s own work, as a member and leader in a team, to manage projects and
in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and
PO12 ability to engage in independent and life-long learning in the broadest context
of technological change.

6|Page
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Program Specific Outcomes (PSO’s)

PSO PROGRAM SPECIFIC OUTCOMES DETAILS


Graduates should have strong foundations in Basic Sciences, Mathematics, Computer
PSO1 Science, and allied engineering to become software professionals to satisfy the needs
of IT Companies, research academia, and society.
Graduates should be able to identify, plan, design, analyze, and evolve project-
PSO2 implementing proficiencies and develop novel product solutions and simulations for
real-life problems in Computer Science and Engineering and the IT industry.
Initiative to adopt innovative computing technologies lifelong to acquire professional

PSO3 greatness and develop Graduates as computing professionals who can conduct
research and lead, design, develop, or maintain projects in various areas of Computer
science and engineering.

PSO4 Graduates must possess professional, ethical, and social responsibilities,


communicational skills, and teamwork needed for a prosperous professional career.

7|Page
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Program Educational Objectives (PEO’s)

PEO PROGRAM EDUCATIONAL OBJECTIVES

Knowledge of Basic Engineering Science and Technical Skills:


PEO1 To provide Students with good breadth of knowledge in mathematical, scientific,
computing and basic engineering fundamentals necessary to formulate, analyze and
solve hardware/software engineering problems.

PEO2 Engineering Design Skills:


To equip Students with the capability of problem solving skills required for the
general practice of engineering design.

PEO3 Preparation for Further/Higher Studies:


Students will have the ability to pursue advanced studies and research in their
chosen fields.

PEO4 Preparation for Profession:


Students will have the ability of working in teams with professional ethics, soft
skills and required domain knowledge.

8|Page
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Course Outcomes (CO’s)

Course Outcomes (CO’s)


Course DESCRIPTION Blooms’
Outcome The student will be able to- Taxonomy Level
PCC-CS593.1 Understand the methodologies involved in class, constructor, Understand, Apply
overloading, inheritance, overriding
PCC-CS593.2 Gain knowledge about wrapper class, arrays Understand, Apply
PCC-CS593.3 Developing interfaces multiple inheritance, extending interfaces Apply, Analyze
PCC-CS593.4 Creating and accessing packages Create

PCC-CS593.5 Assignments on multithreaded programming Evaluate, Create

PCC-CS593.6 Learn applet programming Apply, Analyze

Mapping of Course Outcomes with Program Outcomes and Program specific Outcomes

Mapping of CO with PO and PSO


COs' PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3 PSO4

PCC-CS593.1 2 2 1 1 1 1 2 2 1 1 1 3 3

PCC-CS593.2 1 1 2 1 1 1 1 3 2 1 2 2 3

PCC-CS593.3 3 2 2 2 1 1 1 2 2 2 1 1 3 2

PCC-CS593.4 3 1 2 2 2 1 1 2 2 2 1 2 3 3

PCC-CS593.5 2 2 3 2 3 1 2 1 2 3 3 1 3

PCC-CS593.6 1 2 1 3 1 2 3 1 2 2 3 1 1
Average 2.00 1.67 2.00 2.00 1.67 1.00 1.20 1.50 2.00 1.83 1.75 1.50 1.80 2.50 2.50 1.00

9|Page
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Do’s and Dont’s

DO’S

 Without Prior permission do not enter into the Laboratory.


 While entering into the LAB students should wear their I-cards.
 The Students should come with proper uniform.
 Students should come with observation and record note book to the laboratory.
 Students should maintain silence inside the laboratory.
 After completing the laboratory exercise, make sure to shutdown the system properly.

DONT’S

 Students bringing the bags inside the laboratory.


 Students wearing slippers/shoes insides laboratory.
 Students using the computers in an improper way.
 Students scribbling on the desk and mishandling chairs.
 Students using mobile phones inside the laboratory.
 Students making noise inside the laboratory.

10 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment List

Sl. Course Blooms


Topic of the Assignment
No. Outcome Taxonomy
Write a program in Java for addition of any two whole
1. PCC-CS593.1 Apply
numbers.

Write a program in Java to find out if a number is Prime or


2. PCC-CS593.1 Apply
not.

Write a program in Java of creation of an object and using


3. PCC-CS593.1 Apply
that object to display the values.

Write a program in Java of basic method overloading using


4. different objects and display the values for every object PCC-CS593.1 Apply
accordingly.

Write a program in Java of basic Banking Process of deposit


5. and withdrawal and display by creating a single object and PCC-CS593.1 Analyze
using it accordingly.

Write a program in Java to show constructor overloading


6. PCC-CS593.1 Apply
with the help of four different object creations.

Write a program in Java where constructor overloading and


7. method overloading will perform with the help of four PCC-CS593.1 Apply
different objects.

Write a program in Java of polymorphism where


concatenation of two different strings and two float numbers
8. PCC-CS593.1 Apply
where concatenation and addition both will perform in a
single program.

Write a program in Java of polymorphism to calculate area


9. PCC-CS593.1 Apply
of different shapes like Square, Rectangle, Triangle and

11 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
Circle with the help of four different object creations.

Write a program in Java to show constructor overloading


10. and method overloading with the help of Inheritance by PCC-CS593.1 Analyze
Creating three different subclasses.

Write a program in Java to show method overloading with


11. the help of Inheritance by Creating three different PCC-CS593.1 Analyze
subclasses.

Write a program in Java of basic example of Inheritance


12. PCC-CS593.3 Apply
using interface.

Write a program in Java of multiple Inheritance using


13. PCC-CS593.3 Apply
interface-1.

Write a program in Java of multiple Inheritance using


14. PCC-CS593.3 Apply
interface-2.

Write a program in Java to show example of multilevel


15. PCC-CS593.3 Apply
inheritance.

Write a program in Java of basic two number additions


16. through user input using command line arguments using PCC-CS593.2 Apply
wrapper class.

Write a program in Java that demonstrates how command


17. PCC-CS593.1 Analyze
line arguments are received as strings in Java.

Write a program in Java to test system define exceptions


18. PCC-CS593.1 Apply
through different category user inputs.

Write a program in Java to exceptions of user’s choice


19. PCC-CS593.1 Apply
depending on user input logic.

Write a program in Java for several types of system defined


20. PCC-CS593.1 Apply
exceptions.

12 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
Write a program in Java for different types of user defined
21. PCC-CS593.1 Apply
exceptions.

Write a program in Java to show exceptions of user’s choice


22. PCC-CS593.1 Apply
depending on user input logic

Create an abstract class to calculate employee details,


23. leveraging inheritance properties. Then, create two objects PCC-CS593.3 Analyze
for different child classes.

Write a program in Java for Banking transactions where


24. deposit, withdrawal, display and search of an account have PCC-CS593.1 Create
to show according to the choice of the user.

Write a program in Java that demonstrates thread


25. functionality for getting the thread name and priority. Use PCC-CS593.5 Analyze
try-catch logic in your implementation.

Write a program in Java of your own thread which will


26. PCC-CS553.5 Apply
follow the thread life cycle

Write a program in Java that extends thread using package


27. PCC-CS593.4 Analyze
which contains thread class

Write a program in Java to control main thread by


28. PCC-CS593.5 Analyze
changing its name.

Write a program in Java to create threads using two


29. PCC-CS593.5 Apply
processes which will run simultaneously using sleep timer.

Write a program in Java to create threads by setting child


30. PCC-CS593.5 Apply
thread and using all thread with time interval.

Write a program in Java to create threads by making child


31. PCC-CS593.5 Apply
thread and use all threads by their name and their priorities.

Create a basic Java applet that demonstrates interactivity


32. PCC-CS593.6 Create
and dynamic behavior within a web page.

13 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Hardware and Software Specification for the Laboratory

Hardware Requirements:

Processor : A minimum of Pentium 2 with a clock speed


of 266 MHz or higher.
RAM : 1 GB
Hard Disk : Approximately 124 MB for the Java Runtime
Environment (JRE) and 2 MB for Java updates.

Software Requirements
1. Java Development Kit (JDK): You’ll need JDK installed on your system. The
recommended version is Java 8 (JDK 1.8).

2. Software installed: Microsoft Office Integrated Development Environment


(IDE): Choose an IDE for writing and compiling Java code. Some popular
options include:

o Eclipse: A widely used IDE for Java development.

o IntelliJ IDEA: Another powerful IDE with excellent Java support.

o NetBeans: A free and open-source IDE for Java development.

3. Text Editor: If you prefer not to use an IDE, you can write Java code in a
simple text editor (e.g., Notepad++) and compile it using the command line.

4. Compiler: Java code needs to be compiled into bytecode. The JDK includes the
necessary compiler (javac).

14 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assessment methods of University Lab Examination

PRACTICAL ASSESSMENT

Internal Assessment 40 Marks

Practical Assessment 60 Marks

Total 100 Marks

Internal Assessment (40 Marks)

Attendance 10 Marks

Lab Performance 20 Marks

Lab Report 10 Marks

External Assessment (60 Marks)

Viva Voice 20 Marks

Experiment and Result 40 Marks

15 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

ANNEXURE

16 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment-01

 Write a program in Java for addition of any two whole numbers.

import java.util.Scanner;

public class AddTwoNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input two whole numbers


System.out.print("Enter the first whole number: ");
int num1 = scanner.nextInt();

System.out.print("Enter the second whole number: ");


int num2 = scanner.nextInt();

// Calculate the sum


int sum = num1 + num2;

// Display the result


System.out.println("Sum of " + num1 + " and " + num2 + " is " + sum);

// Close the scanner


scanner.close();
}
}

To run this program:


1. Save the code to a file named AddTwoNumbers.java.
2. Open a terminal or command prompt.
3. Compile the program using javac AddTwoNumbers.java.
4. Run the compiled program using java AddTwoNumbers

OUTPUT:

Enter the first whole number: 10


Enter the second whole number: 20
Sum of 10 and 20 is 30

17 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 02

 Write a program in Java to find out if a number is Prime or not.

import java.util.Scanner;

public class PrimeNumberChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a positive integer: ");


int number = scanner.nextInt();

boolean isPrime = checkPrime(number);

if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}

scanner.close();
}

// Function to check if a number is prime


public static boolean checkPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}

18 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

To run this program:


1. Save the code to a file named PrimeNumberChecker.java.
2. Open a terminal or command prompt.
3. Compile the program using javac PrimeNumberChecker.java.
4. Run the compiled program using java PrimeNumberChecker.

OUTPUT:
Enter a positive integer: 17
17 is a prime number.

19 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 03

 Write a program in Java of creation of an object and using that object to display the
values.

public class Student {


// Instance variables
String name;
int age;

// Constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
}

// Display method
public void displayInfo() {
System.out.println("Student Name: " + name);
System.out.println("Student Age: " + age);
}

public static void main(String[] args) {


// Create an object of the Student class
Student student1 = new Student("John Doe", 20);

// Display the student's information


student1.displayInfo();
}
}

In this program:
 We define a Student class with instance variables (name and age).
 The constructor initializes the object with the provided name and age.
 The displayInfo() method prints the student’s name and age.
 In the main method, we create an object (student1) and call the displayInfo() method to
show the values.

20 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

OUTPUT:

Student Name: John Doe


Student Age: 20

21 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 04

Write a program in Java of basic method overloading using different objects and display
the values for every object accordingly.

public class Calculator {


// Method to add two integers
public int add(int a, int b) {
return a + b;
}

// Method to add two doubles


public double add(double a, double b) {
return a + b;
}

// Method to concatenate two strings


public String add(String str1, String str2) {
return str1 + str2;
}

public static void main(String[] args) {


Calculator calculator = new Calculator();

// Example 1: Adding integers


int sumInt = calculator.add(5, 3);
System.out.println("Sum of integers: " + sumInt);

// Example 2: Adding doubles


double sumDouble = calculator.add(2.5, 3.7);
System.out.println("Sum of doubles: " + sumDouble);

// Example 3: Concatenating strings


String resultStr = calculator.add("Hello, ", "world!");
System.out.println("Concatenated string: " + resultStr);
}
}

In this program:
 We have three overloaded add methods with different parameter types.
 The program demonstrates how to use each method based on the argument types.

22 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

OUTPUT:
Sum of integers: 8
Sum of doubles: 6.2
Concatenated string: Hello, world!

23 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 05

Write a program in Java of basic method overloading using different objects and display
the values for every object accordingly.

import java.util.Scanner;

class BankAccount {
private String accountHolder;
private double balance;

// Constructor to initialize account details


public BankAccount(String accountHolder, double initialBalance) {
this.accountHolder = accountHolder;
this.balance = initialBalance;
}

// Method to deposit funds


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposit successful. New balance: $" + balance);
} else {
System.out.println("Invalid deposit amount. Please enter a positive value.");
}
}

// Method to withdraw funds


public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;

System.out.println("Withdrawal successful. New balance: $" + balance);


} else {
System.out.println("Insufficient funds or invalid withdrawal amount.");
}
}

// Method to display account details


public void displayAccountInfo() {
24 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
System.out.println("Account Holder: " + accountHolder);
System.out.println("Current Balance: $" + balance);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter account holder's name: ");


String name = scanner.nextLine();

System.out.print("Enter initial balance: $");


double initialBalance = scanner.nextDouble();

BankAccount account = new BankAccount(name, initialBalance);

// Perform deposit and withdrawal


account.deposit(100); // Example deposit
account.withdraw(50); // Example withdrawal

// Display account information


account.displayAccountInfo();

scanner.close();
}
}

In this program:
 We define a BankAccount class with private instance variables
(accountHolder and balance).
 The constructor initializes the account details.
 The deposit method allows adding funds to the account.

 The withdraw method allows withdrawing funds (if sufficient balance).


 The displayAccountInfo method shows the account holder’s name and current balance.
 In the main method, we create an account object, perform deposit and withdrawal
operations, and display account information.

25 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

OUTPUT:
Enter account holder's name: Alice Johnson
Enter initial balance: $500
Deposit successful. New balance: $600
Withdrawal successful. New balance: $550
Account Holder: Alice Johnson
Current Balance: $550

26 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 06

Write a program in Java to show constructor overloading with the help of four different
object creations.

class Employee {
private int empId;
private String empName;
private double salary;

// Constructor with no parameters (default constructor)


public Employee() {
empId = 0;
empName = "Unknown";
salary = 0.0;
}

// Constructor with one parameter (employee ID)


public Employee(int id) {
empId = id;
empName = "Guest";
salary = 0.0;
}

// Constructor with two parameters (employee ID and name)


public Employee(int id, String name) {
empId = id;
empName = name;

salary = 0.0;
}

// Constructor with three parameters (employee ID, name, and salary)


public Employee(int id, String name, double sal) {
empId = id;
empName = name;
salary = sal;
}

// Display employee details


public void displayInfo() {
27 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
System.out.println("Employee ID: " + empId);
System.out.println("Employee Name: " + empName);
System.out.println("Salary: $" + salary);
System.out.println();
}

public static void main(String[] args) {


// Create four different employee objects using different constructors
Employee emp1 = new Employee();
Employee emp2 = new Employee(101);
Employee emp3 = new Employee(102, "Alice");
Employee emp4 = new Employee(103, "Bob", 50000.0);

// Display employee information


emp1.displayInfo();
emp2.displayInfo();
emp3.displayInfo();
emp4.displayInfo();
}
}

In this program:
 We define an Employee class with overloaded constructors.
 Each constructor initializes different combinations of employee details (ID, name, and
salary).
 In the main method, we create four different employee objects using different
constructors and display their information.
OUTPUT:

Employee ID: 0
Employee Name: Unknown
Salary: $0.0
Employee ID: 101
Employee Name: Guest
Salary: $0.0

Employee ID: 102


Employee Name: Alice
Salary: $0.0
Employee ID: 103
Employee Name: Bob
Salary: $50000.0
28 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 07

Write a program in Java where constructor overloading and method overloading will
perform with the help of four different objects.

class MathOperations {
// Constructor with no parameters (default constructor)
public MathOperations() {
// No initialization needed for default constructor
}

// Constructor with one parameter (integer)


public MathOperations(int num) {
// Initialize with the provided integer
}

// Constructor with two parameters (double and string)


public MathOperations(double num, String operation) {
// Perform the specified operation on the double value
}

// Method to add two integers


public int add(int a, int b) {

return a + b;
}

// Method to add two doubles


public double add(double a, double b) {
return a + b;
}

// Method to concatenate two strings


public String add(String str1, String str2) {
return str1 + str2;
}

public static void main(String[] args) {


// Create four different MathOperations objects
MathOperations math1 = new MathOperations();
MathOperations math2 = new MathOperations(42);
29 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
MathOperations math3 = new MathOperations(3.14, "add");
MathOperations math4 = new MathOperations(5.0, "multiply");

// Perform operations and display results


System.out.println("Sum of 10 and 20: " + math1.add(10, 20));
System.out.println("Sum of 2.5 and 3.7: " + math2.add(2.5, 3.7));
System.out.println("Concatenated strings: " + math3.add("Hello, ", "world!"));
// Additional operations can be performed using math4 object
}
}

In this program:
 We define a MathOperations class with overloaded constructors and
overloaded add methods.
 Each constructor initializes different combinations of parameters (integers, doubles, and
strings).
 The add methods perform addition or string concatenation based on the argument types.
 In the main method, we create four different MathOperations objects and demonstrate
their usage.

OUTPUT:

Sum of 10 and 20: 30


Sum of 2.5 and 3.7: 6.2
Concatenated strings: Hello, world!

30 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 08

Write a program in Java of polymorphism where concatenation of two different strings


and two float numbers where concatenation and addition both will perform in a single
program.

public class PolymorphismDemo {


// Method to concatenate two strings
public String performOperation(String str1, String str2) {
return str1 + str2;
}

// Method to add two float numbers


public float performOperation(float num1, float num2) {
return num1 + num2;
}

public static void main(String[] args) {


PolymorphismDemo demo = new PolymorphismDemo();

// Concatenate two strings


String resultStr = demo.performOperation("Hello, ", "world!");
System.out.println("Concatenated string: " + resultStr);

// Add two float numbers


float resultFloat = demo.performOperation(3.14f, 2.5f);
System.out.println("Sum of float numbers: " + resultFloat);
}
}

In this program:
 We define a PolymorphismDemo class with two overloaded methods: one for string
concatenation and another for float addition.
 The performOperation method is overloaded based on the argument types.
 In the main method, we demonstrate both operations using the same method name.

OUTPUT:
Concatenated string: Hello, world!
Sum of float numbers: 5.64

31 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 09

Write a program in Java of polymorphism to calculate area of different shapes like Square,
Rectangle, Triangle and Circle with the help of four different object creations.

// Shape interface (or base class)


interface Shape {
double calculateArea();
}

// Square class
class Square implements Shape {
private double side;

public Square(double side) {


this.side = side;
}

@Override
public double calculateArea() {
return side * side;
}
}

// Rectangle class
class Rectangle implements Shape {
private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;

this.width = width;
}

@Override
public double calculateArea() {
return length * width;
}
}

// Triangle class
32 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
class Triangle implements Shape {
private double base;
private double height;

public Triangle(double base, double height) {


this.base = base;
this.height = height;
}

@Override
public double calculateArea() {
return 0.5 * base * height;
}
}

// Circle class
class Circle implements Shape {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

public class AreaCalculator {


public static void main(String[] args) {
// Create different shape objects

Shape square = new Square(5.0);


Shape rectangle = new Rectangle(4.0, 6.0);
Shape triangle = new Triangle(3.0, 4.0);
Shape circle = new Circle(2.5);

// Calculate and display areas


System.out.println("Area of square: " + square.calculateArea());
System.out.println("Area of rectangle: " + rectangle.calculateArea());
System.out.println("Area of triangle: " + triangle.calculateArea());
System.out.println("Area of circle: " + circle.calculateArea());
33 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
}
}

In this program:
 We define an interface called Shape with a single method calculateArea().
 Each shape class (Square, Rectangle, Triangle, and Circle) implements
the Shape interface and provides its own implementation of the calculateArea() method.
 In the main method, we create different shape objects and calculate their respective areas.

OUTPUT:
Area of square: 25.0
Area of rectangle: 24.0
Area of triangle: 6.0
Area of circle: 19.634954084936208

34 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 10

Write a program in Java to show constructor overloading and method overloading with the
help of Inheritance by creating three different subclasses.

// Base class (parent class)


class Vehicle {
String type;

// Constructor with one parameter


public Vehicle(String type) {
this.type = type;
}

// Method overloading: Different versions of the same method


public void displayInfo() {
System.out.println("Type of vehicle: " + type);
}
}

// Subclass Car
class Car extends Vehicle {
String brand;

// Constructor with two parameters (overloaded constructor)


public Car(String type, String brand) {
super(type); // Call the parent class constructor
this.brand = brand;
}

// Method overloading: Another version of displayInfo()


@Override
public void displayInfo() {
System.out.println("Car type: " + type);
System.out.println("Car brand: " + brand);
}
}

// Subclass Bike
class Bike extends Vehicle {
int wheels;
35 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

// Constructor with three parameters (overloaded constructor)


public Bike(String type, int wheels) {
super(type); // Call the parent class constructor
this.wheels = wheels;
}

// Method overloading: Another version of displayInfo()


@Override
public void displayInfo() {
System.out.println("Bike type: " + type);
System.out.println("Number of wheels: " + wheels);
}
}

// Subclass Truck
class Truck extends Vehicle {
double loadCapacity;

// Constructor with four parameters (overloaded constructor)


public Truck(String type, double loadCapacity) {
super(type); // Call the parent class constructor
this.loadCapacity = loadCapacity;
}

// Method overloading: Another version of displayInfo()


@Override
public void displayInfo() {
System.out.println("Truck type: " + type);
System.out.println("Load capacity (in tons): " + loadCapacity);
}
}

public class Main {


public static void main(String[] args) {
// Create instances of each subclass
Car myCar = new Car("Sedan", "Toyota");
Bike myBike = new Bike("Mountain Bike", 2);
Truck myTruck = new Truck("Heavy Duty", 10.5);

// Demonstrate method overloading


myCar.displayInfo();
36 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
myBike.displayInfo();
myTruck.displayInfo();
}
}

In this program:
 We have a base class Vehicle with a constructor and a method.
 The subclasses Car, Bike, and Truck inherit from Vehicle.
 Each subclass has its own constructors (overloaded) and overrides
the displayInfo() method.

OUTPUT:
Car type: Sedan
Car brand: Toyota
Bike type: Mountain Bike
Number of wheels: 2
Truck type: Heavy Duty
Load capacity (in tons): 10.5

37 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 11

 Write a program in Java to show method overloading with the help of Inheritance
by creating three different subclasses.

// Base class (parent class)


class Animal {
String species;

// Constructor with one parameter


public Animal(String species) {
this.species = species;
}

// Method overloading: Different versions of the same method


public void makeSound() {
System.out.println("Animal makes an unspecified sound.");
}
}

// Subclass Dog
class Dog extends Animal {
String breed;

// Constructor with two parameters (overloaded constructor)


public Dog(String species, String breed) {
super(species); // Call the parent class constructor
this.breed = breed;
}

// Method overloading: Another version of makeSound()


@Override
public void makeSound() {

System.out.println("Dog barks!");
}
}

// Subclass Cat
class Cat extends Animal {
boolean isLazy;
38 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

// Constructor with three parameters (overloaded constructor)


public Cat(String species, boolean isLazy) {
super(species); // Call the parent class constructor
this.isLazy = isLazy;
}

// Method overloading: Another version of makeSound()


@Override
public void makeSound() {
System.out.println("Cat meows!");
}
}

// Subclass Bird
class Bird extends Animal {
String color;

// Constructor with four parameters (overloaded constructor)


public Bird(String species, String color) {
super(species); // Call the parent class constructor
this.color = color;
}

// Method overloading: Another version of makeSound()


@Override
public void makeSound() {
System.out.println("Bird chirps!");
}
}

public class Main {


public static void main(String[] args) {
// Create instances of each subclass
Dog myDog = new Dog("Canine", "Golden Retriever");

Cat myCat = new Cat("Feline", true);

Bird myBird = new Bird("Avian", "Blue");

// Demonstrate method overloading


myDog.makeSound();
myCat.makeSound();
39 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
myBird.makeSound();
}
}

In this program:
 We have a base class Animal with a constructor and a method.
 The subclasses Dog, Cat, and Bird inherit from Animal.
 Each subclass has its own constructors (overloaded) and overrides
the makeSound() method

OUTPUT:

Dog barks!
Cat meows!
Bird chirps!

40 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 12

 Write a program in Java of basic example of Inheritance using interface.

// Define the Shape interface


interface Shape {
double calculateArea();
}

// Circle class implementing the Shape interface


class Circle implements Shape {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

// Rectangle class implementing the Shape interface


class Rectangle implements Shape {
private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
public double calculateArea() {
return length * width;
}
}

public class Main {


public static void main(String[] args) {
// Create instances of Circle and Rectangle
41 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Circle circle = new Circle(5.0);


Rectangle rectangle = new Rectangle(4.0, 6.0);

// Calculate and display areas


System.out.println("Area of the circle: " + circle.calculateArea());
System.out.println("Area of the rectangle: " + rectangle.calculateArea());
}
}

In this program:
 We define the Shape interface with a single method calculateArea().
 The Circle class implements the Shape interface and provides its own implementation
of calculateArea().
 The Rectangle class also implements the Shape interface with its own implementation
of calculateArea().

OUTPUT:

Area of the circle: 78.53981633974483


Area of the rectangle: 24.0

42 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 13

 Write a program in Java of multiple Inheritance using interface-1.

// Define the Drawable interface


interface Drawable {
void draw();
}

// Define the Resizable interface


interface Resizable {
void resize(double factor);
}

// Rectangle class implementing both interfaces


class Rectangle implements Drawable, Resizable {
private double width;
private double height;

public Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

@Override
public void draw() {
System.out.println("Drawing a rectangle with width " + width + " and height " + height);
}

@Override
public void resize(double factor) {
width *= factor;
height *= factor;
System.out.println("Resized rectangle: new width = " + width + ", new height = " + height);
}
}

public class Main {


public static void main(String[] args) {
// Create a Rectangle object
Rectangle myRectangle = new Rectangle(5.0, 3.0);

43 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
// Draw the rectangle
myRectangle.draw();

// Resize the rectangle


myRectangle.resize(1.5);
}
}

In this program:
 We define two interfaces: Drawable and Resizable.
 The Rectangle class implements both interfaces.
 The draw() method from the Drawable interface is used to draw the rectangle.
 The resize(double factor) method from the Resizable interface is used to resize the
rectangle.

OUTPUT:
Drawing a rectangle with width 5.0 and height 3.0
Resized rectangle: new width = 7.5, new height = 4.5

44 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 14

Write a program in Java of multiple Inheritance using interface-2.

// Define the Drawable interface


interface Drawable {
void draw();
}

// Define the Resizable interface


interface Resizable {
void resize(double factor);
}

// Rectangle class implementing both interfaces


class Rectangle implements Drawable, Resizable {
private double width;
private double height;

public Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

@Override
public void draw() {
System.out.println("Drawing a rectangle with width " + width + " and height " + height);
}

@Override
public void resize(double factor) {
width *= factor;
height *= factor;
System.out.println("Resized rectangle: new width = " + width + ", new height = " + height);
}
}

public class Main {


public static void main(String[] args) {
// Create a Rectangle object
Rectangle myRectangle = new Rectangle(5.0, 3.0);
45 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

// Draw the rectangle


myRectangle.draw();

// Resize the rectangle


myRectangle.resize(1.5);
}
}

In this program:
 We define two interfaces: Drawable and Resizable.
 The Rectangle class implements both interfaces.
 The draw() method from the Drawable interface is used to draw the rectangle.
 The resize(double factor) method from the Resizable interface is used to resize the
rectangle.

OUTPUT:

Drawing a rectangle with width 5.0 and height 3.0


Resized rectangle: new width = 7.5, new height = 4.5

46 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment-15

 Write a program in Java to show example of multilevel inheritance.

// Base class (parent class)


class Animal {
void eat() {
System.out.println("Animal is eating.");
}
}

// Intermediate class (inherits from Animal)


class Mammal extends Animal {
void run() {
System.out.println("Mammal is running.");
}
}

// Derived class (inherits from Mammal)


class Dog extends Mammal {
void bark() {
System.out.println("Dog is barking.");
}
}

public class Main {


public static void main(String[] args) {
// Create a Dog object
Dog myDog = new Dog();

// Demonstrate multilevel inheritance


myDog.eat(); // Inherited from Animal
myDog.run(); // Inherited from Mammal
myDog.bark(); // Specific to Dog
}
}

47 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

In this program:
 Animal is the base class with an eat() method.
 Mammal inherits from Animal and adds a run() method.
 Dog inherits from Mammal and adds a bark() method.

OUTPUT:
Animal is eating.
Mammal is running.
Dog is barking.

48 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 16

Write a program in Java of basic two number additions through user input using
command line arguments using wrapper class.

public class AddTwoNumbers {


public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java AddTwoNumbers <number1> <number2>");
return;
}

try {
// Parse command line arguments as doubles
double num1 = Double.parseDouble(args[0]);
double num2 = Double.parseDouble(args[1]);

// Perform addition
double sum = num1 + num2;

// Display the result


System.out.println("Sum of " + num1 + " and " + num2 + " is " + sum);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please provide valid numeric values.");
}
}
}

To run this program:


1. Open a terminal or command prompt.
2. Compile the program using javac AddTwoNumbers.java.
3. Run it with two numeric arguments, e.g., java AddTwoNumbers 5.5 3.2.

OUTPUT:

Sum of 5.5 and 3.2 is 8.7

49 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 17

 Write a program in Java that demonstrates how command line arguments are
received as strings in Java.

public class CommandLineArgumentsDemo {


public static void main(String[] args) {
// Check if any command line arguments are provided
if (args.length == 0) {
System.out.println("No command line arguments provided.");
} else {
System.out.println("Command line arguments:");
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i + 1) + ": " + args[i]);
}
}
}
}

To run this program,

Open a terminal or command prompt, navigate to the directory containing the


compiled .class file, and execute the following command:

java CommandLineArgumentsDemo arg1 arg2 arg3

Replace arg1, arg2, and arg3 with any values you’d like. The program will display the
provided command line arguments.

For example, if you run:

java CommandLineArgumentsDemo apple banana cherry

OUTPUT:

Command line arguments:


Argument 1: apple
Argument 2: banana
Argument 3: cherry

50 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 18

 Write a program in Java to test system define exceptions through different category
user inputs.

import java.util.Scanner;

public class ExceptionHandlingDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
// Example 1: Handling NumberFormatException
System.out.print("Enter an integer: ");
String userInput = scanner.nextLine();
int number = Integer.parseInt(userInput);
System.out.println("You entered: " + number);

// Example 2: Handling ArithmeticException


System.out.print("Enter a divisor (non-zero): ");
int divisor = scanner.nextInt();
int result = 10 / divisor;
System.out.println("Result of division: " + result);

// Example 3: Handling ArrayIndexOutOfBoundsException


int[] numbers = { 1, 2, 3 };
System.out.print("Enter an index (0 to 2): ");
int index = scanner.nextInt();
System.out.println("Value at index " + index + ": " + numbers[index]);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid integer.");
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index out of bounds. Valid indices are 0 to 2.");
} finally {
scanner.close();
}
}
}

51 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

In this program:

 We use a Scanner to read user input.


 We handle exceptions using try, catch, and finally blocks.
 The program demonstrates handling NumberFormatException (when parsing an
integer), ArithmeticException (division by zero),
and ArrayIndexOutOfBoundsException (invalid array index).

52 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 19

 Write a program in Java to exceptions of user’s choice depending on user input


logic.

import java.util.Scanner;

// Custom exception class for division by zero


class DivisionByZeroException extends Exception {
public DivisionByZeroException(String message) {
super(message);
}
}

public class ExceptionHandlingExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter a dividend: ");
int dividend = scanner.nextInt();

System.out.print("Enter a divisor: ");


int divisor = scanner.nextInt();

if (divisor == 0) {
throw new DivisionByZeroException("Division by zero is not allowed.");
}

int result = dividend / divisor;


System.out.println("Result of division: " + result);
} catch (DivisionByZeroException e) {
System.err.println("Error: " + e.getMessage());
} catch (Exception e) {
System.err.println("An error occurred: " + e.getMessage());
} finally {
scanner.close();
}
}
}

53 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

In this program:

 We create a custom exception class DivisionByZeroException.


 The user inputs a dividend and a divisor.
 If the divisor is zero, we throw a DivisionByZeroException.
 Otherwise, we calculate the result of division and display it.

OUTPUT:
Enter a dividend: 10
Enter a divisor: 2
Result of division: 5

54 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 20
Write a program in Java for several types of system defined exceptions.

public class ExceptionDemo {


public static void main(String[] args) {
try {
// Example 1: ArithmeticException (division by zero)
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " + e.getMessage());
}

try {
// Example 2: ArrayIndexOutOfBoundsException
int[] arr = new int[5];
int value = arr[10];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: " + e.getMessage());
}

try {
// Example 3: NullPointerException
String str = null;
int length = str.length();
} catch (NullPointerException e) {
System.out.println("NullPointerException caught: " + e.getMessage());
}

55 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

try {
// Example 4: NumberFormatException
String invalidNumber = "abc";
int parsedNumber = Integer.parseInt(invalidNumber);
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught: " + e.getMessage());
}
}
}

In this program:
We intentionally cause exceptions to occur and handle them using try-catch blocks.
The output shows the exception messages associated with each type of exception.

OUTPUT:
ArithmeticException caught: / by zero
ArrayIndexOutOfBoundsException caught: Index 10 out of bounds for length 5
NullPointerException caught: null
NumberFormatException caught: For input string: "abc"

56 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 21
 Write a program in Java for different types of user defined exceptions.

// Custom exception class for invalid age


class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

// Custom exception class for insufficient balance


class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}

class BankAccount {
private double balance;

public BankAccount(double initialBalance) {


this.balance = initialBalance;
}

public void withdraw(double amount) throws InsufficientBalanceException {


if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance to withdraw $" +
amount);
57 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

}
balance -= amount;
}
}

public class CustomExceptionDemo {


public static void main(String[] args) {
try {
// Example 1: Creating a bank account
BankAccount account = new BankAccount(1000);

// Example 2: Withdraw an amount


double withdrawalAmount = 1500;
account.withdraw(withdrawalAmount);
System.out.println("Withdrawal successful!");
} catch (InsufficientBalanceException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Explanation:
 We’ve defined two custom exception
classes: InvalidAgeException and InsufficientBalanceException.
 The BankAccount class has a withdraw method that throws
an InsufficientBalanceException if the withdrawal amount exceeds the account balance.
 In the main method, we create a bank account with an initial balance of $1000 and
attempt to withdraw $1500.
 Since the balance is insufficient, an InsufficientBalanceException is thrown and caught.

58 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

OUTPUT:
Error: Insufficient balance to withdraw $1500.0
Explanation:
 In the main method, we create a BankAccount object with an initial balance of $1000.
 We attempt to withdraw an amount of $1500 using the withdraw method.
 Since the account balance is insufficient for this withdrawal,
an InsufficientBalanceException is thrown.
 The catch block catches the exception and prints the error message: “Insufficient balance
to withdraw $1500.0”.

59 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 22
 Write a program in Java to show exceptions of user’s choice depending on user
input logic.

import java.util.Scanner;

public class UserChoiceExceptionDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Choose an exception type:");


System.out.println("1. NullPointerException");
System.out.println("2. ArrayIndexOutOfBoundsException");
System.out.println("3. CustomException (InvalidInputException)");

int choice = scanner.nextInt();


scanner.nextLine(); // Consume newline

try {
switch (choice) {
case 1:
// Example 1: NullPointerException
String str = null;
int length = str.length();
break;
case 2:
// Example 2: ArrayIndexOutOfBoundsException
int[] arr = new int[5];
60 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
int value = arr[10];
break;
case 3:
// Example 3: CustomException (InvalidInputException)
throw new InvalidInputException("Custom exception: Invalid input
provided.");
default:
System.out.println("Invalid choice. Please select 1, 2, or 3.");
}
} catch (NullPointerException e) {
System.out.println("NullPointerException caught: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: " +
e.getMessage());
} catch (InvalidInputException e) {
System.out.println("CustomException caught: " + e.getMessage());
}

scanner.close();
}
}

// Custom exception class for invalid input


class InvalidInputException extends Exception {
public InvalidInputException(String message) {
super(message);
}
}

61 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

OUTPUT:
Choose an exception type:
1. NullPointerException
2. ArrayIndexOutOfBoundsException
3. CustomException (InvalidInputException)
2
ArrayIndexOutOfBoundsException caught: Index 10 out of bounds for length 5

Explanation:
 The user selects option 2, which corresponds to the ArrayIndexOutOfBoundsException.
 The program attempts to access an array element that is out of bounds (index 10 in an
array of length 5).
 The exception is caught, and the error message is displayed.

62 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 23
 Create an abstract class to calculate employee details, leveraging inheritance
properties. Then, create two objects for different child classes.

// Abstract class for Employee


abstract class Employee {
private String name;
private int employeeId;

public Employee(String name, int employeeId) {


this.name = name;
this.employeeId = employeeId;
}

// Abstract method to calculate salary (to be implemented by child classes)


public abstract double calculateSalary();

// Common method to display employee details


public void displayDetails() {
System.out.println("Employee ID: " + employeeId);
System.out.println("Name: " + name);
}
}

// Child class for FullTimeEmployee


class FullTimeEmployee extends Employee {
private double monthlySalary;
63 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

public FullTimeEmployee(String name, int employeeId, double monthlySalary) {


super(name, employeeId);
this.monthlySalary = monthlySalary;
}

@Override
public double calculateSalary() {
return monthlySalary;
}
}

// Child class for ContractEmployee


class ContractEmployee extends Employee {
private int contractDuration; // in months

public ContractEmployee(String name, int employeeId, int contractDuration) {


super(name, employeeId);
this.contractDuration = contractDuration;
}

@Override
public double calculateSalary() {
// Assume a fixed monthly payment for contract employees
return 2000 * contractDuration;
}
}

64 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
public class EmployeeDemo {
public static void main(String[] args) {
// Create a FullTimeEmployee object
FullTimeEmployee fullTimeEmp = new FullTimeEmployee("John Doe", 101,
5000);
fullTimeEmp.displayDetails();
System.out.println("Monthly Salary: $" + fullTimeEmp.calculateSalary());

System.out.println(); // Add a line break

// Create a ContractEmployee object


ContractEmployee contractEmp = new ContractEmployee("Jane Smith", 201, 6);
contractEmp.displayDetails();
System.out.println("Total Contract Payment: $" + contractEmp.calculateSalary());
}
}
OUTPUT:
Employee ID: 101
Name: John Doe
Monthly Salary: $5000.0

Employee ID: 201


Name: Jane Smith
Total Contract Payment: $12000.0
Explanation:
 We’ve defined an abstract class Employee with common properties
(name and employeeId) and an abstract method calculateSalary().
 Two child classes (FullTimeEmployee and ContractEmployee) inherit
from Employee and provide their own implementations of calculateSalary().
 In the main method, we create instances of both child classes and display their details.

65 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 24
 Write a program in Java for Banking transactions where deposit, withdrawal,
display and search of an account have to show according to the choice of the user.

import java.util.ArrayList;
import java.util.Scanner;

class BankAccount {
private int accountNumber;
private String accountHolder;
private double balance;

public BankAccount(int accountNumber, String accountHolder, double initialBalance) {


this.accountNumber = accountNumber;
this.accountHolder = accountHolder;
this.balance = initialBalance;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposit successful. New balance: $" + balance);
}

public void withdraw(double amount) {


if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawal successful. New balance: $" + balance);
} else {
66 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
System.out.println("Insufficient balance. Cannot withdraw.");
}
}

public void displayAccountDetails() {


System.out.println("Account Number: " + accountNumber);
System.out.println("Account Holder: " + accountHolder);
System.out.println("Balance: $" + balance);
}
}

public class BankingApp {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<BankAccount> accounts = new ArrayList<>();

// Create some initial accounts (for demonstration purposes)


accounts.add(new BankAccount(1001, "Alice", 5000));
accounts.add(new BankAccount(1002, "Bob", 3000));

while (true) {
System.out.println("\nBanking Transactions Menu:");
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Display Account Details");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();

67 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
switch (choice) {
case 1:
System.out.print("Enter account number: ");
int accNum = scanner.nextInt();
System.out.print("Enter deposit amount: $");
double depositAmount = scanner.nextDouble();
for (BankAccount acc : accounts) {
if (acc.getAccountNumber() == accNum) {
acc.deposit(depositAmount);
break;
}
}
break;
case 2:
System.out.print("Enter account number: ");
int accNum2 = scanner.nextInt();
System.out.print("Enter withdrawal amount: $");
double withdrawalAmount = scanner.nextDouble();
for (BankAccount acc : accounts) {
if (acc.getAccountNumber() == accNum2) {
acc.withdraw(withdrawalAmount);
break;
}
}
break;
case 3:
System.out.print("Enter account number: ");
int accNum3 = scanner.nextInt();
for (BankAccount acc : accounts) {
68 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
if (acc.getAccountNumber() == accNum3) {
acc.displayAccountDetails();
break;
}
}
break;
case 4:
System.out.println("Exiting the program. Thank you!");
scanner.close();
System.exit(0);
default:
System.out.println("Invalid choice. Please select 1, 2, 3, or 4.");
}
}
}
}

OUTPUT:
Banking Transactions Menu:
1. Deposit
2. Withdraw
3. Display Account Details
4. Exit
Enter your choice: 1
Enter account number: 1001
Enter deposit amount: $1000
Deposit successful. New balance: $6000.0

69 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Banking Transactions Menu:


1. Deposit
2. Withdraw
3. Display Account Details
4. Exit
Enter your choice: 3
Enter account number: 1002
Account Number: 1002
Account Holder: Bob
Balance: $3000.0

Banking Transactions Menu:


1. Deposit
2. Withdraw
3. Display Account Details
4. Exit
Enter your choice: 2
Enter account number: 1001
Enter withdrawal amount: $2000
Withdrawal successful. New balance: $4000.0

Banking Transactions Menu:


1. Deposit
2. Withdraw
3. Display Account Details
4. Exit
Enter your choice: 4
Exiting the program. Thank you!
70 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 25
 Write a program in Java that demonstrates thread functionality for getting the
thread name and priority. Use try-catch logic in your implementation.

public class ThreadDemo {


public static void main(String[] args) {
// Create a custom thread
Thread customThread = new Thread(() -> {
try {
// Simulate some work
Thread.sleep(2000);
System.out.println("Custom thread is running.");
} catch (InterruptedException e) {
System.out.println("Custom thread interrupted.");
}
});

// Set thread name and priority


customThread.setName("MyCustomThread");
customThread.setPriority(Thread.MAX_PRIORITY);

// Start the custom thread


customThread.start();

// Display thread details


System.out.println("Thread name: " + customThread.getName());
System.out.println("Thread priority: " + customThread.getPriority());
}
}
71 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

OUTPUT:
Thread name: MyCustomThread
Thread priority: 10
Custom thread is running.
Explanation:
 We create a custom thread using a lambda expression that simulates some work (sleeps
for 2 seconds).
 We set the thread name to “MyCustomThread” and the priority to the maximum value
(10).
 The thread starts executing, and we display its name and priority.
 The custom thread completes its work and prints “Custom thread is running.”

72 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 26
 Write a program in Java of your own thread which will follow the thread life cycle.

public class CustomThreadDemo {


public static void main(String[] args) {
// Create a custom thread
Thread customThread = new Thread(() -> {
System.out.println("Custom thread is running (State: NEW)");
try {
Thread.sleep(2000); // Simulate some work
System.out.println("Custom thread completed its work (State:
TERMINATED)");
} catch (InterruptedException e) {
System.out.println("Custom thread interrupted (State: INTERRUPTED)");
}
});

// Display initial thread state (NEW)


System.out.println("Thread state before starting: " + customThread.getState());

// Start the custom thread


customThread.start();

// Display thread state after starting (RUNNABLE)


System.out.println("Thread state after starting: " + customThread.getState());

// Wait for the custom thread to complete


try {
73 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
customThread.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted while waiting for custom thread.");
}

// Display final thread state (TERMINATED)


System.out.println("Thread state after completion: " + customThread.getState());
}
}

OUTPUT:
Thread state before starting: NEW
Custom thread is running (State: NEW)
Thread state after starting: RUNNABLE
Custom thread completed its work (State: TERMINATED)
Thread state after completion: TERMINATED

Explanation:
 We create a custom thread using a lambda expression.
 Initially, the thread is in the NEW state.
 After starting the thread, it transitions to the RUNNABLE state.
 The custom thread simulates some work (sleeps for 2 seconds) and then completes its
task.
 Finally, the thread enters the TERMINATED state.

74 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 27
 Write a program in Java that extends thread using package which contains thread
class.

// Custom thread class extending Thread


class MyCustomThread extends Thread {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread " + Thread.currentThread().getId() + ": " + i);
try {
Thread.sleep(1000); // Simulate some work
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
}

public class ThreadExtensionDemo {


public static void main(String[] args) {
// Create two custom threads
MyCustomThread thread1 = new MyCustomThread();
MyCustomThread thread2 = new MyCustomThread();

// Start the threads


thread1.start();
thread2.start();
}
}
75 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

OUTPUT:
Thread 11: 1
Thread 12: 1
Thread 11: 2
Thread 12: 2
Thread 11: 3
Thread 12: 3
Thread 11: 4
Thread 12: 4
Thread 11: 5
Thread 12: 5

Explanation:
 We create a custom thread class MyCustomThread by extending the Thread class.
 The run method is overridden to define the behavior of the custom thread.
 In the main method, we create two instances of MyCustomThread.
 Both threads start executing concurrently and print numbers from 1 to 5.

76 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment - 28
 Write a program in Java to control main thread by changing its name.

public class MainThreadNameDemo {


public static void main(String[] args) {
// Get the reference to the main thread
Thread mainThread = Thread.currentThread();

// Set a custom name for the main thread


mainThread.setName("MyMain");

// Display the updated thread name


System.out.println("Main thread name: " + mainThread.getName());

// Simulate some work (for demonstration purposes)


for (int i = 1; i <= 5; i++) {
System.out.println("Working in " + mainThread.getName() + ": Step " + i);
try {
Thread.sleep(1000); // Simulate some work
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
}
}
}

77 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

OUTPUT:
Main thread name: MyMain
Working in MyMain: Step 1
Working in MyMain: Step 2
Working in MyMain: Step 3
Working in MyMain: Step 4
Working in MyMain: Step 5

Explanation:
 We retrieve the reference to the main thread using Thread.currentThread().
 We set a custom name for the main thread using setName("MyMain").
 The program then simulates some work (printing steps) in the main thread.

Assignment – 29
 Write a program in Java to create threads using two processes which will run
simultaneously using sleep timer.

public class SimultaneousThreadsDemo {


public static void main(String[] args) {
// Create and start the first thread
Thread thread1 = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 1: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
System.out.println("Thread 1 interrupted.");
}
78 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
}
});

// Create and start the second thread


Thread thread2 = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 2: " + i);
try {
Thread.sleep(800); // Sleep for 800 milliseconds
} catch (InterruptedException e) {
System.out.println("Thread 2 interrupted.");
}
}
});

// Start both threads


thread1.start();
thread2.start();
}
}

79 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

OUTPUT:
Thread 1: 1
Thread 2: 1
Thread 2: 2
Thread 1: 2
Thread 2: 3
Thread 1: 3
Thread 2: 4
Thread 1: 4
Thread 2: 5
Thread 1: 5

Explanation:
 We create two threads (thread1 and thread2) using lambda expressions.
 Each thread prints numbers from 1 to 5 with a specified delay using Thread.sleep.
 The threads run simultaneously, and their output may be interleaved.

80 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 30
 Write a program in Java to create threads by setting child thread and using all
thread with time interval.

public class ThreadDemo {


public static void main(String[] args) {
// Create a child thread
Thread childThread = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Child Thread: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});

// Create an auxiliary thread


Thread auxiliaryThread = new Thread(() -> {
for (char c = 'A'; c <= 'E'; c++) {
System.out.println("Auxiliary Thread: " + c);
try {
Thread.sleep(1500); // Sleep for 1.5 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
81 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
});

// Start both threads


childThread.start();
auxiliaryThread.start();

// Main thread continues execution


for (int i = 1; i <= 3; i++) {
System.out.println("Main Thread: " + i);
try {
Thread.sleep(2000); // Sleep for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

OUTPUT:
The output will be a mix of numbers and letters printed by the three threads. The order of
execution may vary due to thread scheduling.

82 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 31
 Write a program in Java to create threads by making child thread and use all
threads by their name and their priorities.

public class ThreadPriorityDemo {


public static void main(String[] args) {
// Create a child thread
Thread childThread = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
System.out.println("Child Thread: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
childThread.setName("ChildThread");
childThread.setPriority(Thread.MIN_PRIORITY); // Set minimum priority

// Create an auxiliary thread


Thread auxiliaryThread = new Thread(() -> {
for (char c = 'A'; c <= 'E'; c++) {
System.out.println("Auxiliary Thread: " + c);
try {
Thread.sleep(1500); // Sleep for 1.5 seconds
} catch (InterruptedException e) {
e.printStackTrace();
83 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593
}
}
});
auxiliaryThread.setName("AuxiliaryThread");
auxiliaryThread.setPriority(Thread.NORM_PRIORITY); // Set normal priority

// Start both threads


childThread.start();
auxiliaryThread.start();

// Main thread continues execution


for (int i = 1; i <= 3; i++) {
System.out.println("Main Thread: " + i);
try {
Thread.sleep(2000); // Sleep for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

84 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

OUTPUT:
Auxiliary Thread: A
Main Thread: 1
Child Thread: 1
Child Thread: 2
Auxiliary Thread: B
Main Thread: 2
Child Thread: 3
Auxiliary Thread: C
Child Thread: 4
Main Thread: 3
Child Thread: 5
Auxiliary Thread: D
Auxiliary Thread: E

In this program:
 The child thread is named “ChildThread” and has the minimum priority.
 The auxiliary thread is named “AuxiliaryThread” and has the normal priority.
 The main thread continues execution alongside the child and auxiliary threads.

85 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

Assignment – 32
 Create a basic Java applet that demonstrates interactivity and dynamic behavior
within a web page.

Below is a straightforward Java applet named HelloWorld:

import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorld extends Applet {


public void paint(Graphics g) {
g.drawString("Hello, Applet World!", 50, 25);
}
}

To run this applet, follow these steps:

1. Create the Java Applet Code:


o Save the above code in a file named HelloWorld.java.

2. Compile the Applet Code:


o Open your terminal or command prompt.
o Navigate to the directory where HelloWorld.java is saved.
o Compile the code using the command: javac HelloWorld.java

86 | P a g e
BUDGE BUDGE INSTITUTE OF TECHNOLOGY
Affiliated to MAKAUT (formerly WBUT) & Approved by AICTE, NAAC Accredited
Kolkata - 700 137, West Bengal, India
Phone : 033 2482 0676 / 0670
http://www.bbit.edu.in

LABORATORY NAME-OBJECT ORIENTED PROGRAMMING LAB


COURSE CODE-PCC-CS593

3. Create an HTML Document:


o Create an HTML file (e.g., myapplet.html) with the following content:

<html>

<head>

<title>Hello Applet</title>

</head>

<body>

<applet code="HelloWorld.class" width="300" height="300"></applet>

</body>

</html>

4. Deploy the Applet:

o Place the compiled HelloWorld.class file in the same directory as myapplet.html.

o Open myapplet.html in a web browser with Java enabled.

o You should see the message “Hello, Applet World!” displayed on the screen.

Remember that the class name must be public because its object is created by the Java Plugin
software that resides in the browser. The HTML file (myapplet.html) specifies the applet’s
dimensions and references the compiled class file.

You can also run the applet using the appletviewer tool:

appletviewer HelloWorld.java

87 | P a g e

You might also like