Oop Lab Manual Java by Rab Nawaz Jadoon
Oop Lab Manual Java by Rab Nawaz Jadoon
Lab Manual
Faculty Name(s)
Lab No. 15: Abstract classes, interface, and inner classes-III................................................................... 102
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.
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?
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
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.
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):
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:
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).
class circle1{
Public static void main(String[] a){
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..
Example 5: Method returns integer that contains the sum of two numbers.
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
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.
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.
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:
Example 1: Write a Java Program to define a class, describe its constructor, overload the Constructors and
instantiate its object
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
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.
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.
Example 5: Write a Java program to implement the concept of importing classes from user defined pack-
age.
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.
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.
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).
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:
0011
1101
1010
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.
23.5 35 2 10
4.5 3 45 3.5
35 44 5.5 9.6
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.
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.
(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:
Write a program that prompts the user to enter a password and displays "Valid Password" if the rule is
followed or "Invalid Password" otherwise.
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.
Exercise 1:
Exercise 2:
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.
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.
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.
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.
When invoking a superclass version of an overridden method the super keyword is used. Con-
sider the following example:
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
❖ 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.
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
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);
}
}
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.
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:
(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.
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
Objective:
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.
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.
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.
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);
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:
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.
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.
Department of Mathematics
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
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.
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.
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.
3. Write a program that causes the JVM to throw an OutOfMemoryError and catches and handles this
error.
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 7: Java finally example where exception occurs and not 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)
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.
Each container contains a layout manager, which is an object responsible for layingout the GUI compo-
nents in the container.
A container can be placed inside another container. Panels can be used as sub-containers to group GUI
components to achieve the desired layout.
Exercises:
Exercise 1:
(Use the FlowLayout manager) Write a program that meets the following requirements (see Figure):
(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.
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.
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:
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.
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.
ed.
Exercise 1:
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
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’.
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.
Exercise 1:
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.
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.
Exercise 1:
(Sub-Query)
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.
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.
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”};
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.
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
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.
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
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.
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:
Define a dynamic Queue called PatientRecords which is capable of holding the following information:
PastVisitsInfo: array that can store 100 of the above PastVistits 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.
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 #: 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
up to so on……
If option 3 is selected
Enter Line #: 2
If option 4 is selected
Exercise 2:
Develop a program that allows the user to perform the following operations
Main Menu
Each of the above operations is to be implemented in terms of a function taking in appropriate param-
eter
Whereby:
Third
If option 2 is chosen
December
If option 3 is chosen
Second of November
If option 4 is chosen
Fifth of November
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:
References