You are on page 1of 17

CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21

PART-A
1 Define Encapsulation in Java.
The wrapping up of data and functions into a single unit is known as data encapsulation.
Here the data is not accessible to the outside the class. The data inside that class is accessible
by the function in the same class. It is normally not accessible from the outside of the
component
2 What is Constructors in Java?
A constructor is a special method that is used to initialize an object. The name of the
constructor and the name of the class must be the same. A constructor does not have any
return type.
There are two types of Constructor
Default Constructor – constructor without argument
Parameterized constructor – constructor with arguments
3 What is the use of super keyword?
This is used to initialize constructor of base class from the derived class and also access the
variables of base class like super.i = 10.
4 Difference between class and interface.
Class and Interface both are used to create new reference types. A class is a collection of fields
and methods that operate on fields. An interface has fully abstract methods i.e. methods with
nobody. An interface is syntactically similar to the class but there is a major difference
between class and interface that is a class can be instantiated, but an interface can never be
instantiated.
5 What is the purpose of finally clause? Give example.
The finally clause is used to provide the capability to execute code no matter whether or not
an exception is thrown or caught.
class Example
{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
/* Finally block will always execute even if there is no exception in try block */
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}
Output:
Number should not be divided by zero
This is finally block
Out of try-catch-finally
6 What are the uses of streams? What are the two types of streams?
Java provides I/O Streams to read and write data where, a Stream represents an input source
or an output destination which could be a file, i/o devise, other program etc.

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 1 of 17
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
In general, a Stream will be an input stream or, an output stream.
 InputStream − This is used to read data from a source.
 OutputStream − This is used to write data to a destination.
The Stream API is used to process collections of objects. A stream is a sequence of objects that
supports various methods which can be pipelined to produce the desired result.
7 What is the need for synchronization? How it can be implemented?
Synchronization is a process of handling resource accessibility by multiple thread requests.
The main purpose of synchronization is to avoid thread interference. At times when more
than one thread try to access a shared resource, we need to ensure that resource will be used
by only one thread at a time. The process by which this is achieved is called
synchronization. If we do not use synchronization, and let two or more threads access a
shared resource at the same time, it will lead to distorted results.
Consider an example, Suppose we have two different threads T1 and T2, T1 starts execution
and save certain values in a file temporary.txt which will be used to calculate some result
when T1 returns. Meanwhile, T2 starts and before T1 returns, T2 change the values saved by
T1 in the file temporary.txt (temporary.txt is the shared resource). Now obviously T1 will
return wrong result. To prevent such problems, synchronization was introduced.
8 How to create a single class, which automatically works with different types of data? Give
example. (Nov/Dec 2020)(Apr/May 2021)
A Wrapper class is a class whose object wraps or contains primitive data types. When we
create an object to a wrapper class, it contains a field and in this field, we can store primitive
data types. In other words, we can wrap a primitive value into a wrapper class object. They
convert primitive data types into objects. Objects are needed if we wish to modify the
arguments passed into a method.

Example:
1. //Autoboxing example of int to Integer
2. public class WrapperExample1{
3. public static void main(String args[]){
4. //Converting int into Integer
5. int a=20;
6. Integer i=Integer.valueOf(a);//converting int into Integer explicitly
7. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
8. System.out.println(a+" "+i+" "+j);
9. }}
10. Output:
20 20 20
9 Write the sequence in which method calls takes place when an applet is terminated?
Define those methods.
When an applet is terminated, the following sequence of method calls takes place :
 stop()
 destroy()
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
stop( ) method is called when a web browser leaves the HTML document containing the
applet—when it goes to another page, for example. When stop( ) is called, the applet is
probably running. You should use stop( ) to suspend threads that don't need to run when the
applet is not visible.
destroy() method is called by the browser just before an applet is terminated. Your applet will
override this method if it needs to perform any cleanup prior to its destruction. A subclass of
Applet should override this method if it has any operation that it wants to perform before it
is destroyed.
10 What are the two key features of swing?
Swing offers two key features:
 Swing components are lightweight and don't rely on peers.
 Swing supports a pluggable look and feel.
PART B –(5*13=65 marks)
11 a How Java changed the internet? ii) If semicolons are needed at the end of each statement, why
does the comment line not end with a semicolon ?
The Internet helped catapult Java to the forefront of programming, and Java, in turn, had a profound
effect on the Internet. In addition to simplifying web programming in general, Java innovated a new
type of networked program called the applet that changed the way the online world thought about
content. Java also addressed some of the thorniest issues associated with the Internet: portability and
security.
Semicolon is a punctuation mark (;) indicating a pause, typically between two main clauses, that is ore
pronounced than that indicated by a comma. In programming, Semicolon symbol plays a vital role. It
is used to show the termination of instruction in various programming languages as well, like C, C++,
Java, JavaScript and Python.
Role of Semicolon in Java:
1. Java uses Semicolon similar to C.
2. Semicolon is a part of syntax in Java.
3. It shows the compiler where an instruction ends and where the next instruction begins.
4. Semicolon allows the java program to be written in one line or multiple lines, by letting the
compiler know where to end the instructions.
Comments are used in a programming language to document the program and remind programmers
of what tricky things they just did with the code, or to warn later generations of programmers stuck
with maintaining some spaghetti code. While comments may seem to be a minor issue in a language,
an awkward comment format in a language is a nuisance and can be a source of nasty errors. The
content of a comment is handled as if it were not there by the compiler. Examples of modern-day
comments are:

max = 100; // using default size.


/* check input for valid values and
print error message for accounting if problems. */

11 b What are the three categories of control statements used in Java? Explain each category with
example.
Control Statements in Java
Java provides us control structures, statements that can alter the flow of a sequence of instructions.
Compound statements
Compound statements or block is a group of statements which are separated by semicolons (;) and
grouped together in a block enclosed in braces { and } is called a compound statement.
Example:
{
temp = a;
a = b;
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
b = temp;
}
Types of control statements
Java supports two basic control statements.
 Selection statements
 Iteration statements
Selection statements
This statement allows us to select a statement or set of statements for execution based on some
condition.
The different selection statements are:
 if statement
 if-else statement
 nested statement
 switch statement
if statement
This is the simplest form of if statement. This statement is also called as one-way branching. This
statement is used to decide whether a statement or a set

of statements should be executed or not. The decision is based on a condition which can be evaluated
to TRUE or FALSE.
Syntax:
if(expression)
Statement;

if–else statement
This statement is also called as two-way branching. It is used when there are alternative statements
need to be executed based on the condition. It executes some set of statements when the given
condition is TRUE and if the condition is FALSE then other set of statements to be executed.
Syntax:
if(expression)
Statement;
else
Statement;

Nested-if statement
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
An if statement may contain another if statement within it. Such an if statement is called as nested if
statement.
Syntax:
if(condition1)
Statement
If(condition2)
Statement

if-else-if statement
This structure is also called as else-if ladder. This structure will be used to verify a range of values. This
statement allows a choice to be made between different possible alternatives.
Syntax:
if(condition)
Statement;
else if (condition)
Statement;
.
.
else
Statement;

Switch statement
Java has a built-in multiple-branch selection statement, switch. This successively tests the value of an
expression against a list of integer or character constants. When a match is found, the statements
associated with that code is executed.
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21

12 a Write a Java program to calculate electricity bill using inheritance. The program should get the
inputs of watts per hour and unit rate. Check your program for the following case : Assume a
consumer consumes 5000 watts per hour daily for one month. Calculate the total energy bill of
that consumer if per unit rate is 7 [1 unit = 1k Wh].
import java.util.*;

class ComputeElectricityBill {

// Function to calculate the


// electricity bill
public static int calculateBill(int units)
{

// Condition to find the charges


// bar in which the units consumed
// is fall
if (units <= 100) {
return units * 10;
}
else if (units <= 200) {
return (100 * 10)
+ (units - 100)
* 15;
}
else if (units <= 300) {
return (100 * 10)
+ (100 * 15)
+ (units - 200)
* 20;
}
else if (units > 300) {
return (100 * 10)
+ (100 * 15)
+ (100 * 20)
+ (units - 300)
* 25;
}
return 0;
}

// Driver Code
public static void main(String args[])
{
int units = 250;

System.out.println(
calculateBill(units));
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
}
}

12 b What is interface? With an example explain how to define and implement interface.
An interface in java is a blueprint of a class. It has static constants and abstract
methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and multiple
inheritance in Java. Java Interface also represents the IS-A relationship. It cannot be
instantiated just like the abstract class
There are mainly three reasons to use interface. They are

erface, we can support the functionality of multiple inheritance.

An interface is declared by using the interface keyword. It provides total abstraction; means
all the methods in an interface are declared with the empty body, and all the fields are public,
static and final by default. A class that implements an interface must implement all the
methods declared in the interface.
Syntax :
interface <interface_name> {
// declare constant fields
// declare methods that abstract
// by default.
}
Example
interface MyInterface{
public void method1();
public void method2();
}
class Demo implements MyInterface{
public void method1() {
System.out.println("implementation of method1");
}
public void method2() {
System.out.println("implementation of method2");
}
public static void main(String arg[]) {
MyInterface obj = new Demo();
obj.method1();
}
}
Output:
implementation of method1
An interface declared within another interface or class is known as nested interface. The
nested interfaces are used to group related interfaces so that they can be easy to maintain. The
nested interface must be referred by the outer interface or class. It can't be accessed directly.
Nested interface must be public if it is declared inside the interface but it can have any access
modifier if declared within the class. Nested interfaces are declared static implicitely.
Example
interface MyInterfaceA{
void display();
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
interface MyInterfaceB{
void myMethod();
}
}
class NestedInterfaceDemo1 implements MyInterfaceA.MyInterfaceB{
public void myMethod(){
System.out.println("Nested interface method");
}
public static void main(String args[]){
MyInterfaceA.MyInterfaceB obj= new NestedInterfaceDemo1();
obj.myMethod();
}
}
Output:
Nested interface method
13 a Write a short note on the following topics :
a) Uncaught exceptions.
b) Difference between throw and throws. Give example for both.
c) Chained exceptions. Give example
13 b How to perform reading and writing files? Explain with example.
i. reading from a file
Java FileWriter and FileReader classes are used to write and read data from text files (they are
Character Stream classes). It is recommended not to use the FileInputStream and
FileOutputStream classes if you have to read and write any textual information as these are
Byte stream classes.
FileReader is useful to read data in the form of characters from a ‗text‘ file.
• This class inherit from the InputStreamReader Class.
• The constructors of this class assume that the default character encoding and the
default byte-buffer size are appropriate. To specify these values yourself, construct an
InputStreamReader on a FileInputStream.
• FileReader is meant for reading streams of characters. For reading streams of raw
bytes, consider using a FileInputStream.
importjava.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReaderfr=new FileReader("D:\\testout.txt");
inti;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
ii. writing in a file
FileWriter is useful to create a file writing characters into it. This class inherits from the
OutputStream class. The constructors of this class assume that the default character encoding
and the default byte-buffer size are acceptable. To specify these values yourself, construct an
OutputStreamWriter on a FileOutputStream.FileWriter is meant for writing streams of
characters. For writing streams of raw bytes, consider using a FileOutputStream. FileWriter
creates the output file , if it is not present already
importjava.io.FileWriter;
public class FileWriterExample {
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
public static void main(String args[]){
try{
FileWriterfw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to javaTpoint.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
14 a Discuss the different states of thread in detail.
The following figure shows the states that a thread can be in during its life and illustrates
which method calls cause a transition to another state.

14 b i) What is the purpose of thread priorities? What are the different thread priorities that exist?
What are bounded types? Why it is used? Give example.
In a Multi threading environment, thread scheduler assigns processor to a thread based on
priority of thread. Whenever we create a thread in Java, it always has some priority assigned
to it. Priority can either be given by JVM while creating the thread or it can be given by
programmer explicitly.
Accepted value of priority for a thread is in range of 1 to 10. There are 3 static variables
defined in Thread class for priority.
public static int MIN_PRIORITY: This is minimum priority that a thread can have. Value for
this is 1.
public static int NORM_PRIORITY: This is default priority of a thread if do not explicitly
define it. Value for this is 5.
public static int MAX_PRIORITY: This is maximum priority of a thread. Value for this is 10.
Get and Set Thread Priority:
1. public final int getPriority(): java.lang.Thread.getPriority() method returns priority of
given thread.
2. public final void setPriority(int newPriority): java.lang.Thread.setPriority() method
changes the priority of thread to the value newPriority. This method throws
IllegalArgumentException if value of parameter newPriority goes beyond minimum(1)
and maximum(10) limit.
Bounded Type Parameters
There may be times when you want to restrict the types that can be used as type arguments in
a parameterized type. For example, a method that operates on numbers might only want to
accept instances of Number or its subclasses. This is what bounded type parameters are for.
 Sometimes we don‘t want whole class to be parameterized, in that case we can create
java generics method. Since constructor is a special kind of method, we can use generics
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
type in constructors too.
 Suppose we want to restrict the type of objects that can be used in the parameterized type.
For example in a method that compares two objects and we want to make sure that the
accepted objects are Comparables.
 The invocation of these methods is similar to unbounded method except that if we will try
to use any class that is not Comparable, it will throw compile time error.
15 a List any five different user interface components that can generate the events. Demonstrate
any four mouse event handlers with example.
Change in the state of an object is known as event i.e. event describes the change in state of
source. Events are generated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from list, scrolling the page are the activities that causes
an event to happen.
Types of Event
The events can be broadly classified into two categories:
Foreground Events - Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components in Graphical
User Interface. For example, clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from list, scrolling the page etc.
Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer expires,
an operation completion are the example of background events.
Event Handling is the mechanism that controls the event and decides what should happen if n
event occurs. This mechanism have the code which is known as event handler that is executed
when an event occurs. Java Uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events. Let's have a brief
introduction to this model.
The Delegation Event Model has the following key participants namely:
Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provides classes for source object.
Listener - It is also known as event handler. Listener is responsible for generating response to
an event. From java implementation point of view the listener is also an object. Listener waits
until it receives an event. Once the event is received , the listener process the event an then
returns.

15 b Describe how to work with graphics to display information within window.


Displaying Information Within a Window
In the most general sense, a window is a container for information. Although we have already
output small amounts of text to a window in the preceding examples, we have not begun to
take advantage of a window's ability to present high-quality text and graphics. Indeed, much
of the power of the AWT comes from its support for these items. For this reason, he remainder
of this chapter discusses Java's text-, graphics-, and font-handling capabilities.
The AWT supports a rich assortment of graphics methods. All graphics are drawn relative to
a window. This can be the main window of an applet, a child window of an applet, or a stand-
alone application window. The origin of each window is at the top-left corner and is 0,0.
Coordinates are specified in pixels. All output to a window takes place through a graphics
context. A graphics context is encapsulated by the Graphics class and is obtained in two ways:
· It is passed to an applet when one of its various methods, such as paint( ) or update( ),
is called.
· It is returned by the getGraphics( ) method of Component.
For the sake of convenience the remainder of the examples in this chapter will demonstrate
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
graphics in the main applet window. However, the same techniques will apply to any other
window.
The Graphics class defines a number of drawing functions. Each shape can be drawn edge-
only or filled. Objects are drawn and filled in the currently selected graphics color, which
is black by default. When a graphics object is drawn that exceeds the dimensions of the
window, output is automatically clipped.

PART – C (1*15 =15 marks)


16 a Write an AWT GUI application (called AWT counter) as shown in the Figure 1. Each time the
―Count‖ button is clicked, the counter value shall increase by 1.

import java.awt.*; // Using AWT's containers and components


import java.awt.event.*; // Using AWT's event classes and listener interfaces

// An AWT GUI program inherits the top-level container java.awt.Frame


public class AWTCounter extends Frame implements ActionListener {
private Label lblCount; // Declare component Label
private TextField tfCount; // Declare component TextField
private Button btnCount; // Declare component Button
private int count = 0; // counter's value

// Constructor to setup UI components and event handlers


public AWTCounter () {
setLayout(new FlowLayout());
// "super" Frame sets layout to FlowLayout, which arranges
// Components from left-to-right, then top-to-bottom.

lblCount = new Label("Counter"); // Construct component Label


add(lblCount); // "super" Frame adds Label

tfCount = new TextField(count + "", 10); // Construct component TextField


tfCount.setEditable(false); // read-only
add(tfCount); // "super" Frame adds TextField

btnCount = new Button("Count"); // Construct component Button


add(btnCount); // "super" Frame adds Button
btnCount.addActionListener(this);
// btnCount is the source object that fires ActionEvent when clicked.
// The source add "this" instance as an ActionEvent listener, which provides
// an ActionEvent handler called actionPerformed().
// Clicking btnCount invokes actionPerformed().

St. Joseph’s College of Engineering & St. Joseph’s Institute of Technology Page 11 of 17
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
setSize(250, 100); // "super" Frame sets initial size
setTitle("AWT Counter"); // "super" Frame sets title
setVisible(true); // show "super" Frame
}

// ActionEvent handler - Called back when the button is clicked.


@Override
public void actionPerformed(ActionEvent evt) {
++count; // Incrase the counter value
tfCount.setText(count + ""); // Display on the TextField
// setText() takes a String
}

// The entry main() method


public static void main(String[] args) {
// Invoke the constructor by allocating an anonymous instance
new AWTCounter();
}
}
16 b Write an addressbook class that manages a collection of person object. An addressbook will
allow a person to add, delete, or search for a person object in the address book.
 Add method : It should add a person object to the addressbook.
 Delete method: It should remove the specified person object from the book.
Search method: It searches the address book for a specified person and returns the list of
persons matching the specified criteria. The search can be done either by first name, last name
or person id.

Person Class Code:

/Person Class
public class Person {

// Attributes
private int id;
private String firstName;
private String lastName;

// Constructor
public Person(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}

// Getters
public int getId() {
return id;
}

public String getFirstName() {


return firstName;
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
}

public String getLastName() {


return lastName;
}

// Setters
public void setId(int id) {
this.id = id;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

// Overrided hasCode method to return same hasCode


// if two Person Objects are equal
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + id;
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
return result;
}

// Method to check if two Person Objects are equal or not


public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (id != other.id)
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
return true;
}

// to String method for String representation Of Person Object


public String toString() {
return "Id: " + id + "\tFirst Name: " + firstName + "\tLast Name: " + lastName;
}
}
AddressBook Class Code:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class AddressBook {

// to hold persons details(set does not allow duplicates)


private HashSet<Person> book;

// Constructor to create AddressBook Object


public AddressBook() {
this.book = new HashSet<Person>();
}

// method to add person to addressBook


public boolean addPerson(Person p) {
return this.book.add(p);
}

// Method to remove specified Person


// return true if removal done otherwise return false
public boolean remove(Person p) {
return book.remove(p);
}

// method to search based on First Name


public List<Person> searchByFirstName(String name) {
// create List to hold search result
List<Person> result = new ArrayList<Person>();
// look for all Persons in book
for (Person p : book) {
// if current person first name matches to provided name
if (p.getFirstName().equalsIgnoreCase(name)) {
// add that person to result list
result.add(p);
}
}
// return the result
return result;
}

// method to search based on Last Name


CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21
public List<Person> searchByLastName(String name) {

// create List to hold search result


List<Person> result = new ArrayList<Person>();
// look for all Persons in book
for (Person p : book) {
// if current person last name matches to provided name
if (p.getLastName().equalsIgnoreCase(name)) {
// add that person to result list
result.add(p);
}
}
// return the result
return result;
}

// method to search based on id


public List<Person> searchById(int id) {

// create List to hold search result


List<Person> result = new ArrayList<Person>();
// look for all Persons in book
for (Person p : book) {
// if current person id matches to provided id
if (p.getId() == id) {
// add that person to result list
result.add(p);
}
}
// return the result
return result;
}
}
AddressBookTester Class Code:

import java.util.List;

public class AddressBookTester {

public static void main(String[] args) {

// create AddressBook Object


AddressBook book = new AddressBook();

// Adding Some Persons to book


book.addPerson(new Person(1337, "kowlutla", "Mangali"));
book.addPerson(new Person(1338, "Hindu", "Mangali"));
book.addPerson(new Person(1330, "Deepti", "Maruvada"));
book.addPerson(new Person(1129, "Dheeraj", "Kalluri"));
book.addPerson(new Person(1293, "kowlutla", "Maruvada"));
book.addPerson(new Person(1337, "Hari", "Banavath"));
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21

// trying to add Duplicate Person


System.out.println("trying to add Duplicate Person: ");
if (book.addPerson(new Person(1337, "Hari", "Banavath"))) {
System.out.println("Successfully added person");
} else {
System.out.println("Duplicate Person not allowed");
}

// Search person by using person first name


System.out.println("\nSearching Person By First Name (kowlutla): ");
String firstName = "kowlutla";
List<Person> results = book.searchByFirstName(firstName);

System.out.println("Results: ");
if (results.size() != 0) {
for (Person p : results) {
System.out.println(p);
}
} else {
System.out.println("No person matched");
}

// Search person by using person last name


System.out.println("\nSearching Person By Last Name (Mangali): ");
String lastName = "Mangali";
results = book.searchByLastName(lastName);

System.out.println("Results: ");
if (results.size() != 0) {
for (Person p : results) {
System.out.println(p);
}
} else {
System.out.println("No person matched");
}

// Search person by using person id


System.out.println("\nSearching Person By ID (1337): ");
int id = 1337;
results = book.searchById(id);

System.out.println("Results: ");
if (results.size() != 0) {
for (Person p : results) {
System.out.println(p);
}
} else {
System.out.println("No person matched");
}
}
CS8392-Object Oriented Programming Department of CSE Nov/Dec 20 & Apr/May 21

}
Output Of Code:

trying to add Duplicate Person:


Duplicate Person not allowed

Searching Person By First Name (kowlutla):


Results:
Id: 1293 First Name: kowlutla Last Name: Maruvada
Id: 1337 First Name: kowlutla Last Name: Mangali

Searching Person By Last Name (Mangali):


Results:
Id: 1338 First Name: Hindu Last Name: Mangali
Id: 1337 First Name: kowlutla Last Name: Mangali

Searching Person By ID (1337):


Results:
Id: 1337 First Name: Hari Last Name: Banavath
Id: 1337 First Name: kowlutla Last Name: Mangali

You might also like