Вы находитесь на странице: 1из 133

Department of Basic Engineering Sciences-1

LAB WORKBOOK
19CS1203 OBJECT ORIENTED PROGRAMMING

Team OOP
K L UNIVERSITY | OBJECT ORIENTED PROGRAMMING – 19CS1203
19CS1203 OBJECT ORIENTED PROGRAMMING

LABORATORY WORKBOOK

STUDENT
NAME
REG. NO
YEAR
SEMESTER
SECTION
FACULTY

1
19CS1203 OBJECT ORIENTED PROGRAMMING

Table of contents
Organization of the STUDENT LAB WORKBOOK ..................................................................................... 4
Lab 1: ....................................................................................................................................................... 7
Prerequisite: Java fundamentals- Operators, Conditions, loops and output statement ................... 7
Pre-Lab Task: ....................................................................................................................................... 7
In-Lab Task: ......................................................................................................................................... 9
Post-Lab Task: ................................................................................................................................... 15
Lab 2: ..................................................................................................................................................... 19
Pre-Lab Task: ..................................................................................................................................... 19
In-Lab Task: ....................................................................................................................................... 24
Post-Lab Task: ................................................................................................................................... 29
Lab 3: ..................................................................................................................................................... 33
Prerequisite: I/O through files and GUI ........................................................................................... 33
Pre-Lab Task: ..................................................................................................................................... 33
In-Lab Task: ....................................................................................................................................... 35
Post-Lab Task: ................................................................................................................................... 39
Lab 4: ..................................................................................................................................................... 41
Prerequisite: Constructors and Overloading, Chaining and this ....................................................... 41
Pre-Lab Task: ..................................................................................................................................... 41
In-Lab Task: ....................................................................................................................................... 45
Post-Lab Task: ................................................................................................................................... 50
Lab 5: ..................................................................................................................................................... 55
Prerequisite: Objects as data members, Menu driven programs - operations on array of objects . 55
Pre-Lab Task: ..................................................................................................................................... 55
In-Lab Task:........................................................................................................................................ 58
Post-Lab Task: .................................................................................................................................... 63
Lab 6: ..................................................................................................................................................... 68
Prerequisite: String, StringBuffer, StringTokenizer and Date ........................................................... 68
Pre-Lab Task: ..................................................................................................................................... 68
In-Lab Task: ....................................................................................................................................... 72
Post-Lab Task: ................................................................................................................................... 75
Lab 7 ...................................................................................................................................................... 77
Prerequisite: Inheritance, super keyword ........................................................................................ 91
Pre-Lab Task ...................................................................................................................................... 91
In -Lab Task: ...................................................................................................................................... 92

2
19CS1203 OBJECT ORIENTED PROGRAMMING

Post-Lab Task .................................................................................................................................... 95


Lab 08: ................................................................................................................................................... 77
Prerequisite:...................................................................................................................................... 77
Pre-Lab Task: ..................................................................................................................................... 77
In-Lab Task: ....................................................................................................................................... 79
Post-Lab Task: ................................................................................................................................... 88
Lab 09: ................................................................................................................................................... 98
Prerequisite:...................................................................................................................................... 98
Pre-Lab Task: ..................................................................................................................................... 98
In-Lab Task: ..................................................................................................................................... 100
Post-Lab Task: ................................................................................................................................. 103
Lab 10: ................................................................................................................................................. 107
Prerequisite: Exception Handling ................................................................................................... 107
Pre-Lab Task: ................................................................................................................................... 107
In-Lab Task: ..................................................................................................................................... 109
Post-Lab Task: ................................................................................................................................. 113
Lab 11 .................................................................................................................................................. 115
Prerequisite: Multithreading.......................................................................................................... 115
Pre-Lab Task: ................................................................................................................................... 115
In-Lab Task: ..................................................................................................................................... 118
Post-Lab Task: ................................................................................................................................. 122
Lab 12 .................................................................................................................................................. 124
Prerequisite: Collection Framework – List, Set and Map ............................................................... 124
Pre-Lab Task: ................................................................................................................................... 124
In-Lab Task: ..................................................................................................................................... 127
Post-Lab Task: ................................................................................................................................. 127

3
19CS1203 OBJECT ORIENTED PROGRAMMING

Organization of the STUDENT LAB WORKBOOK

The laboratory framework includes a creative element but shifts the time-intensive
aspects outside of the Two-Hour closed laboratory period. Within this structure, each
laboratory includes three parts: Prelab, In-lab, and Post-lab.
a. Pre-Lab
The Prelab exercise is a homework assignment that links the lecture with the
laboratory period - typically takes 2 hours to complete. The goal is to synthesize the
information they learn in lecture with material from their textbook to produce a
working piece of software. Prelab Students attending a two-hour closed laboratory
are expected to make a good-faith effort to complete the Prelab exercise before
coming to the lab. Their work need not be perfect, but their effort must be real
(roughly 80 percent correct).
b. In-Lab
The In-lab section takes place during the actual laboratory period. The First hour of
the laboratory period can be used to resolve any problems the students might have
experienced in completing the Prelab exercises. The intent is to give constructive
feedback so that students leave the lab with working Prelab software - a significant
accomplishment on their part. During the second hour, students complete the In-lab
exercise to reinforce the concepts learned in the Prelab. Students leave the lab having
received feedback on their Prelab and In-lab work.
c. Post-Lab
The last phase of each laboratory is a homework assignment that is done following the
laboratory period. In the Post-lab, students analyze the efficiency or utility of a given
system call. Each Post-lab exercise should take roughly 120 minutes to complete.

4
19CS1203 OBJECT ORIENTED PROGRAMMING

2019-20 EVEN SEMESTER LAB CONTINUOUS EVALUATION


Pre-Lab
In-Lab(30M) Viva
Sl (15M) Total Faculty
Date Experiment Name Logic Impleme Execution LOGIC EXECUTION RESULT ANALYS Voce
No (50M) Signature
(5M) ntation (5M) (10M) (10M) (5M) IS (5M) (5M)
(5M)

5
19CS1203 OBJECT ORIENTED PROGRAMMING

2019-20 EVEN SEMESTER LAB CONTINUOUS EVALUATION


Pre-Lab
In-Lab(30M) Viva
Sl (15M) Total Faculty
Date Experiment Name Logic Impleme Execution LOGIC EXECUTIO RESUL ANALYSI Voce
No (50M) Signature
(5M) ntation (5M) (10M) N (10M) T (5M) S (5M) (5M)
(5M)

10

11

12

6
19CS1203 OBJECT ORIENTED PROGRAMMING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


COURSE CODE: 19CS1203
OBJECT ORIENTED PROGRAMMING

Lab 1:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Java fundamentals- Operators, Conditions, loops and output


statement

Pre-Lab Task:

1. Write a Java Program to print the “Hello World” statement.

2. Write a Java program to compute the factorial of a number (assume hardcoded user
input) in main method

7
19CS1203 OBJECT ORIENTED PROGRAMMING

8
19CS1203 OBJECT ORIENTED PROGRAMMING

In-Lab Task:
1. Develop Java code with 2 methods in MyFirstClass a) factorial () b) isStrong()
Strong number is a special number whose sum of factorial of digits is equal to the
original number. For example: 145 is strong number. Since, 1! + 4! + 5! = 145. The
method expects an integer as argument and then returns true if the number is strong,
otherwise returns false.

9
19CS1203 OBJECT ORIENTED PROGRAMMING

10
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Rework of Q1, modularizing to a class level as follows:

11
19CS1203 OBJECT ORIENTED PROGRAMMING

12
19CS1203 OBJECT ORIENTED PROGRAMMING

3. Rework on Q3, modularizing to package level.

13
19CS1203 OBJECT ORIENTED PROGRAMMING

14
19CS1203 OBJECT ORIENTED PROGRAMMING

Post-Lab Task:
1. Modify MyIntegerMath class, such that it contains the following methods
1) countDigits() 2)isArmstrong().
countDigits() expects an integer as argument and returns the number of digits in it.
isArmstrong() expects an integer as argument and returns true if it is an Armstrong
number otherwise returns false.
A positive integer of n digits is called an Armstrong number of order n (order is
number of digits) if abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....

Draw the class diagrams:


a) modularized to class level
b) modularized to package level

15
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Develop java code for the above designs a) and b).

16
19CS1203 OBJECT ORIENTED PROGRAMMING

17
19CS1203 OBJECT ORIENTED PROGRAMMING

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation


Marks Secured: _______ out of ________

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

18
19CS1203 OBJECT ORIENTED PROGRAMMING

Lab 2:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Syntax to define class, Need for class as a template, Command line
arguments and console input

Pre-Lab Task:
1. Design a class named Stock that contains:
a) A string data field named symbol for the stock’s symbol.
b) A string data field named name for the stock’s name.
c) A double data field named previousClosingPrice that stores the stock price for the
previous day.
d) A double data field named currentPrice that stores the stock price for the current
time.
e) A method named getChangePercent() that returns the percentage changed from
previousClosingPrice to currentPrice.
Use appropriate access specifiers for instance variables and instance methods. Draw
the class diagram.
(Hint: Modularize to package level)

19
19CS1203 OBJECT ORIENTED PROGRAMMING

20
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Write menu driven main () method in Demo class to perform


a) Linear Search
b) Binary Search
c) Bubble Sort
(Hint: Use static methods in same class.)
The program must read a set of integers through command line arguments and
use console to read the key.

21
19CS1203 OBJECT ORIENTED PROGRAMMING

22
19CS1203 OBJECT ORIENTED PROGRAMMING

23
19CS1203 OBJECT ORIENTED PROGRAMMING

In-Lab Task:
1. Design a class named QuadraticEquation for a quadratic equation ax2 + bx + c = 0.
The class contains:
a) Private data fields a, b, and c that represent three coefficients.
b) Three getter methods for a, b, and c.
c) A method named getDiscriminant() that returns the discriminant, which is
b2 - 4ac.
d) The methods named getRoot1() and getRoot2() for returning two roots of
the equation.

r1 and r2 =

24
19CS1203 OBJECT ORIENTED PROGRAMMING

25
19CS1203 OBJECT ORIENTED PROGRAMMING

26
19CS1203 OBJECT ORIENTED PROGRAMMING

2.Define a class Student with the following attributes under private access and
methods under public access.
a. Name b) ID c) gender d) department
i. Define setter methods such that name but not have any special characters
and Digits.
ii. ID must be a positive 9-digit value
iii. Gender must be either M/F
iv. Department must be either BT/CE/CSE/ECE/EEE/ECS/ME/PE
v. Define toString() method
vi. In the main method define two Student objects and prints the details of the
students in the following format.
ID: 190030000
Name: ABC
Gender: M
Department: CSE
(Hint: Read the data from console)

27
19CS1203 OBJECT ORIENTED PROGRAMMING

28
19CS1203 OBJECT ORIENTED PROGRAMMING

Post-Lab Task:
1. Write a program that randomly generates an array of 100,000 integers and a key.
Estimate the execution time of invoking the linearSearch() method in best, average
and worst cases.
You can use the following code template to obtain the execution time:
a. long startTime = System.currentTimeMillis();
b. perform the task;
c. long endTime = System.currentTimeMillis();
d. long executionTime = endTime - startTime;

29
19CS1203 OBJECT ORIENTED PROGRAMMING

30
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Develop a java program to that reads the number of rows and columns through
command-line, reads the set of elements in a 2D array from console. The menu
driven program must perform the following operations:
a) Sum of all elements
b) Print the data in matrix form
c) Print the elements of principal diagonal
d) Print the sum of elements in Principal diagonal

31
19CS1203 OBJECT ORIENTED PROGRAMMING

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation


Marks Secured: _______ out of ________

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

32
19CS1203 OBJECT ORIENTED PROGRAMMING

Lab 3:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: I/O through files and GUI

Pre-Lab Task:
1. Alex has a file which has 2 integers. The task is to add these integers and print the
result. Write java program to perform this task.

33
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Write a java program that reads Student ID, Name, age, gender and prints the details
on User Interface.
(Hint: Use JOptionPane of javax.swing package)

34
19CS1203 OBJECT ORIENTED PROGRAMMING

In-Lab Task:
1. Chandu has 2 files, Names.txt and Address.txt. Names.txt has 2 columns ID and
student names and Dept.txt has 2 columns ID and Address. Fortunately, the IDs in both
files are same and sorted. The task is to read data from both files and print the student
data in the following format:
ID: Name: Address:
Print one student details per line on the console.

35
19CS1203 OBJECT ORIENTED PROGRAMMING

36
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Develop a java program using swing package. The program must display a student
registration page, which reads ID, Name, Gender (Use Radio Buttons) and department
(Use Drop down selection) and two buttons Submit and Reset. When the user clicks
Submit, then validate the data, use JOptionPane to alert if any data is missing or
entered wrong, otherwise display the data submitted back on JOptionPane. The reset
button clears all the data.

37
19CS1203 OBJECT ORIENTED PROGRAMMING

38
19CS1203 OBJECT ORIENTED PROGRAMMING

Post-Lab Task:
1. Develop a simple calculator to perform basic arithmetic on 2 integers using GUI.

39
19CS1203 OBJECT ORIENTED PROGRAMMING

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation


Marks Secured: _______ out of ________

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

40
19CS1203 OBJECT ORIENTED PROGRAMMING

Lab 4:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Constructors and Overloading, Chaining and this

Pre-Lab Task:
1. Design a class named MyInteger. The class contains:
 An int data field named value that stores the int value represented by this object.
 A constructor that creates a MyInteger object for the specified int value.
 A getter method that returns the int value.
 The methods isEven(), isOdd(), and isPrime() that return true if the value in this object
is even, odd, or prime, respectively.
 The static methods isEven(int), isOdd(int), and isPrime(int) that return true if the
specified value is even, odd, or prime, respectively.
 The static methods isEven(MyInteger), isOdd(MyInteger), and isPrime(MyInteger)
that return true if the specified value is even, odd, or prime, respectively.
 The methods equals(int) and equals(MyInteger) that return true if the value in this
object is equal to the specified value.
 A static method parseInt(char[]) that converts an array of numeric characters to an
int value.
 A static method parseInt(String) that converts a string into an int value.

Draw the class diagram for the class and then implement the class. Write a client program
that tests all methods in the class.

41
19CS1203 OBJECT ORIENTED PROGRAMMING

42
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Enhance the above my adding a method factorial () which expects an integer argument
and returns the factorial value as BigInteger Wrapper class.

43
19CS1203 OBJECT ORIENTED PROGRAMMING

44
19CS1203 OBJECT ORIENTED PROGRAMMING

In-Lab Task:

1. Design a class named Account that contains:

 A private int data field named id for the account (default 0).
 A private double data field named balance for the account (default 0).
 A private double data field named annualInterestRate that stores the current interest
rate (default 0). Assume all accounts have the same interest rate.
 A no-arg constructor that creates a default account.
 A constructor that creates an account with the specified id and initial balance.
 The accessor and mutator methods for id, balance, and annualInterestRate.
 Mutators return Boolean (If all the fields must be +ve, return true, else false)
 A method named withdraw that withdraws a specified amount from the account.
 A method named deposit that deposits a specified amount to the account.

Draw the UML diagram for the class and then implement the class.
(Hint: The method getMonthlyInterest() is to return monthly interest, not the interest
rate
Monthly interest is balance * monthlyInterestRate.
monthlyInterestRate is annualInterestRate / 12.)

Note that annualInterestRate is a percentage,e.g., like 4.5%. You need to divide it by 100.)
Write a test program that creates an Account object with an account ID of 1122, a balance
of $20,000, and an annual interest rate of 4.5%. Use the withdraw method to withdraw
$2,500, use the deposit method to deposit $3,000, and print the balance, the monthly
interest.

45
19CS1203 OBJECT ORIENTED PROGRAMMING

46
19CS1203 OBJECT ORIENTED PROGRAMMING

47
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Design a class named MyPoint to represent a point with x- and y-coordinates. The class
contains:

The data fields x and y that represent the coordinates with getter methods.

■ A no-arg constructor that creates a point (0, 0).


■ A constructor that constructs a point with specified coordinates.
■ A method named distance that returns the distance from this point to a specified point of
the MyPoint type.
■ A method named distance that returns the distance from this point to another point with
specified x- and y-coordinates.
Draw the UML diagram for the class and then implement the class. Write a test program that
creates the two points (0, 0) and (10, 30.5) and displays the distance between them.

48
19CS1203 OBJECT ORIENTED PROGRAMMING

49
19CS1203 OBJECT ORIENTED PROGRAMMING

Post-Lab Task:
1. Design Use the Account class that simulates an ATM machine. Create ten accounts in an
array with id 1, . . . , 10, and initial balance $100. The system prompts the user to enter
an id. If the id is entered incorrectly, ask the user to enter a correct id. Once an id is
accepted, the main menu is displayed as shown in the sample run. You can enter a choice
1 for viewing the current balance, 2 for withdrawing money, 3 for depositing money, and
4 for exiting the main menu. Once you exit, the system will prompt for an id again. Thus,
once the system starts, it will stop when id is 0.

50
19CS1203 OBJECT ORIENTED PROGRAMMING

51
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Implement the following

In the no-args constructor, size must be initialized to 10 and initialize the array with the
same.

52
19CS1203 OBJECT ORIENTED PROGRAMMING

53
19CS1203 OBJECT ORIENTED PROGRAMMING

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation


Marks Secured: _______ out of ________

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

54
19CS1203 OBJECT ORIENTED PROGRAMMING

Lab 5:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Objects as data members, Menu driven programs to perform


operations on array of objects

Pre-Lab Task:

1. Design a class named StopWatch. The class contains:


■ Private data fields startTime and endTime with getter methods.
■ A no-arg constructor that initializes startTime with the current time.
■ A method named start() that sets the startTime to the current time.
■ A method named stop() that sets the endTime to the current time.
■ A method named getElapsedTime() that returns the elapsed time for the
stopwatch in milliseconds.
Draw the UML diagram for the class and then implement the class.

55
19CS1203 OBJECT ORIENTED PROGRAMMING

56
19CS1203 OBJECT ORIENTED PROGRAMMING

2. A Restaurant serves dishes of three types: Veg, Non-Veg and Egg represented by green, red
and brown color codes respectively. Help them out by writing a menu driven program to
display the various dishes depending on the type of food the customer opts for.

57
19CS1203 OBJECT ORIENTED PROGRAMMING

In-Lab Task:

1. A customer of a bank wants to withdraw/deposit money from his account. There are
3 ATMs in his town. Help him out by writing a program such that his balance will be
updated after a transaction in any of the ATMs. (Use ‘Account’ as Singleton Class and
it should be Early Instantiated)

58
19CS1203 OBJECT ORIENTED PROGRAMMING

59
19CS1203 OBJECT ORIENTED PROGRAMMING

2. A company wants to digitalize their manual records of the employee details (Employee
ID, Employee name, Employee Department). If all the three fields are given, use the
given details. If not, use the default values.
(Use Constructor Overloading)
Default values are:
ID: 0
Name: #
Department: #.
Write toString () method, mutators and accessors.
Write a menu driven main () method to perform the following operations:
Create new Employee record
Update name based on ID
Print All Employees
Print Department Specific employees

60
19CS1203 OBJECT ORIENTED PROGRAMMING

61
19CS1203 OBJECT ORIENTED PROGRAMMING

62
19CS1203 OBJECT ORIENTED PROGRAMMING

Post-Lab Task:

1. Use the student class define in Lab 2 and enhance the main method such that we
can store data of 10 students in an array and perform the following operations as
a menu driven program.
a) Create a new student
b) Print details of all students
c) Print details based on ID
d) Modify student name based on ID
e) Remove a student based on ID

63
19CS1203 OBJECT ORIENTED PROGRAMMING

64
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Enhance the design of In-lab Q2, such that the date of joining is one attribute of
Employee and print the details of all employees who joined in 2019.

65
19CS1203 OBJECT ORIENTED PROGRAMMING

66
19CS1203 OBJECT ORIENTED PROGRAMMING

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation


Marks Secured: _______ out of ________

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

67
19CS1203 OBJECT ORIENTED PROGRAMMING

Lab 6: Strings

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: String, StringBuffer, StringTokenizer and Date

Pre-Lab Task:
1. Write a menu driven program to illustrate the following operations on String Class
a) charAt()
b) length()
c) indexOf() -all overloaded methods
d) lastIndexOf() -all overloaded methods
e) substring() - all overloaded methods
f) valueOf() - all overloaded methods

68
19CS1203 OBJECT ORIENTED PROGRAMMING

69
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Write a menu driven program to illustrate the following operations on StringBuffer


Class
a) charAt()
b) append()
c) capacity()
d) length()
e) delete()
f) deleteCharAt()
g) insert()
h) reverse()
i) replace()

70
19CS1203 OBJECT ORIENTED PROGRAMMING

71
19CS1203 OBJECT ORIENTED PROGRAMMING

In-Lab Task:
1. Write a program that sets up a String variable containing a paragraph of text of
your choice from file. Extract the words from the text and sort them into
alphabetical order. Display the sorted list of words. You could use a simple sorting
method called the bubble sort.

72
19CS1203 OBJECT ORIENTED PROGRAMMING

73
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Define an array of ten String elements each containing an arbitrary string of the
form “month/day/year”; for example,”10/29/99” or “12/5/01”. Analyze each
element in the array and output the date represented in the form 29th October
1999

74
19CS1203 OBJECT ORIENTED PROGRAMMING

Post-Lab Task:
1. Write a program that will reverse the sequence of letters in each word of your
chosen paragraph from Exercise 3. For instance, “To be or not to be.” would
become “oT eb ro ton ot eb.”

75
19CS1203 OBJECT ORIENTED PROGRAMMING

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation


Marks Secured: _______ out of ________

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

76
19CS1203 OBJECT ORIENTED PROGRAMMING

Lab 07:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Inheritance, method overloading

Pre-Lab Task:
1. Develop a program that creates a generic Shape class with attributes fillColor,
borderColor, fill (Boolean type) and border width. The classes Rectangle, Circle must
inherit Shape. Rectangle has length and width as attributes and circle with radius as
attribute. Also add the corresponding getters and setters, toString() in each of the
classes. Use appropriate access specifiers. In the main () method of Demo class, create
objects and access the methods. Draw the class diagram.

77
19CS1203 OBJECT ORIENTED PROGRAMMING

78
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Enhance the Pre-lab Q1 hierarchy such that Shape is the general class, inherited by
TwoDShape and ThreeDShape class, and Rectangle, Circle inherits the TwoDShape,
Cuboid and Sphere extend the ThreeDshape.

79
19CS1203 OBJECT ORIENTED PROGRAMMING

80
19CS1203 OBJECT ORIENTED PROGRAMMING

81
19CS1203 OBJECT ORIENTED PROGRAMMING

In-Lab Task:
1. Design a class named Triangle that extends GeometricObject. The class contains:
■ Three double data fields named side1, side2, and side3 with default values 1.0 to
denote three sides of the triangle.
■ A no-arg constructor that creates a default triangle.
■ A constructor that creates a triangle with the specified side1, side2, and side3.
■ The accessor methods for all three data fields.
■ A method named getArea() that returns the area of this triangle.
■ A method named getPerimeter() that returns the perimeter of this triangle.
■ A method named toString() that returns a string description for the triangle.
The toString() method is implemented as follows:
return "Triangle: side1 = " + side1 + " side2 = " + side2 +
" side3 = " + side3;
Draw the UML diagrams for the classes Triangle and GeometricObject and implement
the classes. Write a test program that prompts the user to enter three sides of the
triangle, a color, and a Boolean value to indicate whether the triangle is filled. The
program should create a Triangle object with these sides and set the color and filled
properties using the input. The program should display the area, perimeter, color, and
true or false to indicate whether it is filled or not.

82
19CS1203 OBJECT ORIENTED PROGRAMMING

83
19CS1203 OBJECT ORIENTED PROGRAMMING

84
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Design a class named Person and its two subclasses named Student and Employee.
Make Faculty and Staff subclasses of Employee. A person has a name, address, phone
number, and email address. A student has a class status (freshman, sophomore, junior,
or senior). Define the status as a constant. An employee has an office, salary, and date
hired. A faculty member has office hours and a rank. A staff member has a title.
Override the toString method in each class to display the class name and the person’s
name. Draw the UML diagram for the classes and implement them. Write a test
program that creates a Person, Student, Employee, Faculty, and Staff, and invokes
their toString() methods.

85
19CS1203 OBJECT ORIENTED PROGRAMMING

86
19CS1203 OBJECT ORIENTED PROGRAMMING

87
19CS1203 OBJECT ORIENTED PROGRAMMING

Post-Lab Task:
1. The Account class was defined to model a bank account. An account has the
properties account number, balance, annual interest rate, and date created, and
methods to deposit and withdraw funds. Create two subclasses for checking and
saving accounts. A checking account has an overdraft limit, but a savings account
cannot be overdrawn. Draw the UML diagram for the classes and then implement
them. Write a test program that creates objects of Account, SavingsAccount, and
CheckingAccount and invokes their toString() methods.

88
19CS1203 OBJECT ORIENTED PROGRAMMING

89
19CS1203 OBJECT ORIENTED PROGRAMMING

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation


Marks Secured: _______ out of ________

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

90
19CS1203 OBJECT ORIENTED PROGRAMMING

Lab 08:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Inheritance, abstract classes

Pre-Lab Task

1. A customer walks into a KFC outlet and sees that he has two options: veg and non-
veg. He observes that plain veg burger costs 80/- and plain non-veg burger costs 120/-
each. But he wishes to have extra mayonnaise and either of extra veggies/chicken on
each of his burgers. Help the outlet by writing a program which’ll help them calculate
the cost of the basic burger and include the cost of the condiments if he chooses to
add any. (Use Inheritance and Null Object Design Pattern)
Item Cost
Mayonnaise 30/-
Veggies 45/-
Chicken 60/-

91
19CS1203 OBJECT ORIENTED PROGRAMMING

In -Lab Task:

1. Your local library needs your help related to library management and wants you to
develop a program that will help them to calculate the fine. Remember that the name
and the number of days the borrower had the book with them should be protected
and display the information using inheritance concept. After 15 days fine will be
charged as 2 rupees per day until the day of submission, if there is no charge simply
print “NO FINE” else print the fine.

92
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Abilash has given his credit card to his three sons for their monthly expenses. After
the turn of the month, he gets a bill of 1,00,000/- Rahul tells him that he had used
15,000/- in that month. SriRam and Kartheek tell him that they’ve used 35,000/- and
50,000/- respectively. Help Abilash to find out percentage of amount each of his sons
used in that month. Consider creditBill as abstract class containing a return method
and an abstract method. Use Dynamic Polymorphism.

93
19CS1203 OBJECT ORIENTED PROGRAMMING

94
19CS1203 OBJECT ORIENTED PROGRAMMING

Post-Lab Task
1. Karteek is the head of the village panchayat and decides to collect the data related to
the population, total income and the average income of the village and stores it in a
class which is in a package village. Help him out to create another package and access
the village information. (Use Protected access specifier)

95
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Rahul owns a company and ran it for a period of 7 years with a profit of 80cr per annum.
He falls sick and his son Rohan inherits the ownership of the company and runs it for a
period of 6 years with a profit margin of 120cr per annum. Complete the given code.
(Use the keyword ‘Super’)
class Rahul
{
Rahul (int yearsWorked, int profitPerAnnum)
{ //Fill the code

}
}
class Rohan extends Rahul
{
Rohan (int yearsWorked, int profitPerAnnum)
{
//Fill the code

}
}

class Company
{
public static void main (String [] args)
{
//Fill the line

96
19CS1203 OBJECT ORIENTED PROGRAMMING

}
}

OUTPUT FORMAT:
Rahul worked for 7 years and earned profit 80 crores
Total Profit earned by Rahul is: 560
After Rahul's ill health his son Rohan, took over to develop his father’s company
Rohan worked for 6 years and earned profit 120 crores
Total Profit earned by Rohan is: 720

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation


Marks Secured: _______ out of ________

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

97
19CS1203 OBJECT ORIENTED PROGRAMMING

Lab 09:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Abstract classes and Interfaces

Pre-Lab Task:
1. Mobile phone evolution initially happened in 4 phases. It started with phones having
only call feature, then it extended to phones to having messaging also. In the next
generation phones also had camera and in the final generation of that revolution they
started having internet also. Write a program to print all the features present in a 4th
generation phone. (Use inheritance)

98
19CS1203 OBJECT ORIENTED PROGRAMMING

99
19CS1203 OBJECT ORIENTED PROGRAMMING

In-Lab Task:
1. Define an abstract base class Shape that includes protected data members for the
(x, y) position of a shape, a public method to move a shape, and a public abstract
method show() to output a shape. Derive subclasses for lines, circles, and
rectangles. Also, define the class PolyLine with Shape as its base class. You can
represent a line as two points, a circle as a center and a radius, and a rectangle as
two points on diagonally opposite corners. Implement the toString() method for
each class. Test the classes by selecting ten random objects of the derived classes,
and then invoking the show() method for each.
a. Use the toString() methods in the derived classes a menu driven program
to illustrate the a few operations on String Class

100
19CS1203 OBJECT ORIENTED PROGRAMMING

101
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Implement the following for a Bank ABC

Also develop main () method of Demo class to test the functionality.

102
19CS1203 OBJECT ORIENTED PROGRAMMING

3. Mark owns a Xerox shop. He uses a Smart Printer which can Print, Fax and Scan to render
his services to the customers. As the business is booming, he bought and installed an
Economic Printer which can only print. Implement interfaces for both printers using Interface
Segregation Principle.

103
19CS1203 OBJECT ORIENTED PROGRAMMING

104
19CS1203 OBJECT ORIENTED PROGRAMMING

Post-Lab Task:
1. You are a journalist and are required to submit a report on the number of accidents
that had occurred in your area. Collect the information of accidents caused by car, bus
and bike from your local NGO’s and write a program that will print the number of
accidents of each type that had occurred. (Use Interface and it contains a method
numberOfAccidents, also use Adapter Design Pattern.)

105
19CS1203 OBJECT ORIENTED PROGRAMMING

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation


Marks Secured: _______ out of ________

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

106
19CS1203 OBJECT ORIENTED PROGRAMMING

Lab 10:

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Exception Handling

Pre-Lab Task:

1. An old man wants to distribute sweets to children near his home. He was confused of
how many sweets he must give to each child. Help the old man by writing a program
where the number of sweets and number of children are initialized using
parameterized constructor. Observe what happens when there are zero number of
children and handle the exception if any.

107
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Write java program to read 10 values into an array and prints the value in 11th index

108
19CS1203 OBJECT ORIENTED PROGRAMMING

In-Lab Task:
1. Election committee wants to check whether the voter is eligible to vote or not. The
person can vote if his age is greater than 18. Help the Election committee by
developing a code which arises exception if the voter age is less than 18 then print
the exception and “VOTER IS NOT ELIGIBLE TO VOTE”, otherwise print “VOTER IS
ELIGIBLE TO VOTE”. (Hint: Develop user-defined Exception)

109
19CS1203 OBJECT ORIENTED PROGRAMMING

110
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Enhance the Lab-5 In-Lab Task Q2, such that when Invalid ID (-ve number) is given
it must throw InvalidIDException, and InvalidNameException when name has
special characters or digits.

111
19CS1203 OBJECT ORIENTED PROGRAMMING

112
19CS1203 OBJECT ORIENTED PROGRAMMING

Post-Lab Task:
1. Enhance Q2, to read data from file. The program must close the file even when
an exception arises or not. (Hint: Use finally block)

113
19CS1203 OBJECT ORIENTED PROGRAMMING

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation


Marks Secured: _______ out of ________

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

114
19CS1203 OBJECT ORIENTED PROGRAMMING

Lab 11

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Multithreading

Pre-Lab Task:
1. You are given a task of printing the first five natural numbers assigned to all three
different threads which should be created by implementing runnable interface.
Run this program for three times and check the printing style each time.

115
19CS1203 OBJECT ORIENTED PROGRAMMING

116
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Perform the Pre-Lab Q1 task by extending the Thread class.

117
19CS1203 OBJECT ORIENTED PROGRAMMING

In-Lab Task:
1. Rohan was asked by his teacher to develop a program which takes in a dynamic
user input and prints all the prime numbers till that number and then prints all the
composite numbers till that number. Help him out by developing the program to
do so. Use one thread each for both prime and composite numbers

118
19CS1203 OBJECT ORIENTED PROGRAMMING

119
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Tony was asked to develop a program which takes in five alphabets as dynamic
user input and stores them in an array. He passes the array to two threads. First
one should traverse the array, and the vowels present in it should be printed and
the second thread should print the consonants present in the array. Help him out
by writing the program.

120
19CS1203 OBJECT ORIENTED PROGRAMMING

121
19CS1203 OBJECT ORIENTED PROGRAMMING

Post-Lab Task:
1. You are asked to take two integer values as dynamic user inputs. The values are
then passed to two threads where their respective multiplication table’s logic (up
to 10) should be written in a synchronized block and print them.

122
19CS1203 OBJECT ORIENTED PROGRAMMING

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation


Marks Secured: _______ out of ________

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

123
19CS1203 OBJECT ORIENTED PROGRAMMING

Lab 12

Date of the Session: ___/___/___ Time of the Session: _____to______

Prerequisite: Collection Framework – List, Set and Map

Pre-Lab Task:
1. Develop a java program to store 10 integer values in an arraylist. Calculate the sum,
insert 10 more values and compute the sum.

124
19CS1203 OBJECT ORIENTED PROGRAMMING

2. Develop a java program to store 10 integer values in a Hashset and print them.
Analyze the output in case of duplicate inputs.

125
19CS1203 OBJECT ORIENTED PROGRAMMING

3. Create a HashMap with 10 elements where each element has (key:int, value: String)
and apply the following operations.
a) Search for an element of a given key. If exists in the HashMap, print the
key – value pair, otherwise, print “Search key not found”.
b) Remove an element from the HashMap for a given key.

126
19CS1203 OBJECT ORIENTED PROGRAMMING

In-Lab Task:
1. Develop a java program to store the details of students in an ArrayList. Use the
student class as defined in In-Lab 2 Exercise.

127
19CS1203 OBJECT ORIENTED PROGRAMMING

128
19CS1203 OBJECT ORIENTED PROGRAMMING

2. You are the class representative and are required to store the Student Details and ID
numbers of all your classmates. Develop a program which takes in the details of the
students as dynamic user input and store them in Hashmap. It should print the details
and it should also be able to help you search for a Student details using the ID number.

129
19CS1203 OBJECT ORIENTED PROGRAMMING

130
19CS1203 OBJECT ORIENTED PROGRAMMING

Post-Lab Task:
1. Develop a program to read the country names (separated by space) from a file and store in
an ArrayList and then perform the following menu driven operations.
a) Search for a country name
b) Sort based on country name

131
19CS1203 OBJECT ORIENTED PROGRAMMING

(For Evaluator’s use only)

Comment of the Evaluator (if Any) Evaluator’s Observation


Marks Secured: _______ out of ________

Full Name of the Evaluator:

Signature of the Evaluator Date of Evaluation:

132