0% found this document useful (0 votes)
177 views193 pages

Oop Lab Manual Java by Rab Nawaz Jadoon

This document outlines an exercise to explore object-oriented modeling concepts using a personal banking domain as a case study. Students are asked to identify key entities like Customer and Bank Account, and think about their attributes and methods. For attributes, they consider whether each should be object-level or class-level, its data type, and visibility. For methods, they consider level, parameters, return type, and visibility. The goal is to analyze the domain and apply OO principles to model the important objects and their relationships.

Uploaded by

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

Oop Lab Manual Java by Rab Nawaz Jadoon

This document outlines an exercise to explore object-oriented modeling concepts using a personal banking domain as a case study. Students are asked to identify key entities like Customer and Bank Account, and think about their attributes and methods. For attributes, they consider whether each should be object-level or class-level, its data type, and visibility. For methods, they consider level, parameters, return type, and visibility. The goal is to analyze the domain and apply OO principles to model the important objects and their relationships.

Uploaded by

Patsy Chikunya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 193

Object Oriented Programming

Lab Manual

Faculty Name(s)

Object Oriented Programming using JAVA Lab Manual – Page 1|193


The Practice
of Knowledge

Department of Computer Science


COMSATS University, Islamabad
(Abbottabad
Object Oriented Programming using JAVA Campus) Lab Manual – Page 2|193
Object Oriented Programming
Lab Manual

Dr. Rab Nawaz Jadoon


Assistant Professor
Department of Computer Sciences
COMSATS University, Islamabad
Abbottabad Campus
Jadoon956.wordpress.com
Jadoon.rabnawaz@gmail.com
Object Oriented Programming using JAVA Lab Manual – Page 3|193
Contents
Preface .......................................................................................................................................................... 6

Lab No. 1: Object Oriented Modeling ........................................................................................................... 8

Lab No. 2: Control Structures...................................................................................................................... 11

Lab No. 3: Classes, Objects, and Methods .................................................................................................. 19

Lab No. 4: Methods ..................................................................................................................................... 26

Lab No. 5: Method Overloading .................................................................................................................. 32

Lab No. 6: Arrays Application - I.................................................................................................................. 39

Lab No. 7: Arrays Application - II................................................................................................................. 44

Lab No. 8: String handling. .......................................................................................................................... 50

Lab No. 9: Inheritance ................................................................................................................................. 57

Lab No. 10: Inheritance, Overriding and Constructor Chaining ................................................................. 68

Lab No. 11: Polymorphism-I ...................................................................................................................... 79

Lab No. 12: Polymorphism-II ...................................................................................................................... 85

Lab No. 13: Abstract classes, interface, and inner classes-I....................................................................... 95

Lab No. 14: Abstract classes, interface, and inner classes-II...................................................................... 98

Lab No. 15: Abstract classes, interface, and inner classes-III................................................................... 102

Lab No. 16: Static Members and Functions ............................................................................................. 107

Lab No. 17: File Handling. ........................................................................................................................ 114

Lab No. 18: Exception Handling-I ............................................................................................................. 118

Lab No. 19: Exception Handling-II ............................................................................................................ 125

Lab No. 20: GUI-Programming-I ............................................................................................................... 134

Lab No. 21: GUI Programming-II .............................................................................................................. 146

Lab No. 22: JDBC-I .................................................................................................................................... 153

Object Oriented Programming using JAVA Lab Manual – Page 4|193


Lab No. 23: JDBC-II ................................................................................................................................... 159

Lab No. 24: JDBC-III .................................................................................................................................. 165

Lab No. 25:Multithreading-I...................................................................................................................... 171

Lab No. 26: Multithreading-II .................................................................................................................... 177

Lab No. 27: Special Lab Task - I ................................................................................................................. 182

Lab No. 28: Special Lab Task - II ................................................................................................................ 185

Lab No. 29: Special Lab Task - III ............................................................................................................... 188

Lab No. 30: Special Lab Task - IV ............................................................................................................... 185

Object Oriented Programming using JAVA Lab Manual – Page 5|193


Preface

The indispensable intention for writing the manual for Object Oriented Programming using JA-
VA is to impart inclusive guidance for the students to learn object oriented programming tech-
nique for developing software using JAVA. The inspiration at the rear is to spotlight on the prac-
tical phase of programming. To implement this objective it has been included couple of exam-
ples regarding each topic.

The manual provides complete programming guide for the students from beginning to some ad-
vanced level. The language is simple and stress-free to understand.

Each lab ends with some exercises for best practice at lab and for home too. This manual is basi-
cally intended for the students but it can also be used by any person who wants to get the
knowledge of Object Oriented Programming.

Object Oriented Programming using JAVA Lab Manual – Page 6|193


Lab No. 1
Object Oriented Modeling

Object Oriented Programming using JAVA Lab Manual – Page 7|193


Lab No. 1: Object Oriented Modeling
Objective:
To explore the concept behind Object Oriented Modeling.

Scope:
In completing this exercise, the students will be able to:
• Identify entities in a simple “personal banking” application domain.
• Identify attributes required to model these entities.
• Identify methods required to model these entities.
• Identify relationships among these entities.

A Case Study:
1. The Personal Banking Domain
In this exercise the students will investigate the different kinds of objects required to model the banking
domain. To make it simple, the scope of the model is limited to personal banking activities, i.e. excluding
business banking.
2. Brain-Storming
Consider a world in which people can save money into a bank. There may be different banks (e.g. Bank
Al-Habib, Allied Bank etc) and customers may have different activities with their banks.
• Write down the different kinds of objects which are involved in this “Personal banking” domain.
• Look at the objects that you put down above. Is/are there any object(s) that you chose not to in-
clude in your model? What are they? Why?
3. Customer
Depending on your brain-storming result in exercise above, you may have some Customer objects. Con-
sider a customer who can open bank accounts in a bank. Write down the list of attributes required to mod-
el the data components of a customer, (e.g. the name of the customer)
For each of these attributes:
• Would you model it as a class-level/object-level attribute and why?
• What will be the appropriate data type? (e.g. integer, floating point number, a string, etc.)
• Would you make this attribute visible to other objects and why?
• Would you hide this attribute from other objects and why?
• Write down the list of methods required to model the procedural component of a customer, i.e.
Operations/ behavior that a customer can perform. For each of these methods:
• Would you model it as a class-level/object-level method and why?
• Does the method need any input argument/ parameter? If yes, what is/are the data type(s) of
this/these parameter(s)?
• Does the method return any value? If yes, what is the appropriate return data type?

Object Oriented Programming using JAVA Lab Manual – Page 8|193


• Would you make the method visible/invisible to other objects? Why?

4. Bank Account
A bank account stores data about the amount of money that a customer saves in a bank. Write down the
list of attributes required to model a bank account. For each of these attributes:
• Should it be object/class-level and why?
• What is the appropriate data type? (E.g. integer, floating point number, a string, etc.)
• Would you make the attribute visible to the outside world and why?
• Write down the list of methods required to model a bank account. For each of these methods:
• Should it be object/class-level and why?
• Does the method need any input argument/ parameter? If yes, what is/are the data type(s) of
this/these parameter(s)?
• Does the method return any value? If yes, what is the appropriate return data type?
• Would you make the method visible/invisible to other objects? Why?
Consider the relationship between a bank account and a customer.
• Do you think this is a one-to-one, one-to-many, or many-to-many relationship? Why?
• If you need to model this relationship between a bank account and a customer, would you model
it as an attribute or method? Why and How?
• Would you make it an attribute/method of the bank account or the customer?
• What would be the data type of this attribute/method?
5. The Bank
A bank account stores data about the amount of money that a customer saves in a bank. Write down the
list of attributes and methods required to model a Bank. For each of this attributes/method:
• Would you model it as a class/object-level attribute/method? Why?
For each attribute:
• What is the appropriate data type?
• For each method:
• What is/are the required input argument(s)/parameter(s)?
• What is/are its/their data type(s)?
• What is the return data type (if any)?
• Consider the bank and bank accounts:
• Is there any relationship between a bank and bank accounts?
• Is it a one-to-one, one-to-many, or many-to-many relationship?
• How would you model this relationship?
• Consider the bank and customer:
• Is there any relationship between banks a customer?
Will you model this relationship? If yes, how? If you are going to have multiple banks in our domain
(e.g. Bank Al-Habib, Allied Bank etc), will it make a difference to your domain model? If you need to
make any change, how will you modify it?
Object Oriented Programming using JAVA Lab Manual – Page 9|193
Lab No. 2
Control structures

Object Oriented Programming using JAVA Lab Manual – Page 10|193


Lab No. 2: Control Structures
Objective:

Implementation of Control Structures (Selection, and Iterative statements)

Scope:
Sometimes we need to make a decision between two choices. The statements in by which we make this
decision are called conditional statements. We use loops to make one or more statements repeat for speci-
fied number of times. Clearly this have an importance when we wish to take more than one input from
user or do some calculations.

Example 1: This program is used to demonstrate the uses if-else condition.

Object Oriented Programming using JAVA Lab Manual – Page 11|193


Example 2: This program is used to demonstrate the uses switch-case.

Object Oriented Programming using JAVA Lab Manual – Page 12|193


Example 3: This program demonstrates either an input number is prime or not

Object Oriented Programming using JAVA Lab Manual – Page 13|193


Example 4: Following program that keeps reading numbers (integers) from user until input is 0, then
prints average, sum, maximum and minimum.

Object Oriented Programming using JAVA Lab Manual – Page 14|193


Exercises

Exercise 1:

Write a program that specifies whether a given number (x) falls in one of the following categories (give x
a value from the code, don't read from user):

Object Oriented Programming using JAVA Lab Manual – Page 15|193


• 0 to 9
• 10 to 19
• 20 to 29
• None of the categories
For example, if x = 5, program should print "0 to 10", and if x = 44 it should print "None".
Hint: use if statements with Boolean expressions combined using &&.

Exercise 2:

Write a program that reads two integers and prints their sum like the code below (text shown in boldface
is supposed to be user input).
Enter the first number: 3
Enter the second number: 4
The sum is 7

Exercise 3:

Write a program that asks the user to enter two numerical values (integers) and then select an operation
(addition, subtraction, multiplication and division) then prints the result based on operation selected. The
code below shows examples of the output (text shown in boldface is supposed to be user input).
Enter first number: 4
Enter second number: 2
1. Addition (+).
2. Subtraction (-).
3. Multiplication (*).
4. Division (/).
Enter operation number: 3
The result is 8

Exercise 4:

Write a program that reads 10 numbers from the user then prints out how many positive numbers and
negative numbers user has entered (consider 0 a positive number).

Homework

1. Modify calculation program in session 4 exercise 3 by adding the following question at the end of
the program:

Do you want to make another calculation?


1. Yes
2. No
Object Oriented Programming using JAVA Lab Manual – Page 16|193
Enter your option:
If user selects yes (by entering 1), program will ask him again to enter new two numbers and se-
lect operation, if user selects no (by entering 2), program exits. Use appropriate loop to accom-
plish this.

2. Write a program that asks the user to enter certain number, after that asks him to enter another 20
numbers, after entering them all, it prints out the number of occurrences of the first number. See
the below example (text shown in boldface is supposed to be user input).

Enter number to search for: 2


Enter a number: (20 times)
2 3 56 7 9 2 4 5 5 6 2 21 33 19 32 88 0 32 100 20
The number (2) occurred 3 times in your input.

Object Oriented Programming using JAVA Lab Manual – Page 17|193


Lab No. 3
Classes, Objects, and
Methods

Object Oriented Programming using JAVA Lab Manual – Page 18|193


Lab No. 3: Classes, Objects, and Methods
Objective:
• Understanding the concept of Object-Oriented programming.
• Introducing classes and objects and differences between them.
• Understanding class members and their properties.
• Calling methods.
Scope:
In JAVA, programmers concentrate on creating their own user defined classes and objects. Each class
contains data and data members and methods to facilitate the user how to kept data encapsulated manner
for the protection from the unauthorized access.

Example 1: This program demonstrates a simple class implementation.

class circle1{
Public static void main(String[] a){

Object Oriented Programming using JAVA Lab Manual – Page 19|193


} }

Example 2: This program demonstrates the private member of a class can’t be accessed from the outside
of the class which reports compile-time error..

Object Oriented Programming using JAVA Lab Manual – Page 20|193


Example 3: The following example shows the difference between static and non-static variables.
.

Object Oriented Programming using JAVA Lab Manual – Page 21|193


Example 4: The following example shows how to add two numbers using method calling.

Example 5: Method returns integer that contains the sum of two numbers.

Object Oriented Programming using JAVA Lab Manual – Page 22|193


Example 6: Demonstration of methods with BufferedReader class

Exercises:
Exercise 1:
Write a class Book with three data members BookId, Pages and Price. It also contains the follow-
ing member function:
• The get() method is used to input values
• The show() method is used to display values

Object Oriented Programming using JAVA Lab Manual – Page 23|193


• The set() method is used to set the values of data members using parameters
• The getPrice() method is used to return the value of price

Exercise 2:
Create a class building that has the public member floors,area, and occupants and a method
areaperperson()respectively that display the area per person for building. In the main() meth-
od create two instance of building called house and office and display the area per person by di-
vision of area/occupants.

Homework:
1) Write a class Result that contains roll no, name and marks of three subjects. The marks
are stored in an array of integers. The class also contains the following member functions.
• The input() method is used to input values
• The show() method is used to display values
• The total() returns the total marks a student
• The avg() method returns the average marks of a student
2) Create a class rectangle. The class has attributes length and width each of
which defaults to 1. It has member function that calculates the perimeter and the area of
the rectangle. It has set() and get() functions for both length and width.
The set() function should verify that length and width are each floating point
numbers larger than 0.0 and less than 20.0.

Object Oriented Programming using JAVA Lab Manual – Page 24|193


Lab No. 4
Methods

Object Oriented Programming using JAVA Lab Manual – Page 25|193


Lab No. 4: Methods
Objective:
To implements the concepts of Methods.

Scope:

A Java method is a collection of statements that are grouped together to perform an operation. When you
call the System.out.println method, for example, the system actually executes several statements in order
to display a message on the console. Now you will learn how to create your own methods with or without
return values, invoke a method with or without parameters, overload methods using the same names, and
apply method abstraction in the program design.

Example 1: This program demonstrates the use of methods.

Object Oriented Programming using JAVA Lab Manual – Page 26|193


Object Oriented Programming using JAVA Lab Manual – Page 27|193
Example 2: This program demonstrates the use of methods

Object Oriented Programming using JAVA Lab Manual – Page 28|193


Example 3: This program demonstrates the use of methods.

Object Oriented Programming using JAVA Lab Manual – Page 29|193


Exercises:

Exercise 1:

Write a program to generate a Fibonacci series by creating fibonacci class. The result become like

1 1 2 3 5 8 and so on

Homework:

1) Write a class Car that contains the following attributes:

The name of car

The direction of car (E, W, N, S)

The position of car (from imaginary zero point)

The class has the following methods:

• A constructor to initialize the attributes


• Turn() method to change the direction of car to one step right side (i.e. if the direction is to E, it
should be changed to S and so on)
• Overload the turn() method to change the direction to any side directly. It should accept the
direction as parameter.
• Move() method to change the position of car away from zero point. It should accept the distance
as parameter.

Object Oriented Programming using JAVA Lab Manual – Page 30|193


Lab No. 5
Method Overloading

Object Oriented Programming using JAVA Lab Manual – Page 31|193


Lab No. 4: Method Overloading
Objective:
• Defining constructors
• Understanding method / constructor overloading.
• Creating and using packages
Scope:
Overloading means to have more than one constructors or methods having same name. There are more
than one way to discriminate between methods, including name and number and type of parameters. To
see how parameters can help in overloading, consider the following examples.
Packaging is a way to organize files when a project consists of multiple modules. It also helps resolve
naming conflicts when different packages have classes with the same names.
Packages access level also allows you to protect data from being used by the non-authorized classes.

Example 1: Write a Java Program to define a class, describe its constructor, overload the Constructors and
instantiate its object

Object Oriented Programming using JAVA Lab Manual – Page 32|193


Example 2: Write a Java Program to define a class, define instance methods and overload them and use
them for dynamic method invocation.

Object Oriented Programming using JAVA Lab Manual – Page 33|193


Example 3: Implementation of constructor overloading

Example 4: This code generates error message.

To better understand classes and objects, lets analyze a well-known statement we've been using repeated-
ly:
System.out.println("Hello World");
System is a name of a class, inside System class, there is a public and static member (object) of class
PrintWriter, the name of this object is out. Inside PrintWriter class, there is a public, non-static method
called println that has several overloads.

Exercises:
Exercise 1:
• Write a class that represents triangle named Triangle, the class must have the following-
members:
• private double height;//Height
• private double base;//Base length
• public Triangle(double h, double b);//Constructor
• public void setHeight(double x);//Sets height
• public double getHeight();//Gets height
• public void setBase(double x);//Sets base length

Object Oriented Programming using JAVA Lab Manual – Page 34|193


• public double getBase();//Gets base length
• public double getArea();//Returns the area of the triangle

Exercise 2:
Write a class Employee that represents an employee of some organization, the class should con-
tain the following members:
• private int id;//Employee id
• private String name;//Employee name
• private int type;//1 = employee, 2 = manager
• private double baseSalary;//Base salary
• public Employee(int _id, String _name);//Constructor
• public void setID(int x);//id mutator
• public void setName(int x);//name mutator
• public intgetID();//id accessor
• public String getName();//name accessor
• public double getSalary();
• //if manager, add 10% to base salary
• public void setBaseSalary(double bs);//sets base salary.

Creating and using Packages:

A package is the collection of interfaces and classes. It is an important aspect one should be aware of,
packaging means putting two or more classes/interfaces in the same package by stating package name
before declaring class (and also exceptions). When two classes are in the same package, it is possible to
access any one of them from the other, for example, if we have a class named Student that represents a
student, another class named Main to run a program that manages student information, we can access
Student class from Main class and define several objects of it if we use the following statement before
each class declaration:
packagestudentinfo;
In NetBeans IDE, there is no need to manually write the above statement, by adding new class toany
package of your project, that class is automatically declared as a part of that package. Following Figure-
shows packages and classes in NetBeans IDE project explorer.

Object Oriented Programming using JAVA Lab Manual – Page 35|193


To access a class from its package we simply provide package name followed by dot '.' then de-
sired class name. For example, we can access Main class show in above Figure by calling it in
the following statement:
linkedlist.Main

Example 5: Write a Java program to implement the concept of importing classes from user defined pack-
age.

Object Oriented Programming using JAVA Lab Manual – Page 36|193


Object Oriented Programming using JAVA Lab Manual – Page 37|193
Lab No. 6
Arrays Application-I

Object Oriented Programming using JAVA Lab Manual – Page 38|193


Lab No. 6: Arrays Application-I

Objective:
To implements the concept of one dimensional Array.

Scope:
Arrays are special data types that let us store specified number of variables from the same type using one
variable name. Arrays are an indexed data type, which means they are storing different elements discrim-
inating between them using unique index for each one. Declaring and using an array in Java is similar to
declaration of any variable; you have to specify data type and name, in addition to this, you have also to
specify the length of the array before using it.

Example 1: This program is used to calculate the sum of array values.

Object Oriented Programming using JAVA Lab Manual – Page 39|193


Example 2: This program demonstrates how to reverse the array values.

Object Oriented Programming using JAVA Lab Manual – Page 40|193


Example 3: This program demonstrates how to find Maximum and minimum value in arrays.

Object Oriented Programming using JAVA Lab Manual – Page 41|193


Exercises

Exercise 1:

Write a program using arrays to solve the problem. The problem is to read 10 numbers, get the average of
these numbers, and find the number of the items greater than the average.

Exercise 2:

Count the occurrences of each letter in the array. To do so, create an array, say counts, of 26 int values,
each of which counts the occurrences of a letter. That is counts[0] counts the number of a’s, counts[1]
counts the number of b’s, and so on.

Exercise 3:

Write a program that reads 10 numbers in an array, write a method which will return the sort array.

Homework:

1. (Eliminate duplicates) Write a method that returns a new array by eliminating the duplicate values in
the array. Write a JAVA program that reads in at least ten integers, invokes the method, and displays
the results.

Object Oriented Programming using JAVA Lab Manual – Page 42|193


Lab No. 7
Arrays Application-II

Object Oriented Programming using JAVA Lab Manual – Page 43|193


Lab No. 7: Arrays Application - II

Objective:
To implements the concepts of Multidimensional dimensional Arrays.

Scope:

Up to this point, we were storing elements in linear manner, that is, we provide one index to locate the
element in one-dimensional structure. Java also provides arrays of arrays, this means we create an array,
and each element in that array is an array itself. These arrays are also called multidimensional arrays.

Example 1: Two dimensional arrays are common in representing matrices, for example, we can write a
program that adds two matrices (remember that matrices must have same number of rows and same num-
ber of columns when it comes to addition).

Object Oriented Programming using JAVA Lab Manual – Page 44|193


Object Oriented Programming using JAVA Lab Manual – Page 45|193
Example 2: This program demonstrates how to pass Two Dimensional arrays to methods.

Object Oriented Programming using JAVA Lab Manual – Page 46|193


Exercises

Exercise 1:

Write a program that reads 16 integers from the user, stores them in 5 by 4 matrix, the last row of the ma-
trix should contain the sums of the columns (see figure 9.2) calculated by your program. Then the whole
matrix is printed.

Exercise 2:

Write a Java program to multiply two matrices of 5x5. Suggest the data.

Exercise 3:

(Largest row and column) Write a program that randomly fills in 0s and 1s into a 4-by-4 matrix, prints the
matrix, and finds the first row and column with the most 1’s. Here is a sample input/output of the pro-
gram:

Object Oriented Programming using JAVA Lab Manual – Page 47|193


0011

0011

1101

1010

The largest row index: 2

The largest column index: 2

Homework:

1. (Locate the largest element) Write the following method that returns the location of the largest ele-
ment in a two-dimensional array.

The return value is a one-dimensional array that contains two elements. These two elements indicate the
row and column indices of the largest element in the two-dimensional array. Write a test program that
prompts the user to enter a two dimensional array and displays the location of the largest element in the
array.

Enter the number of rows and columns of the array: 3 4

Enter the array:

23.5 35 2 10

4.5 3 45 3.5

35 44 5.5 9.6

The location of the largest element is at (1, 2)

Object Oriented Programming using JAVA Lab Manual – Page 48|193


Lab No. 8
String Handling

Object Oriented Programming using JAVA Lab Manual – Page 49|193


Lab No. 8: String Handling
Objective:

To implements the concepts of Strings in Java.

Scope:

Strings, which are widely used in Java programming, are a sequence of characters. In the Java strings are
objects and provide the String class to create and manipulate Strings. String class is immutable; so that
once it is created a String object cannot be changed.

Example 1: This program demonstrates either an input string is Palindrome or not.

Object Oriented Programming using JAVA Lab Manual – Page 50|193


Example 2: The following class, Filename, illustrates the use of lastIndexOf() and substring() to isolate
different parts of a file name.

Object Oriented Programming using JAVA Lab Manual – Page 51|193


Object Oriented Programming using JAVA Lab Manual – Page 52|193
Example 3: Following program will sort the names in ascending order

Object Oriented Programming using JAVA Lab Manual – Page 53|193


Exercises:

Exercise 1:

The problem is to write a program that prompts the user to enter a string and counts the number of occur-
rences of each letter in the string regardless of case.

Object Oriented Programming using JAVA Lab Manual – Page 54|193


Exercise 2:

(Checking substrings) You can check whether a string is a substring of another string by using the in-
dexOf method in the String class. Write your own method for this function. Write a program that prompts
the user to enter two strings, and check whether the first string is a substring of the second.

Exercise 3:

(Counting the letters, digits, consonants and vowels in a string) Write a method that counts the number of
letters, digits, consonants and vowels in a string.

Write a test program that prompts the user to enter a string and displays the number of letters, digits, con-
sonants and vowels in the string.

Homework:

(Checking password) Some Websites impose certain rules for passwords. Write a method that checks
whether a string is a valid password. Suppose the password rule is as follows:

■ A password must have at least eight characters.

■ A password consists of only letters and digits.

■ A password must contain at least two digits.

Write a program that prompts the user to enter a password and displays "Valid Password" if the rule is
followed or "Invalid Password" otherwise.

Object Oriented Programming using JAVA Lab Manual – Page 55|193


Lab No. 9
Inheritance

Object Oriented Programming using JAVA Lab Manual – Page 56|193


Lab No. 9: Inheritance

Objective:
To implements the concepts of Inheritance.

.Scope:

Inheritance enables you to define a general class (i.e., a superclass) and later extend it to more specialized
classes (i.e., subclasses). You use a class to model objects of the same type. Different classes may have
some common properties and behaviors, which can be generalized in a class that can be shared by other
Classes. You can define a specialized class that extends the generalized class. The specialized classes in-
herit the properties and methods from the general class.

Example 1: This program demonstrates a generalized super class i.e. SimpleGeometricObject and a Spe-
cialized subclass CircleFromGeometricObject. All geometric objects such as a circle or a rectangle may
have the property of color but only circles has radius. The sub class has therefore a data member radius
but also accesses the data member color of the superclass. Furthermore the setColor() and getColor()
methods of the superclass are also accessed by the subclass.

Object Oriented Programming using JAVA Lab Manual – Page 57|193


Example 2:This program demonstrates inheritance with four classes i.e. EmployeeTest,
BasePlusCommissionEmployee, CommissionEmployee and Employee respectively. Em-
ployeeTest is the main class with the main method. BasePlusCommissionEmployee is the
subclass of CommissionEmployee. CommissionEmployee is the subclass of Employee
class. An object of the BasePlusCommissionEmployee subclass is made in the main method of
EmployeeTest class. Since BasePlusCommissionEmployee is the base class of all classes in
this example therefore its object can access its members as well as members of its super classes.

Object Oriented Programming using JAVA Lab Manual – Page 58|193


Object Oriented Programming using JAVA Lab Manual – Page 59|193
Object Oriented Programming using JAVA Lab Manual – Page 60|193
Object Oriented Programming using JAVA Lab Manual – Page 61|193
Object Oriented Programming using JAVA Lab Manual – Page 62|193
Object Oriented Programming using JAVA Lab Manual – Page 63|193
Object Oriented Programming using JAVA Lab Manual – Page 64|193
The outputs are as follows

Object Oriented Programming using JAVA Lab Manual – Page 65|193


Exercises:

Exercise 1:

Create a new class RectangleFromSimpleGeometricObject in example 1 and extend it with


SimpleGeometricObject class. Create an object for this class in the TestCircleRectangle
class with a constructor receiving one parameter of color . Add a method setWidthHeight() which accepts
two double parameters width and height. Add another method getWidthHeight which returns width and
height. Also call the setColor() method of the superclass from the constructor and call the getColor()
method in TestCircleRectangle class for RectangleFromSimpleGeometricObject class.

Exercise 2:

Create a new method CalculateCommission in the CommissionEmployee class. This method


calculates the commission based on the value of commissionRate data member.

Homework

Create a new class SalariedEmployee that extends from class Employee and overrides the meth-
od earnings( ) of class Employee to calculate the fixed monthly salary of each employee. Cre-
ate object of SalariedEmployee class in EmployeeTest class(i.e, main class) to set the
record for new employee and print it using toString()method.

Object Oriented Programming using JAVA Lab Manual – Page 66|193


Lab No. 10
Inheritance, overriding and
constructor chaining

Object Oriented Programming using JAVA Lab Manual – Page 67|193


Lab No. 10: Inheritance, Overriding and Constructor chaining

Objective:
To implements the concepts of Inheritance, overriding and constructor chaining.

Scope:
Inheritance enables specialized classes (i.e., subclasses) to access members of a general class (i.e., a su-
perclass) which can be controlled in many ways using techniques like constructor chaining or overriding.

Example 1: This program demonstrates inheritance with four classes i.e. TestCircleRectangle,
SimpleGeometricObject, CircleFromSimpleGeometricObject and Rectangle-
FromSimpleGeometricObject respectively. TestCircleRectangle is the main class with
the main method. SimpleGeometricObject is the superclass of CircleFromSimpleGe-
ometricObject and RectangleFromSimpleGeometricObject.
An object each for CircleFromSimpleGeometricObject and RectangleFromSimpleGe-
ometricObject is made in the main method of TestCircleRectangle class. Both of these ob-
jects are then used to call their members as well as members of the base class SimpleGeometricOb-
ject.

Object Oriented Programming using JAVA Lab Manual – Page 68|193


Object Oriented Programming using JAVA Lab Manual – Page 69|193
Object Oriented Programming using JAVA Lab Manual – Page 70|193
Object Oriented Programming using JAVA Lab Manual – Page 71|193
Object Oriented Programming using JAVA Lab Manual – Page 72|193
Object Oriented Programming using JAVA Lab Manual – Page 73|193
Example 2: This program demonstrates overriding in inheritance. To override a method, the method must
be defined in the subclass using the same signature and the same return type as in its superclass. Overrid-
ing means to provide a new implementation for a method in the subclass. In the following program the
method name() of the Employee class overrides the method name() of the Person class

Object Oriented Programming using JAVA Lab Manual – Page 74|193


Example 3: Whenever an object of a class is created the constructor is called. In case of inheritance when-
ever a constructor of a subclass is called, for example object creation, the constructor of the superclass
executes first and then the subclass constructor executes. This phenomenon is called constructor chaining.
The following program demonstrates constructor chaining.

Object Oriented Programming using JAVA Lab Manual – Page 75|193


Exercises:
Object Oriented Programming using JAVA Lab Manual – Page 76|193
Exercise 1:

Consider the program from Example1. Create a toString() method in both subclasses
RectangleFromSimpleGeometricObject and CircleFromSimpleGeometricObject
such that these two methods in subclasses overrides the toString() method in the superclass
SimpleGeometricObject . Cal the toString() method in the main method of
TestCircleRectangle class from both objects of the subclasses.

Exercise 2:

Create three classes Food, Fruit and Apple in such a way that class Apple extends Fruit class
and Fruit class extends class Food. Create a constructor in each class containing only a statement
to print current class name. Call all the three constructors using constructor chaining. For reference use
Example 3.

Homework:

Add a new method drawShape( ) in SimpleGeometricObject (i.e., superclass) Class and over-
rides this method into subclass i.e., RectangleFromSimpleGeometricObject and Cir-
clefromGeometricObject to draw a specific shape according to subclass specification.

Object Oriented Programming using JAVA Lab Manual – Page 77|193


Lab No. 11
Polymorphism -I

Object Oriented Programming using JAVA Lab Manual – Page 78|193


Lab No. 11: Polymorphism-I

Objective:
In these labs we will discuss and implement method overriding and polymorphism, which are one of the
key features of Object oriented programming (OOPs). Moreover the importance of these concepts would
be seen in problem solving in Java.

Scope:
In inheritance we have seen the concept of super classes and sub classes. If a class inherits a method from
its super class, then there is a chance to override the method provided that it is not marked final. The ben-
efit of overriding is: ability to define a behavior that's specific to the sub class type. Which means a sub-
class can implement a parent class method based on its requirement. In object oriented terms, overriding
means to override the functionality of any existing method.

Example 1: Let us look at an example.

Object Oriented Programming using JAVA Lab Manual – Page 79|193


Example 2: Consider the following example

Object Oriented Programming using JAVA Lab Manual – Page 80|193


Object Oriented Programming using JAVA Lab Manual – Page 81|193
This program will throw a compile time error since b's reference type Animal doesn't have a method by
the name of bark.

Using the super keyword:

When invoking a superclass version of an overridden method the super keyword is used. Con-
sider the following example:

Object Oriented Programming using JAVA Lab Manual – Page 82|193


Object Oriented Programming using JAVA Lab Manual – Page 83|193
Lab No. 12
Polymorphism -II

Object Oriented Programming using JAVA Lab Manual – Page 84|193


Lab No. 12: Polymorphism-II

Objective:
To implement the concept of Polymorphism

Scope:
Polymorphism is the ability of an object to take on many forms, it is a Greek word where poly means
many and morphism means form. The most common use of polymorphism in OOP occurs when a parent
class reference is used to refer to a child class object.
It is important to know that the only possible way to access an object is through a reference variable. A
reference variable can be of only one type. Once declared the type of a reference variable cannot be
changed. The reference variable can be reassigned to other objects provided that it is not declared final.
The type of the reference variable would determine the methods that it can invoke on the object. A refer-
ence variable can refer to any object of its declared type or any subtype of its declared type. A reference
variable can be declared as a class or interface type

Example 1: consider the following classes:

Object Oriented Programming using JAVA Lab Manual – Page 85|193


Now because of inheritance, it is possible to write a single method that can accept an object of any of the
above classes as parameter and call the print method polymorphically like:

Object Oriented Programming using JAVA Lab Manual – Page 86|193


Example 2: Consider the following inheritance diagram:

Object Oriented Programming using JAVA Lab Manual – Page 87|193


❖ Suppose we have the following:

Shape s = new Circle();


s.draw();

❖ The question is which draw() method will be called?

❖ Because of polymorphism, the draw() of the actual object (not necessarily that of the reference
type) will be called. Thus, it is the draw() method of the Circle object that is called.

Here is the demonstration of this idea

Object Oriented Programming using JAVA Lab Manual – Page 88|193


Object Oriented Programming using JAVA Lab Manual – Page 89|193
Example 3: Suppose we define a subclass, say ResearchAssistant for the class Student in Example 1 as
follows:

It is now possible to call the describe() with an object of type ResearchAssistant without any change to
the method as shown below. The describe() method is said to be extensible – meaning the functionality
can be added to a code simply by inheriting a new data type from the base class.

Whereas the addition of ResearchAssistant class and its calling is shown below

Object Oriented Programming using JAVA Lab Manual – Page 90|193


Exercises:

Exercise 1:
Consider the following class
Public class father
{
int age;
father(int x)
{
age=x;
}
public void Iam()
{
System.out.println(“I AM FATHER and My AGE = %d”, age);
}
}

Object Oriented Programming using JAVA Lab Manual – Page 91|193


Derive two sub classes son and daughter from the above class and override the method Iam() in each of
the subclass and prints an appropriate message in each overridden method. You should also define a suit-
able constructor for each of these sub classes.
Now write a test class to check the functionality of above example. In main() method create three objects
one for each father, son and daughter respectively and call their Iam() method non polymorphically.
Then create an array of father references of size ten and initialize this array randomly with the objects of
daughter and son. Then traverse this array and call the Iam() method polymorphically and display the re-
sults.

Exercise 2:

ShapeHierarchy: Implement the Shape hierarchy shown in Fig. 1 givenbelow. Each TwoDimensional-
Shape should contain method getArea to calculate the area of the two-dimensional shape. Each ThreeDi-
mensionalShape should have methods getArea and getVolume to calculate the surface area and volume,
respectively, of the three-dimensional shape. Create a program that uses an array of Shape references to
objects of each concrete class in the hierarchy. The program should print a text description of the object to
which each array element refers. Also, in the loop that processes all the shapes in the array, determine
whether each shape is a TwoDimensionalShape or a ThreeDimensionalShape. If it’s a TwoDimensional-
Shape, display its area. If it’s a ThreeDimensionalShape, display its area and volume.

Figure 1: Shape hierarchy

Exercise 3:
Modify the exercise 1 and use a Random class to generate the random number between 1 to the length of
the array. Then get the object of an array at indexed equal to the random number generated and call its
functionality.

Homework:

Object Oriented Programming using JAVA Lab Manual – Page 92|193


1. Define a base class called Worker that has two derived classes: Employee and Manager. For
workers, we only have simple attributes such as their names and working hours. For employees
and managers, each has specific attributes unique to the class. Employees have attributes such as
the name of the department that they are working with, and their salaries. Managers have attrib-
utes such as the number of managed employees and the number of projects that they’re in charge.
Also, define another class called Project that has attributes such as the name and the current pro-
gress (in %) of the project.

(1) Write the corresponding constructors that initialize the attributes for classes.

(2) Write the corresponding member functions to set and get the attributes for classes.

(3) Finally, test the classes in a main program. In the test program, you should dynamically allo-
cate some employees and managers, print their corresponding information.

2. A company pays its employees on a weekly basis. The employees are of four types: Sala-
ried employees are paid a fixed weekly salary regardless of the number of hours worked,
hourly employees are paid by the hour and receive overtime pay (i.e., 1.5 times their
hourly salary rate) for all hours worked in excess of 40 hours, commission employees are
paid a percentage of their sales and base-salaried commission employees receive a base
salary plus a percentage of their sales. For the current pay period, the company has decid-
ed to reward salaried-commission employees by adding 10% to their base salaries. The
company wants to write an application that performs its payroll calculations polymorphi-
cally.

Figure 2: Employee hierarchy

Object Oriented Programming using JAVA Lab Manual – Page 93|193


Lab No. 13
Abstract classes, Interfaces, and
Inner classes-I

Object Oriented Programming using JAVA Lab Manual – Page 94|193


Lab No. 13: Abstract classes, Interface and Inner classes - I

Objective:
To implement the concept of Abstract classes, Interface and Inner classes

Scope:
An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract
classes cannot be instantiated, but they can be sub classes. When an abstract class is sub-classes, the sub-
class usually provides implementations for all of the abstract methods in its parent class.

Example 1: The Following program implement the concept of Abstract classes and method

Object Oriented Programming using JAVA Lab Manual – Page 95|193


Exercises:
Exercise 1:
Create an abstract class with at least one method, in its own package. Create a class in a separate package. Add
a protected inner class that implements the interface. In a third package, inherit from your class and, inside a
method, return an object of the protected inner class, up-casting to the abstract class during the return.
Homework:

Create an Abstract Class named Restaurant


Create a function/method that will print the name of the restaurant when called.
Create an abstract function/method named total price
Create an abstract function/method named menu items
Create an abstract function/method name location
Create a Class called McDonalds that extends Restaurant
Implement all abstract methods
Add logic so that the total price method/function will give the total price of the meal including a 6% tax
Add a method that returns a Boolean named hasPlayPlace, which returns true when this location has a play
place
Create a Constructor that will set the name of the Mcdonalds, location, and hasPlayPlace

Object Oriented Programming using JAVA Lab Manual – Page 96|193


Lab No. 14
Abstract classes, Interfaces, and
Inner classes-II

Object Oriented Programming using JAVA Lab Manual – Page 97|193


Lab No. 14: Abstract classes, Interface and Inner classes-II

Objective:

To implement the concept of Abstract classes, Interface and Inner classes

Scope:

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the
abstract methods of the interface. An interface is not a class. Writing an interface is similar to writing a
class, but they are two different concepts. A class describes the attributes and behaviors of an object. An
interface contains behaviors that a class implements.

Example 1: The Following program implements the concept of Interfaces

Object Oriented Programming using JAVA Lab Manual – Page 98|193


Example 2: The Following program implements the concept of Interfaces

Object Oriented Programming using JAVA Lab Manual – Page 99|193


Exercises:
Exercise 1:

Create three interfaces, each with two methods. Inherit a new interface from the three, adding a new
method. Create a class by implementing the new interface and also inheriting from a concrete class. Now
write four methods, each of which takes one of the four interfaces as an argument. In main( ), create an
object of your class and pass it to each of the methods.
Homework:

1. Consider the four core interfaces, Set, List, Queue, and Map. For each of the following four assign-
ments, specify which of the four core interfaces is best-suited, and explain how to use it to implement
the assignment.
1. Whimsical Toys Inc (WTI) needs to record the names of all its employees. Every month,
an employee will be chosen at random from these records to receive a free toy.
2. WTI has decided that each new product will be named after an employee but only first
names will be used, and each name will be used only once. Prepare a list of unique first
names.
3. WTI decides that it only wants to use the most popular names for its toys. Count up the
number of employees who have each first name.
4. WTI acquires season tickets for the local lacrosse team, to be shared by employees.
5. Create a waiting list for this popular sport.

Object Oriented Programming using JAVA Lab Manual – Page 100|193


Lab No. 15
Abstract classes, Interfaces, and
Inner classes-III

Object Oriented Programming using JAVA Lab Manual – Page 101|193


Lab No. 15: Abstract classes, Interface and Inner classes-III

Objective:
To implements the concepts of Inner classes.

Scope:
Inner classes nest within other classes. A normal class is a direct member of a package. Static member
class is a static member of a class. Like any other static method, a static member class has access to all
static methods of the parent, or top-level, class. Like a static member class, a member class is also defined
as a member of a class. Unlike the static variety, the member class is instance specific and has access to
any and all methods and members; even the parent's this reference. Local classes are declared within a
block of code and are visible only within that block, just as any other method variable.

Example 1: The Following program implements the concept of Inner classes

Object Oriented Programming using JAVA Lab Manual – Page 102|193


Object Oriented Programming using JAVA Lab Manual – Page 103|193
Example 2: Following is the implementation of Anonymous class

Object Oriented Programming using JAVA Lab Manual – Page 104|193


Exercises:

Exercise 1:

Create an interface with at least one method, in its own package. Create a class in a separate package. Add
a protected inner class that implements the interface. In a third package, inherit from your class and, in-
side a method, return an object of the protected inner class, up-casting to the interface during the return. .

Exercise 2:

Create an interface with at least one method, and implement that interface by defining an inner class with-
in a method, which returns a reference to your interface. .

Homework:

1. Define a class structure (abstract classes, regular classes, methods, private fields, interfaces) which
implement pizzas, pizza sub-types, crust types, topping sets and (most importantly) the comparator
objects representing different people's preferences about pizzas;

Define a list of pizzas to be compared and ranked, preferably not a fixed list, but one which you can
change "externally" (see below);

Define the individual people/comparator objects to be used to rank the pizzas;


Run the ranking algorithm and print out the sorted list of pizzas with their scores (it might be good to
print out individual people's rank lists, too, so that you can tell that the algorithm is working proper-
ly).

You should make your own design decisions about class structure, although of course I will be avail-
able for help and discussion, and also design your own graphical or command-line interface. But
please try to take the following issues into account:

Object Oriented Programming using JAVA Lab Manual – Page 105|193


Lab No. 16
Static members and Functions

Object Oriented Programming using JAVA Lab Manual – Page 106|193


Lab No. 16: Static members and Functions

Objective:
To implements the concepts of static members and functions.

Scope:
After introducing static data members as you may recall, a static member is not duplicated for each object
of the class; rather a single data item is shared by all objects of a class. For better understanding some ex-
amples are given below.

Example 1: This program demonstrates the use of static member shared by some objects.

Object Oriented Programming using JAVA Lab Manual – Page 107|193


Object Oriented Programming using JAVA Lab Manual – Page 108|193
Example 2: This program demonstrates the use of static member and static function in a class.

Object Oriented Programming using JAVA Lab Manual – Page 109|193


Example 3: This program demonstrates the Printer sharing among various faculty members with the use
of static member in a class.

Object Oriented Programming using JAVA Lab Manual – Page 110|193


Output:

Exercises:

Exercise 1:

Create a SavingsAccount class and use a static data member to contain the annualInterest for
each of the savors. Each member of the class contains a private data member savingbalance
indicating the amount the saver currently has deposited. Provide a monthlyInterest() member
function that calculate the monthly interest by multiplying the balance by annualInterest by 12;
Object Oriented Programming using JAVA Lab Manual – Page 111|193
this interest should be added to the savingbalance. Provide a static member function
modifyInterest() that sets the static annualInerest to a new value.

Write a driver program to test class SavingAccount and instantiate two objects saver1 &
saver2 with balance of $30000 and $50000 respectively. Set annual interest 5% then calculate the
monthly interest and show the new balance for each saver.

Exercise 2:

Write a static method equalize() that takes two arrays of integers as arguments and returns true if they
contain the same number of elements and all corresponding pairs of elements are equal, and false other-
wise.

Exercise 3:

Write a static method Triangle_Test() that takes three double values as arguments and returns true if
they could be the sides of a triangle (none of them is greater than or equal to the sum of the other two).

Homework

Write a program in JAVA to show a delegate report regarding the printer usage of three departments. Re-
port consists of total pages has been taken by each department and total pages taken by each individual
faculty member. At the end of each month how many pages in total has been taken from the printer.

Report should look like as:

Department of Computer Science

Total # of Pages taken:????

Faculty member 1 has taken:????

Faculty member 2 has taken:???? And so on

Department of Mathematics

Total # of Pages taken:????

Faculty member 1 has taken:????

Faculty member 2 has taken:???? And so on

Object Oriented Programming using JAVA Lab Manual – Page 112|193


Lab No. 17
File Handling

Object Oriented Programming using JAVA Lab Manual – Page 113|193


Lab No. 17: File Handling

Objective:
To implement the concepts Reading from text file using input output stream.

Scope:
Standard streams are pre-connected input and output communication channels between a computer pro-
gram and its environment when it begins execution. The three I/O connections are called standard in-
put, standard output & standard error. We can use input stream in that scenario to read/write content from
file.

Example 1: There will be another program which demonstrates the use InputStreamReader to read stand-
ard input stream from file with buffer reader

Object Oriented Programming using JAVA Lab Manual – Page 114|193


Example 2: This program demonstrates How to write to file in Java File Output stream.

Object Oriented Programming using JAVA Lab Manual – Page 115|193


Exercises:

Exercise 1: Open a text file so that you can read the file one line at a time. Read each line as a String and
place that String object into a Linked List. Print all of the lines in the Linked List in reverse order.

Exercise 2: Modify Exercise 1 so that the name of the file you read is provided as a command-line argu-
ment.

Exercise 3: Open a text file so you can write text into it. Write the lines in the Array List, along with line
numbers (do not attempt to use the Line Number classes), out to the file.

Exercise 4: Modify Exercise 2 to force all the lines in the Array List to uppercase and send the results to
output file.

Homework:

1. Text 1= “Today is Thursday and it is a bright sunny day. I am the student of software engineer-
ing”
Text 2= “we need help”?
Write a program that should create a text file with a name OOPs in D:\ drive and store the above
mention text of text 1 in file then add above mention text of Text 2 in the same file in reverse or-
der.

2. Write a Java application that will be able to add, subtract, multiply, divide, compare, convert to
floating point, reduce to its lowest terms, and find absolute value for rational numbers.

Your program should be written in Object Oriented Programming style. It should read a file
called input.txt that contains a pair of rational numbers to a line.
(NOTE: the line may contain incorrect input). It should parse each line to retrieve two rational
numbers and perform operations on them. Rational numbers will be separated by “and”. The re-
sults must be written to a file called results.txt.

Object Oriented Programming using JAVA Lab Manual – Page 116|193


Lab No. 18
Exception Handling-I

Object Oriented Programming using JAVA Lab Manual – Page 117|193


Lab No. 18: Exception Handling-I
Objective:
Introduction to Exception Handling. The Exception Hierarchy in java.

Scope:
An Exception can be anything which interrupts the normal flow of the program. When an excep-
tion occurs program processing gets terminated and doesn’t continue further. In such cases we
get a system generated error message. The good thing about exceptions is that they can be han-
dled. Exceptions are conditions within the code. A developer can handle such conditions and
take necessary corrective actions.

Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of
the Throwable class. Other than the exception class there is another subclass called Error which is de-
rived from the Throwable class.

Errors are not normally trapped form the Java programs. These conditions normally happen in case of
severe failures, which are not handled by the java programs. Errors are generated to indicate errors gen-
erated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot re-
cover from errors. The Exception class has two main subclasses: IOException class and RuntimeExcep-
tion Class.

Object Oriented Programming using JAVA Lab Manual – Page 118|193


Example 1: The following programs handle an exception:

Example 2: Implementation of multiple Catch blocks:

Object Oriented Programming using JAVA Lab Manual – Page 119|193


Object Oriented Programming using JAVA Lab Manual – Page 120|193
Example 3: Implementation of Nested try catch:

Object Oriented Programming using JAVA Lab Manual – Page 121|193


Object Oriented Programming using JAVA Lab Manual – Page 122|193
Homework:

1. Write a program that prompts the user to read two integers and displays their sum. Your program
should prompt the user to read the number again if the input is incorrect.

2. Write a program that meets the following requirements:


■ Create an array with 100 randomly chosen integers.
■ Prompts the user to enter the index of the array, and then displays the corresponding element value.
If the specified index is out of bounds, display the message Out of Bounds.

3. Write a program that causes the JVM to throw an OutOfMemoryError and catches and handles this
error.

Object Oriented Programming using JAVA Lab Manual – Page 123|193


Lab No. 19
Exception Handling-II

Object Oriented Programming using JAVA Lab Manual – Page 124|193


Lab No. 19: Exception Handling-II

Objective:
Introduction to Exception Handling. The Exception Hierarchy in java.

Scope:
An Exception can be anything which interrupts the normal flow of the program. When an excep-
tion occurs program processing gets terminated and doesn’t continue further. In such cases we
get a system generated error message. The good thing about exceptions is that they can be han-
dled. Exceptions are conditions within the code. A developer can handle such conditions and
take necessary corrective actions.

Example 1: Implementation throwing an exception

Object Oriented Programming using JAVA Lab Manual – Page 125|193


Example 2: Implementation throwing an IOException with normal flow.

Example 3: Implementation throwing a runtime Exception.

Object Oriented Programming using JAVA Lab Manual – Page 126|193


Example 4: To demonstrate using our user-defined exception, the following CheckingAccount class con-
tains a withdraw() method that throws an InsufficientFundsException.

Object Oriented Programming using JAVA Lab Manual – Page 127|193


Example 5: The following BankDemo program demonstrates invoking the deposit() and withdraw()
methods of CheckingAccount.

Object Oriented Programming using JAVA Lab Manual – Page 128|193


Object Oriented Programming using JAVA Lab Manual – Page 129|193
Example 6: Java finally example where exception doesn't occur.

Example 7: Java finally example where exception occurs and not handled.

Object Oriented Programming using JAVA Lab Manual – Page 130|193


Example 8: Java finally example where exception occurs and handled.

Homework:

1. List the various exceptional conditions that have occurred in programs throughout this text so far.
List as many additional exceptional conditions as you can. For each of these, describe briefly how
a program typically would handle the exception by using the exception-handling techniques dis-
cussed in this chapter. Typical exceptions include division by zero and array index out of bounds.

2. Write a program that demonstrates how various exceptions are caught with catch (Exception ex-
ception) This time, define classes ExceptionA (which inherits from class Exception) and Excep-
tionB (which inherits from class ExceptionA). In your program, create try blocks that throw ex-
ceptions of types ExceptionA, ExceptionB, NullPointerException and IOException. All excep-
tions should be caught with catch blocks specifying type Exception.(Catching Exceptions Using
Class Exception)

Object Oriented Programming using JAVA Lab Manual – Page 131|193


3. Create a directory) Write a program that prompts the user to enter a directory name and creates a
directory using the File’s mkdirs method. The program displays the message “Directory created
successfully” if a directory is created or “Directory already exists” if the directory already exists

Object Oriented Programming using JAVA Lab Manual – Page 132|193


Lab No. 20
GUI Programming-I

Object Oriented Programming using JAVA Lab Manual – Page 133|193


Lab No. 20: GUI Programming - I
Objective:
To create user interfaces using frame, panels, and simple GUI components.

Scope:
This lab will serve two purposes. First, it presents the basics of Java GUI programming. Second, it uses
GUI to demonstrate OOP. Specifically, this lab introduces the framework of the Java GUI API and dis-
cusses GUI components and their relationships, containers and layout managers, colors, fonts, borders,
image icons, and tool tips. It also introduces some of the most frequently used GUI components.

Example 1:Creating a frame

Object Oriented Programming using JAVA Lab Manual – Page 134|193


Example 2: Adding components to a frame

Object Oriented Programming using JAVA Lab Manual – Page 135|193


Layout Manager

Each container contains a layout manager, which is an object responsible for layingout the GUI compo-
nents in the container.

Example 3: Flow Layout

Object Oriented Programming using JAVA Lab Manual – Page 136|193


Example 4: Grid Layout

Object Oriented Programming using JAVA Lab Manual – Page 137|193


Example 5: Border Layout

Object Oriented Programming using JAVA Lab Manual – Page 138|193


Example 6: Using Panels and sub-containers

A container can be placed inside another container. Panels can be used as sub-containers to group GUI
components to achieve the desired layout.

Object Oriented Programming using JAVA Lab Manual – Page 139|193


Object Oriented Programming using JAVA Lab Manual – Page 140|193
Example 7: Colors & Fonts

Object Oriented Programming using JAVA Lab Manual – Page 141|193


Object Oriented Programming using JAVA Lab Manual – Page 142|193
Example 8: Image Icon

Exercises:

Exercise 1:

(Use the FlowLayout manager) Write a program that meets the following requirements (see Figure):

Object Oriented Programming using JAVA Lab Manual – Page 143|193


• Create a frame and set its layout to FlowLayout.
• Create two panels and add them to the frame.
• Each panel contains three buttons. The panel uses FlowLayout.

(Use the BorderLayout manager) Rewrite the preceding program to create the same user interface, but
instead of using FlowLayout for the frame, use BorderLayout. Place one panel in the south of the frame
and the other in the center.

(Use the GridLayout manager) Rewrite Programming Exercise 1 to add six buttons into a frame. Use a
GridLayout of two rows and three columns for the frame.

(Use JPanel to group buttons) Rewrite Programming Exercise 1 to create the same user interface. Instead
of creating buttons and panels separately, define a class that extends the JPanel class. Place three buttons
in your panel class, and create two panels from the user-defined panel class.

Exercise 2:

(Display random 0 or 1) Write a program that displays a 10-by-10 square matrix, as shown in Figure.
Each element in the matrix is 0 or 1, randomly generated. Display each number centered in a label.

Object Oriented Programming using JAVA Lab Manual – Page 144|193


Lab No. 21
GUI Programming-II

Object Oriented Programming using JAVA Lab Manual – Page 145|193


Lab No. 21: GUI Programming - II
Objective:
To get a taste of event-driven programming.

Scope:
Suppose you want to write a GUI program that lets the user enter a loan amount, annual interstate, and
number of years and click the Compute Payment button to obtain the monthly payment and total payment,
as shown in Figure. How do you accomplish the task? You have to use event-driven programming to
write the code to respond to the button-clicking event.

To respond to a button click, you need to write the code to process the button-clicking action. The button
is an event source object—where the action originates. You need to create an object capable of handling
the action event on a button. This object is called an event listener.

Object Oriented Programming using JAVA Lab Manual – Page 146|193


Example 1: Handling a simple event

Object Oriented Programming using JAVA Lab Manual – Page 147|193


Object Oriented Programming using JAVA Lab Manual – Page 148|193
Object Oriented Programming using JAVA Lab Manual – Page 149|193
Example 2: Handling a simple event (Alternate way using inner anonymous classes)

Object Oriented Programming using JAVA Lab Manual – Page 150|193


Exercises:

Exercise 1:

(Create an investment-value calculator) Write a program that calculates the future value of an investment
at a given interest rate for a specified number ofyears. The formula for the calculation is:

futureValue = investmentAmount * (1 + monthlyInterestRate)years*12

Use text fields for the investment amount, number of years, and annual interestrate. Display the future
amount in a text field when the user clicks the Calculatebutton, as shown in Figure.

Object Oriented Programming using JAVA Lab Manual – Page 151|193


Lab No. 22
JDBC-I

Object Oriented Programming using JAVA Lab Manual – Page 152|193


Lab No. 22: JDBC-I
Objective:
To implement the concepts of JDBC, that enables Java programs to execute SQL statements. Since nearly
all relational database management systems (DBMSs) support SQL. JDBC makes it possible to write a
single database application that can run on different platforms and interact with different DBMSs.

Scope:
JAVA interacts with database using a common database application programming interface called as
JDBC. The JDBC API provides set of interfaces and there are different implementations respective to
different databases. So the developer will be interacting with JDBC API rather than getting in to compli-
cations of the database. JDBC allows us to write Java code, and leave the platform (database) specific
code to the driver. JAVA was designed to be platform independent and JDBC takes JAVA one step ahead
making java database code database independent. That means if we use JDBC for connectivity for SQL
Server we can run the same code without changing for ORACLE.
Example 1: This program demonstrates to how data retrieved from the table by applying JDBC objects.

Object Oriented Programming using JAVA Lab Manual – Page 153|193


Object Oriented Programming using JAVA Lab Manual – Page 154|193
Example 2: To search the specific record in the table following query will be execut-

ed.

Object Oriented Programming using JAVA Lab Manual – Page 155|193


Example 3: Search by Highest and the lowest marks with details by applying the sub-query

Object Oriented Programming using JAVA Lab Manual – Page 156|193


Exercises:

Exercise 1:

Create the following tables:


1) client_master

columnname datatype size


client_no varchar 25
name varchar2 20
address1 varchar2 30
address2 varchar2 30
city varchar2 15
state varchar2 15
pincode number 06
bal_due number 10,2

2) Product_master
Columnname datatype size
Product_no varchar2 25
Description varchar2 30
Profit_percent number 9,2
Unit_measure varchar2 10
Qty_on_hand number 06
Reoder_lvl number 05
Sell_price number 06
Cost_price number 06

On the basis of above two tables apply queries accordingly:


i) Find out the names of all the clients.
ii) Retrieve the list of names and cities of all the clients.
iii) List the various products available from the product_master table.
iv) List all the clients who are located in D.I. Khan.
v) Display the information for client no 001 and 007.

Homework:

i) Find the products with description as ‘1.44 drive’ and ‘1.22 Drive’.
ii) Find all the products whose selling price is greater than 7000.
iii) Find the list of all clients who stay in city ‘D.I. Khan’ or city ‘Abbottabad’.
iv) Find the product whose selling price is greater than 3000 and less than or equal to 9000.
v) List the name, city and state of clients those are not in the state of ‘KPK’.

Object Oriented Programming using JAVA Lab Manual – Page 157|193


Lab No. 23
JDBC-II

Object Oriented Programming using JAVA Lab Manual – Page 158|193


Lab No. 23: JDBC-II
Objective:
To implement the concepts of JDBC, that enables Java programs to execute SQL statements. Since nearly
all relational database management systems (DBMSs) support SQL. JDBC makes it possible to write a
single database application that can run on different platforms and interact with different DBMSs.

Scope:
JAVA interacts with database using a common database application programming interface called as
JDBC. The JDBC API provides set of interfaces and there are different implementations respective to
different databases. So the developer will be interacting with JDBC API rather than getting in to compli-
cations of the database. JDBC allows us to write Java code, and leave the platform (database) specific
code to the driver. JAVA was designed to be platform independent and JDBC takes JAVA one step ahead
making java database code database independent. That means if we use JDBC for connectivity for SQL
Server we can run the same code without changing for ORACLE.
Example 1: This program demonstrates that user may enter the data into the database.

Object Oriented Programming using JAVA Lab Manual – Page 159|193


Object Oriented Programming using JAVA Lab Manual – Page 160|193
Example 2: This program demonstrates the Record Deletion.

Object Oriented Programming using JAVA Lab Manual – Page 161|193


Exercises:

Exercise 1:

On the basis of above two tables apply queries accordingly:

1. Change the selling price of ‘1.44 floppy drive to Rs.1150.00


2. Delete the record with client 0001 from the client master table.
3. Change the city of client_no’0005’ to Abbottabad.
4. Change the bal_due of client_no ‘0001, to 5000.
5. Find the products whose selling price is more than 3500 and also find the new selling price as
original selling price *15.
6. Find out the clients who stay in a city whose second letter is b.
7. Find out the name of all clients having ‘a’ as the second letter in their names.
8. List the products in sorted order of their description.

9. Count the total number of orders


10. Calculate the average price of all the products.
11. Calculate the minimum price of products.
12. Determine the maximum and minimum prices. Rename the tittle as ‘max_price’ and min_price
respectively.
13. Count the number of products having price greater than or equal to 3500.

Homework:

(Group by)

1. Print the description and total quantity sold for each product.
2. Find the value of each product sold.
3. Calculate the average quantity sold for each client that has a maximum order value of 15000.
4. Find out the products which has been sold to Baloch.
Object Oriented Programming using JAVA Lab Manual – Page 162|193
5. Find the names of clients who have ‘CD Drive’.
6. Find the products and their quantities for the orders placed by ‘Tariq’ and ‘Baloch’.
7. Select product_no, total qty_ordered for each product.
8. Select product_no, product description and qty ordered for each product.
9. Display the order number and day on which clients placed their order.
10. Display the month and Date when the order must be delivered.

Object Oriented Programming using JAVA Lab Manual – Page 163|193


Lab No. 24
JDBC-III

Object Oriented Programming using JAVA Lab Manual – Page 164|193


Lab No. 24: JDBC-III

Objective:
To implement the concepts of JDBC, that enables Java programs to execute SQL statements. Since nearly
all relational database management systems (DBMSs) support SQL. JDBC makes it possible to write a
single database application that can run on different platforms and interact with different DBMSs.

Scope:
JAVA interacts with database using a common database application programming interface called as
JDBC. The JDBC API provides set of interfaces and there are different implementations respective to
different databases. So the developer will be interacting with JDBC API rather than getting in to compli-
cations of the database. JDBC allows us to write Java code, and leave the platform (database) specific
code to the driver. JAVA was designed to be platform independent and JDBC takes JAVA one step ahead
making java database code database independent. That means if we use JDBC for connectivity for SQL
Server we can run the same code without changing for ORACLE.
Example 1: This program demonstrates Record updating.

Object Oriented Programming using JAVA Lab Manual – Page 165|193


Object Oriented Programming using JAVA Lab Manual – Page 166|193
Example 2: This program demonstrates the Navigation of Records.

Object Oriented Programming using JAVA Lab Manual – Page 167|193


Object Oriented Programming using JAVA Lab Manual – Page 168|193
Exercises:

Exercise 1:

(Sub-Query)

On the basis of above two tables apply queries accordingly:


1. Find the product_no and description of non- moving products.
2. Find the customer name, address, city and pincode for the client who has placed order no “0583”
3. Find the client names who have placed order before the month of Dec 2015.
4. Find out if product “1.44 Drive” is ordered by only client and print the client_no name to whom
it was sold.
5. Find the names of client who have placed orders worth Rs.10000 or more.
6. Select the orders placed by ‘Baloch”.
Homework:

1. Select the names of persons who are in Mr. Mudassar’s department and who have also worked on
an inventory control system.
2. Select all the clients and the salesman in the city of Lahore.
3. Select salesman name in “Lahore” who has at least one client located at “D.I.Khan”
4. Select the product_no, description, qty_on-hand,cost_price of on_moving items in the prod-
uct_master table.

Object Oriented Programming using JAVA Lab Manual – Page 169|193


Lab No. 25
Multithreading-I

Object Oriented Programming using JAVA Lab Manual – Page 170|193


Lab No. 25: Multithreading-I

Objective:
To implement the concepts of Multithreading

Scope:
Multithreading is a widespread programming and execution model that allows multiple threads to exist
within the context of a single process. These threads share the process's resources, but are able to execute
independently. The threaded programming model provides developers with a useful abstraction of con-
current execution. Multithreading can also be applied to a single process to enable parallel execution on a
multiprocessing system.

Example 1: This program demonstrates how to implement threads in Java.

Object Oriented Programming using JAVA Lab Manual – Page 171|193


Object Oriented Programming using JAVA Lab Manual – Page 172|193
Example 2: This program demonstrates how to implement threads in Java

Object Oriented Programming using JAVA Lab Manual – Page 173|193


Object Oriented Programming using JAVA Lab Manual – Page 174|193
Exercises:

Exercise 1:

Create an example of a “busy wait.” One thread sleeps for awhile and then sets a flag to true. The second
thread watches that flag inside a while loop (this is the “busy wait”) and when the flag becomes true, sets
it back to false and reports the change to the console. Note how much wasted time the program spends
inside the “busy wait” and create a second version of the program that uses wait( ) instead of the “busy
wait.”

Homework

Exercise 1
Write a program to create two threads. In this class we have one constructor used to start the threads and
run it. Check whether these two threads are run or not.

Exercise 2
Create a multithreaded program by using Runnable interface and then create, initialize and start three
Thread objects from your class. The threads will execute concurrently and display the following String
array elements.
String course [ ] = {“Java”, “J2EE”, “Spring”, “Struts”};

Object Oriented Programming using JAVA Lab Manual – Page 175|193


Lab No. 26
Multithreading-II

Object Oriented Programming using JAVA Lab Manual – Page 176|193


Lab No. 26: Multithreading-II
Objective:
To implement the concepts of Multithreading

Scope:
Multithreading is a widespread programming and execution model that allows multiple threads to exist
within the context of a single process. These threads share the process's resources, but are able to execute
independently. The threaded programming model provides developers with a useful abstraction of con-
current execution. Multithreading can also be applied to a single process to enable parallel execution on a
multiprocessing system.

Example 1: This program demonstrates how to implement threads in Java.

Object Oriented Programming using JAVA Lab Manual – Page 177|193


Object Oriented Programming using JAVA Lab Manual – Page 178|193
Example 2: This program demonstrates how to implement threads in Java

Object Oriented Programming using JAVA Lab Manual – Page 179|193


Exercises:

Exercise 1:

Write a program that runs 5 threads, each thread randomizes a number between 1 and 10. The
main thread waits for all the others to finish, calculates the sum of the numbers which were ran-
domized and prints that sum. You will need to implement a Runnable class that randomizes a
number and store it in a member field. When all the threads have done, your main program can
go over all the objects and check the stored values in each object.

Exercise 2:

Modify the program in (Ex. 1) so that instead of each object keeping its own score, you will use
one collection to store all the results in.

Homework:

1. Write a program for inventory problem to illustrate the usage of synchronized keyword.
Note: The output should be similar as mentioned below:
Thread1Thread[test thread,5,main]
Thread2Thread[test thread,5,main]
Quantity ordered :13
Quantity on hand :487
Total quantify taken away by way of order :13
Quantity ordered :91
Quantity on hand :396
Total quantify taken away by way of order :104
Object Oriented Programming using JAVA Lab Manual – Page 180|193
Lab No. 27
Special Lab Task-I

Object Oriented Programming using JAVA Lab Manual – Page 181|193


Lab No. 27: Special lab Task – I (Linked List Implementation)

Objective:

The special lab is designed for the students with some general menu driven programs for better under-
standing of Java that will be more beneficial for the students and to meet the objective of the course.

Scope:

This will be helpful for the students to adapt the mini-project level approach.

Exercise 1:
You are supposed to write a complete Inventory system in Java by applying Linked List for James Timber
Store. James Timber owns a large piece of forest. He runs a business cutting down the trees and sells
them. He asks you to develop a program to track the trees in the forest. Each tree when cut (called timber)
has got unique identification code and other information for each of his timber as below.

• Zone : a character representing the location zone of the tree


• TimberID : integer
• Kind : a 30 character description of the timber
• Weight : a float number containing the weight of the timber
• Height : a float number containing the height of the timber
• Quantity : integer
• Price : integer

Perform the following tasks

a) Declare the nodes for the linked list using all details written above. Make sure you declare a ob-
ject reference in the node so that it can be used to link the other nodes.
b) Create a Main Menu to allow the user to choose options.

Main Menu

[1]. Add a new timber records


[2]. Display all records for a given Zone
[3]. Display a particular record given the Kind
[4]. Analysis of record level
[5]. Sales update Report

Object Oriented Programming using JAVA Lab Manual – Page 182|193


Please enter your choice:???

c) Add New--- is used to allow the user to enter timber record details. No duplication of TimberID
is allowed.
d) Display Records—will display zone wise records, for example there are four zone in the forest
like A, B, C, D.
e) Display Particular record of the given kind
f) Analysis of record level—Display all records where the quantity in hand is lower than 100 in the
stock.
g) Sales update—ask the user to enter the TimberID to be sold. Search the TimberID in the linked
list and when found ask the user Quantity to be sold. If the quantity to be sold is greater than
quantity on hand, please display an error message, otherwise update the node accordingly and
display the sales report.

Object Oriented Programming using JAVA Lab Manual – Page 183|193


Lab No. 28
Special Lab Task-II

Object Oriented Programming using JAVA Lab Manual – Page 184|193


Lab No. 28: Special Lab Task –II (Queue Implementation)

Objective:
To be able to form linked data structure by self-referential classes and to create and manipulate dynamic
data structures such as Linked List, Queues and Stack and to understand various important applications of
linked data structures.

Scope:
Queue has many applications in computer systems, most computers have only a single processor, so only
one user can be server at a time. Entries for the other users are placed in a queue. Each entry gradually
advances to the front of the queue as user receives service. The entry at the front of the queue is the next
to receive service process will continue till all the jobs are finished.

Exercise:

1) Define a class called PastVisits that contains the following fields:

DateVisited: a string of 10 characters in form of ‘dd/mm/yyyy’

MedicinePrescribed: a string of 100 characters

Symptoms: a string of 100 characters

Define a dynamic Queue called PatientRecords which is capable of holding the following information:

Name: a string of up to 30 characters

Visits: an integer recording the numbers of visits to the clinic

PastVisitsInfo: array that can store 100 of the above PastVistits class

NextPatient: a pointer pointing to the next PatientRec class

Define a class called PatientsQueue which stores the following:

NumOfPatient: an integer recording the number of patients in the queue

FirstInQueue: an address pointing to the first PatientRec class

Object Oriented Programming using JAVA Lab Manual – Page 185|193


LastInQueue: an address pointing to the last PatientRec class

a) The doctor wishes to know the name of the next patient to visit him. Write a method called Dis-
playFirstPatient() that takes in a parameter which points to a PatientQueue and prints
out the name of the patient at the head of the queue.

b) The nurse wishes to know the Patient’s names in the queue who visited the clinic on a certain
date. Write a method called FindPatients() which takes in a parameter which points to Pa-
tientQueue and a second parameter RequiredDate which is a string of 10 characters. The
function should print out the names of all patients in the queue on that date.

Object Oriented Programming using JAVA Lab Manual – Page 186|193


Lab No. 29
Special Lab Task-III

Object Oriented Programming using JAVA Lab Manual – Page 187|193


Lab No. 29: Special Lab Task –III

Objective:

The special lab is designed for the students with some general menu driven programs for better under-
standing of Java that will be more beneficial for the students and to meet the objective of the course.

Scope:

This will be helpful for the students to adapt the mini-project level approach.

Exercise 1:

You should develop test cases (of screen captures) to show successful running of each of the option in this
program.
Define a structure called LineType with following field:
Line : that can store a maximum 80 characters
Declare an array called Page that can store up to 25 LineType above
Develop a program in Java to manipulate Page above to allow the user to perform the following opera-
tions.

Main Menu
[1]. Enter Lines of Text
[2]. Retrieve all Lines
[3]. Retrieve a particular line of Text
[4]. Delete a particular line of Text

Choice:

If option 1 is selected

Enter Line #: 1

Enter line (up to max. 80 char): This is first line

Enter Line #: 2
Object
Enter line (upOriented Programming
to max. 80 char): This isusing JAVA
second line Lab Manual – Page 188|193

up to so on……
If option 2 is selected

Line #: 1 This is first line

Line #: 2 This is second line

up to so on……
If option 3 is selected

Enter Line #: 2

This is second line

If option 4 is selected

Enter Line # to Delete: 1

Line 1 Deleted Successfully

Exercise 2:

Develop a program that allows the user to perform the following operations

Main Menu

1) Convert Day Integer to Day String


2) Convert Month Integer to Month String
3) Convert Date Integer to Date String
4) Change Date
Choice:???

Each of the above operations is to be implemented in terms of a function taking in appropriate param-
eter

Whereby:

Object Oriented Programming using JAVA Lab Manual – Page 189|193


If option 1 is chosen

Enter Day Integer: 3

Third

If option 2 is chosen

Enter Month Integer: 12

December

If option 3 is chosen

Enter Date Integer (Day followed by Months): 2 11

Second of November

If option 4 is chosen

Enter Original Date Integer (Day followed by Month): 2 11

Enter no. of Days to Add: 3

Fifth of November

Object Oriented Programming using JAVA Lab Manual – Page 190|193


Lab No. 30
Special Lab Task-IV

Object Oriented Programming using JAVA Lab Manual – Page 191|193


Lab No. 30: Special lab Task - IV

Objective:

The special lab is designed for the students with some general menu driven programs for better under-
standing of Java that will be more beneficial for the students and to meet the objective of the course.

Scope:

This will be helpful for the students to adapt the mini-project level approach.

Exercises:
Designing Simple Calculator in JAVA with Login Form

• Design a login form with password field, If password is invalid, display the proper message
• If user enters valid password, the functional calculator should be displayed
• Apply Exception Handling where applicable

Example:

If password is invalid then

Object Oriented Programming using JAVA Lab Manual – Page 192|193


If password is valid then

References

1. Java The complete reference, by Herbert Schildt, 8th edition


2. OOP using Java, from Problem solving to Program Design by D.S. Malik
3. Java How to Program, by Deitel & Deitel, 9th edition
4. Beginning Java 2 by Ivor Horton

Object Oriented Programming using JAVA Lab Manual – Page 193|193

You might also like