COSC212 Slides
COSC212 Slides
06/12/25 Unit 01 1
Recall What Inheritance is About
• Inheritance allows a software developer to derive a new class from an existing
one. –Reusability
• The existing class is called the parent class, base class or super class.
• The new class is called the child class, derived class or subclass.
• As the name implies, the child inherits characteristics of the parent.
• That is, the child class inherits the methods and data defined in the parent class.
Student
• Inheritance relationships are often shown
graphically in a class diagram, with the arrow
pointing to the parent class.
• Inheritance creates an is-a relationship, GraduateStudent
meaning the child is a more specific version
of the parent. defendThesis()
06/12/25 Unit 01 2
The extends Keyword
• In Java, the keyword extends is used to establish an inheritance.
06/12/25 Unit 01 3
The Object Class
06/12/25 Unit 01 4
Overriding Methods
• A child class can override a method it inherited from its super class.
• The new method must have the same signature as the parent's method.
06/12/25 Unit 01 5
Overloading vs Overriding
• If super is not used to call the parent's constructor, the compiler inserts a
call to the parent's default constructor. An error results if no such default
constructor exists.
06/12/25 Unit 01 7
What then is Inherited
• Fields and Methods are inherited if their access modifiers allow.
• public variables and methods are inherited, but private ones are not.
06/12/25 Unit 01 8
The protected Visibility
Modifier
• We saw that fields that are declared private cannot be inherited.
• We also know that it is a very bad practice to declare fields as public. So is there a compromise? Yes, protected modifier.
06/12/25 Unit 01 9
Single vs. Multiple Inheritance
• Multiple inheritance allows a class to be derived directly from two or more
classes, inheriting the members of all parent.
• Collisions, such as the same variable name in two parents, have to be resolved -
leading to complex code.
• To avoid this complexity, Java supports only single inheritance, meaning that a
derived class can have only one direct parent class.
Object
Student
GraduateStudent
defendThesis()
06/12/25 Unit 01 10
Class Hierarchy
• A child class of one parent can be the parent of another child, forming
class hierarchies.
• Two children of the same parent are called siblings - Example, Faculty and
Staff..
• Good class design puts all common features as high in the hierarchy as is
reasonable
06/12/25 Unit 01 11
Up-Casting
• An object reference can refer to an object of its class, or to an object of any class
related to it by inheritance
• For example, if the Employee class is used to derive a class, Faculty, then an
Employee reference can be used to point to a Faculty object.
• Now since the method is expecting Employee as argument, we can call it with an
object of MonthlyEmployee or HourlyEmployee.
7.0
method1() from class ShadowingVsOverriding.
method2() from class ShadowingVsOverriding.
Press any key to continue...
06/12/25 Unit 01 16
Abstract Classes
06/12/25 Unit 01
02 17
What is an Abstract Class?
• A subclass (programmer) normally has the option of whether
to override the methods of a superclass or not.
• However, there are situations where the superclass
(programmer) would like to force the subclass (programmer)
to override a certain method.
• This is usually the case if there is no suitable default
implementation.
06/12/25 Unit 01
02 19
What is an Abstract Class? –
Cont’d
1. class HourlyEmployee extends Employee{
2. private int hours;
3.
4. public HourlyEmployee(String name, double rate){
5. super(name, rate);
6. hours = 0;
7. }
8. public void addHours(int moreHours){
9. hours += moreHours;
10. }
11. public String toString(){
12. return super.toString()+"Hours: "+hours;
13. }
14. public double pay(){
15. return super.pay() * hours;
16. }
17. }
The payRate field represents the hourly pay for the employee. Here the pay method multiplies this value with the hours worked and returns the result.
06/12/25 Unit 01
02 20
What is an Abstract Class? –
Cont’d
• Clearly, if the pay method is not overridden, by mistake, the pay of the HourlyEmployee will be computed wrongly.
• To force the subclass programmer to override this method, the method should be declared as abstract.
• An abstract method consists of only the method heading.
06/12/25 Unit 01
02 21
What is an Abstract Class? –
Cont’d
• Now, once a class has at least one abstract method, then the class is said to
be abstract and it must be declared as such in its heading.
06/12/25 Unit 01
02 22
Properties of an Abstract Class
• An abstract class cannot be instantiated - that is, it cannot be used to create objects.
• For example, We cannot create an object of the Employee class.
• Thus, to represent an employee whose pay is per month, we need to sub-class the Employee
abstract class as follows:
06/12/25 Unit 01
02 23
Properties of an Abstract Class
– Cont’d
• The relationship between the three classes is shown by the following:
06/12/25 Unit 01
02 24
Properties of an Abstract Class
– Cont’d
06/12/25 Unit 01
02 25
Discovering Abstract Classes
• Suppose we wish to write a program that manipulates two-dimensional
geometrical shapes, namely:
– Squares
– Rectangles and
– Circles
• Suppose further that we want each such shape to tell its name, its area
and its perimeter.
• Since each of these shapes is a type of shape, it makes sense to have a
superclass, Shape, from which the others can be derived.
• However, since the computation of area and perimeter for each of these
shapes is different, the subclasses should be forced to override these
methods. Thus the Shape class must be abstract.
06/12/25 Unit 01
02 26
Discovering Abstract Classes –
Cont’d
• Moreover, since square is a special type of rectangle, we
can derive it from the Rectangle class.
• Thus, we have a two level hierarchy tree shown as follows:
06/12/25 Unit 01
02 27
Discovering Abstract Classes –
•
Cont’d
The code for these classes is shown as follows:
• What is an Interface?
• Implementing Interfaces
06/12/25 Unit 01
03 32
What is an Interface? –Cont’d
• Interfaces are used to realize some of the advantages of multiple inheritance, while
avoiding its complexity.
• For example, both GraduateStudent and Faculty might implement the Instructor
interface.
• Interfaces only declare methods that objects must have but with no implementation
- all methods are abstract.
• Interfaces differ from abstract classes in that:
– They cannot have implemented methods
– No constructors
– No instance variables except constants.
• Interface names are often adjectives, ending in -able.
examples: Colorable, Rotatable, Comparable, Runnable
• Interfaces that specify roles can be named with nouns.
examples: Container, Mover, Instructor
06/12/25 Unit 01
03 33
Interface Declaration Syntax
• Interfaces are declared similar to classes, except "interface" is used instead of "class".
Unit 01
03 34
Implementing Interfaces
• A class implements an interface similar to the way it extends a superclass but using " implements" instead of "extends".
• A class can extend another class and at the same time implements one or more interfaces.
06/12/25 Unit 01
03 35
Implementing Interfaces –
Cont’d
• Note: although methods of an interface are automatically public, they must be specified as
such in the implementing class.
• If a class implements more than one interface, the interface names are separated by commas.
• What happens if a class does not define all the methods of an interface it claims to
implement?
• Same thing that happens if an abstract method of a superclass is not defined - the
implementing class is abstract.
• If a super class implements an interface, then all its subclasses are considered to
implement it too.
06/12/25 Unit 01
03 36
Using Interfaces as Types
• Interfaces can be used as types of variables and parameters.
• For example, an object of GraduateStudent can be of type
GraduateStudent, Student, Object or Instructor.
• Similarly, if Faculty is defined as shown below, then its instance can be of type
Faculty, MonthlyEmployee, Employee, Instructor, Comparable, or Object.
• Thus, a method with the following header can accept both an object of Faculty or
that of GraduateStudent.
06/12/25 Unit 01
03 38
Conflicting Methods in
Interfaces
06/12/25 Unit 01
03 39
Interfaces Cannot Grow
• It important to think through very well about the methods (and
their signatures) when designing an interface.
Unit 01
03 40
Abstract Classes Versus
Interfaces
Interfaces Abstract Classes
Does not implement its methods May implement some or all of its
methods
A class can implement multiple A class can extend only one abstract
interfaces class
06/12/25 Unit 01
03 41
Exercises
Write each of the following:
1. an interface, Instructor, which has two methods: String getOfficeHours() and
Course[ ] getTeachingCourses().
2. a class, Course, with instance variables: courseCode, creditHours, and title; and
appropriate accessor, mutator and toString methods.
3. a class Faculty that extends MonthlyEmpolyee and implements the Instructor
interface. It has two additional instance variables: String officeHourse and
Course[] teachingCourses.
4. classes, Student and GraduateStudents as described in page 3 of the inheritance
session.
5. a class, ReaseachAssistant, that extends GraduateStudent and implements the
Instructor interface
6. A test class, TestInstructors, that has the following methods: void
PrintTeachingDetails(Instructor i): that prints the office hours and teaching
courses for i; and a main method, that creates instances of Faculty and
ReasearchAssistant and prints their teaching details.
06/12/25
Sahalu Junaidu Unit 01
03 42
Polymorphism
• What is Polymorphism?
• Down-Casting
• Advantages of Polymorphism
06/12/25
Sahalu Junaidu Unit 01
04 43
What is Polymorphism?
• Polymorphism means many forms (it derives from the Greek words Poly,
meaning many, and Morphos, meaning form).
• In Java, the term is used in a number of ways.
• For example, we recall that a reference of type
superclass can be assigned an object of any of
its subclasses.
• Similarly, a reference of type a given interface can be assigned
an object of any class that implements the interface.
• These types of references are therefore called polymorphic
references - since they can take different forms.
06/12/25
Sahalu Junaidu Unit 01
04 44
What is Polymorphism? -
Cont’d
• However, the polymorphism which we consider is this lecture, is
that which involves binding of method calls to particular methods.
• We explain this using an example.
• Recall our Shapes example discussed in the Abstract classes lecture.
06/12/25
Sahalu Junaidu Unit 01
04 45
What is Polymorphism? -
•
Cont’d
With these classes in mind, consider the following application and its output.
06/12/25
Sahalu Junaidu Unit 01
04 46
What is Polymorphism? -
Cont’d
• First, we note that because the references (of type Shape) in the array, shape, are polymorphic, we are able to store all the three types of shapes in one
array.
• Second, and the most important point, the same set of statements produced three different outputs.
• for(int i = 0; i<shape.length; i++){
1. System.out.println("\n"+shape[i].name());
2. System.out.println("Perimeter: "+shape[i].perimeter());
3. System.out.println("Area: "+shape[i].area());
4. }
06/12/25
Sahalu Junaidu Unit 01
04 47
What is Polymorphism? -
Cont’d
• How does the system know which area method to call from the statement,
shape[i].area(), given that the reference type is Shape?
• The answer, as far as Java Compiler is concerned is “I don’t know”. That is
this question cannot be answered at compilation time.
• It is only possible to answer this question after knowing the actual type of
object being referenced by the reference variable shape[i].
• The association of a method call to a particular method
is called binding, and Java exhibits what is called
run-time binding, also called dynamic binding or
late-binding.
06/12/25
Sahalu Junaidu Unit 01
04 48
What is Polymorphism? -
Cont’d
• Java uses late-binding for all methods except those that are declared as
final.
• In other languages such as Pascal, binding is determined by the compiler.
Such languages are said to exhibit early or static binding.
• Since binding takes place at run-time in Java, it is possible to write code
that executes differently depending on the actual object.
• This behavior, whereby the same code executes differently, depending on
the object it acts on is what is called polymorphism.
06/12/25
Sahalu Junaidu Unit 01
04 49
Taking Advantage of
Polymorphism
• Since binding takes place at run-time, it is possible to make a call to abstract methods, since by the time the code executes, the methods would have been implemented.
• For example, we can modify the Shape class as follows:
06/12/25
Sahalu Junaidu Unit 01
04 50
Taking Advantage of Polymorphism –
Cont‘d
• With this modification, the application can now be simplified as follows and it produces the same output as before:
1. public class TestShapes{
2. public static void main(String[] args){
3. Shape[] shape = new Shape[3];
4.
5. shape[0] = new Rectangle(5, 10);
6. shape[1] = new Square(10);
7. shape[2] = new Circle(15);
8.
9. for(int i = 0; i<shape.length; i++)
10. System.out.println(shape[i]);
11. }
12. }
• The println calls the toString method of the object. Since the method is not overridden in the subclasses, that of the super class is used.
• Due to polymorphism, the call to perimeter and area methods in toString method will be bound to those of the actual object.
06/12/25 Unit 01
04 51
Down-Casting
06/12/25
Sahalu Junaidu Unit 01
04 53
Down-Casting –Cont’d
• In our example, if the method we want to call is not in the superclass Shape, then we still need to down-cast
further.
• For example, suppose that the Circle class has an additional method, public double getRadius(), and we wish
to call this method. Then we must down-cast the object returned by the get method to Circle.
• But how do we know that the actual object is of type Circle.
• Fortunately, Java has an operator, instaceof, which we can use to check the actual type of an object.
1. for(int i = 0; i<shape.size; i++){
2. Shape nextShape (Shape)shape.get(i);
3. System.out.println(nextShape.name()+"\t"+nextShape.area());
4. if(nextShape instanceOf Circle){
5. Circle circle = (Circle)nextShape;
6. System.out.println("Radius = "+circle.getRadius());
7. }
8. }
06/12/25
Sahalu Junaidu Unit 01
04 54
Down-Casting –Cont’d
• Although the Compiler will allow down-casting even if the actual object
is not of type the subclass being down-cast to, a run-time error will result
if the resulting reference is used to call a method that does not exists.
06/12/25
Sahalu Junaidu Unit 01
04 55
Advantages of Polymorphism
06/12/25
Sahalu Junaidu Unit 01
04 56
Advantages of Polymorphism – Cont’d
• Rather than:
1. for(int i = 0; i<munShapes; i++){
2. switch(shapeType[i]){
3. 'c': System.out.println(circleArea()); break;
4. 's': System.out.println(squareArea()); break;
5. ...
6. }
7. }
• In fact any time you find yourself doing the later, it is a pointer to re-think your code. It probably could be made more Polymorphic.
06/12/25
Sahalu Junaidu Unit 01
04 57
Exercises
1(a). Write a class, Triangle, that extends Shape, and has three instance
variable, side1, side2, side3. Implement the area and perimeter methods.
Note: area = SQRT(s(s-side1)(s-side2)(s-side3)), where, s = perimeter/2.
(b). Write a class, TestShapes, that creates an instance of each of our shape
classes and prints it.
2(a). Write an interface, Zakatable, that has a method getZakat() and a constant,
ZAKAT_RATE= 0.025
(b).Write a class, IslamicBankAccount, that implements Zakatable. It has
methods: deposit, withdraw, getBalance, and addDivident, which is used to
add profit or loss to the account.
(c).Modify the Employee abstract class so that it implements Zakatable.
(d).Write a test class, that has two methods: void PrintZakat(Zakatable o) that
prints the zakat from any zakatable object, o; and a main method that creates
instances of MonthlyEmployee and IslamicBankAccount and print their
zakat.
06/12/25
Sahalu Junaidu Unit 01
04 58
Packages
• What is a Package?
• Creating a Package
• Naming a Package
• Visibility Modifiers
06/12/25
Sahalu Junaidu Unit 01
05 59
What is a Package?
• The classes in Java API are organized into packages. For example:
06/12/25
Sahalu Junaidu Unit 01
05 60
Why use Packages?
• You can allow classes within a package to have access to each other.
06/12/25
Sahalu Junaidu Unit 01
05 61
Creating a Package
• To create a package, you put a package statement at the top of each source file for the class or interface that belongs to the package.
• For example, suppose we want to create a package, graphics, to store our shape classes, namely, Shape, Circle, Rectangle, and
Square.
• Then we should add the statement, package graphics; as the first statement in each of the source files.
06/12/25
Sahalu Junaidu Unit 01
05 62
Creating a Package-Cont’d
06/12/25
Sahalu Junaidu Unit 01
05 63
Naming a Package
• By convention, packages are named using lower case letters.
• Dots are also used to group related packages together.
• For example, the packages: java.awt, java.io, java.lang, are named as such to
indicate that they all belong to Java API.
• Similarly, java.awt.color, java.awt.geom, java.awt.event, are named as such to
indicate that they all belong to a group of classes for programming GUI
applications.
• Notice that this grouping is for the human reader only. As far as the system is
concerned, the packages java.awt.color is completely independent of
java.awt.geom.
06/12/25
Sahalu Junaidu Unit 01
05 64
Naming a Package-Cont’d
• Within one organization, it is clear that packages can be used to avoid
conflict in class names. What about between different organizations?
• We shall name our packages in this course starting with the prefix, ics201.
Example: ics201.graphics, ics201.lab01, etc.
06/12/25
Sahalu Junaidu Unit 01
05 65
Using Package Members
06/12/25
Sahalu Junaidu Unit 01
05 66
Referring to a Package Member by Full
Name
• So far, our examples have referred to classes and interfaces by their simple
names, such as Rectangle.
• You can use a package member’s simple name if:
– The code you are writing is in the same package as the member
– If the members package has been imported.
• However, if a member is from a different package and that package has not
been imported, you must use the member’s fully qualified name:
ics201.graphics.Rectangle
• To create an instance of the member we use:
ics201.graphics.Rectangle myRect = new ics201.graphics.Rectangle();
06/12/25
Sahalu Junaidu Unit 01
05 67
Importing a Package Member
• To import a specific package member into the current file, put an import
statement at the beginning the file before any class or interface definitions but
after the package statement, if there is one.
1. package ics201.lab02;
2. import ics201.graphics.Shape;
3. import ics201.graphics.Rectangle;
4. import ics201.graphics.Square;
5. import ics201.graphics.Circle;
06/12/25
Sahalu Junaidu Unit 01
05 68
Importing an Entire Package
• To import all of the classes and interfaces contained in a particular package, use
the asterisk (*).
1. package ics201.lab02;
2. import ics201.graphics.*;
3. public class TestShapes{
4. public static void main(String[] args){
5. Shape[] shape = new Shape[2];
6. shape[0] = new Rectangle(5, 10);
7. shape[0] = new Square(10);
8.
9. for(int i=0; i< shape.length; i++)
10. System.out.println(shape[i]);
11. }
12. }
06/12/25
Sahalu Junaidu Unit 01
05 69
Importing an Entire Package-
Cont’d
• Also note that the asterisk cannot be used to match a subset of a package.
For example, the following does not match all the classes in the graphics
package that begin with a:
• For convenience, the Java runtime system automatically imports three entire
packages:
o The default package (the package with no name)
o The java.lang package
o The current package
• What if two packages have classes with the same name and both packages are
imported? -- You must use fully qualified names.
06/12/25
Sahalu Junaidu Unit 01
05 70
Managing Source and Class
Files
• Declaring package names at the beginning of source files is what is
required to create a package.
• However, for the Java system to locate your source and class files, you
must store them in a directory whose name matches the name of their
package.
• For example, the source code for the Rectangle class should be in a file,
Rectangle.java, and must be in a directory, ics201\graphics. The ics201\
graphics directory can be anywhere on the file system.
06/12/25
Sahalu Junaidu Unit 01
05 71
Managing Source and Class Files-
Cont’d
• Note however, that the .class and .java files do not have to be in the same
directory as shown below:
• Since the directory structure can be anywhere in the file system, it is obvious
that the package name alone does not provide a java tool, such as the
Compiler, with all the information need to locate a class.
• The balance of the information is provided by class path.
06/12/25
Sahalu Junaidu Unit 01
05 72
Managing Source and Class Files-
Cont’d
• A class path is an ordered list of directories or jar files in which to search
for class files.
• Each directory listed in the class path is a top-level directory in which
package directories appear.
• For example, suppose that both .java and .class files for the ics201.graphics
package are stored in the same directory. Suppose also that the directory
structure for the package is in a directory z:\cs, as shown below, then we
must add z:\cs to the class path:
06/12/25
Sahalu Junaidu Unit 01
05 73
Visibility Modifiers
• Now that we have learnt about packages, this is a good time to summarize
what we learnt about visibility modifiers.
• Visibility modifiers are used to allow/deny access to other classes or
interfaces.
• There are four of them, namely, public, private, and protected. The fourth,
the default, does not have a keyword, but is assumed if none of the other
three is specified.
06/12/25
Sahalu Junaidu Unit 01
05 74
Example
1. package package1;
2. public class A{
3. public A(){
4. System.out.println("Inside Class A");
5. }
6. int method1(int x){
7. return x*x;
8. }
9. public int method2(int x){
10. return method1(x) + method1(x);
11. }
12. }
06/12/25
Sahalu Junaidu Unit 01
05 75
Example (cont’d)
1. package package2;
2. import package1.*;
3. public class B extends A{
4. public B(){
5. System.out.println("Inside Class B");
6. }
7. public int method1(int x){
8. A a = new B();
9. return a.method2(x);
10. }
11. public int method2(int x){
12. return x;
13. }
14. public static void main(String [] x){
15. B b = new B();
16. System.out.println(b.method1(3));
17. }
18. }
06/12/25
Sahalu Junaidu Unit 01
05 76
Exercises
1. Add the statement: package ics202.graphics; to each of our shape classes,
except TestShape. Store all the files in some root folder. Try compiling and
running the TestShape class. What happens?
2. Create a folder, ics201\graphics, and store the shape files in it, except the
TestShape class. Do not put any import statement in the TestShape. Try
compiling and running TestShape. What happens?
3. Add the import statement, import ics201.graphics.*; to TestShape Try
compiling and running TestShape without giving the class path for the
ics201.graphics package. What happens?
4. Try compiling and running TestShape, giving the class path for the
ics201.graphics package. It should compile and run successfully.
5. Try each of the methods of importing classes discussed in this session and
the TestShape class.
6. Add the import statement; java.awt.*; What happens? How can this
problem be resolved?
06/12/25
Sahalu Junaidu Unit 01
05 77
Java Virtual Machine (JVM)
• What is Java Virtual Machine?
• The Class Loader Subsystem
• Linking
o Verification
o Preparation
o Resolution
• Class Initialization
• Class Instantiation
06/12/25
Sahalu Junaidu Unit 01
06 78
What is JVM
• JVM is a component of the Java system that interprets and executes the
instructions in our class files.
• The following figure shows a block diagram of the JVM that includes its
major subsystems and memory areas.
06/12/25
Sahalu Junaidu Unit 01
06 79
What is JVM Cont’d
• Each instance of the JVM has one method area, one heap, and one or
more stacks - one for each thread.
• When JVM loads a class file, it puts its information in the method area.
• As the program runs, all objects instantiated are stored in the heap.
• The stack area is used to store activation records as a program runs.
06/12/25
Sahalu Junaidu Unit 01
06 80
The Class Loader Subsystem
• The class loader performs three main functions of JVM, namely: loading,
linking and initialization.
• The linking process consists of three sub-tasks, namely, verification,
preparation, and resolution, as shown by the following figure.
• Loading means reading the class file for a type, parsing it to get its
information, and storing the information in the method area.
• For each type it loads, the JVM must store the following kinds of
information in the method area:
• The fully qualified name of the type
• The fully qualified name of the type's direct superclass or if the type is an
interface, a list of its direct super interfaces .
• Whether the type is a class or an interface
• The type's modifiers ( public, abstract, final, etc)
• Constant pool for the type: constants and symbolic references.
• Field info : name, type and modifiers of variables (not constants)
• Method info : name, return type, number & types of parameters,
modifiers, bytecodes, size of stack frame and exception table.
06/12/25
Sahalu Junaidu Unit 01
06 82
Class Loading – Cont’d
• The end of the loading process is the creation of an instance of java.lang.Class for
the loaded type.
• The purpose is to give access to some of the information captured in the method
area for the type, to the programer.
• Some of the methods of the class java.lang.Class are:
• Note that for any loaded type T, only one instance of java.lang.Class is created even
if T is used several times in an application.
• To use the above methods, we need to first call the getClass method on any instance
of T to get the reference to the Class instance for T.
06/12/25
Sahalu Junaidu Unit 01
06 83
Class Loading –Cont’d
1. import java.lang.reflect.Method;
2. //you must import your Circle class
3. public class TestClassClass{
4. public static void main(String[] args){
5. Circle circle = new Circle(10);
6. Class circleClassInfo = circle.getClass();
7. System.out.println("Class name is :"+circleClassInfo.getName());
8. System.out.println("Parent is :"+circleClassInfo.getSuperclass());
9. Method[] methods = circleClassInfo.getMethods();
10. System.out.println("\nMethods are: ");
11. for(int i = 0; i<methods.length; i++)
12. System.out.println(methods[i]);
13. }
14. }
06/12/25
Sahalu Junaidu Unit 01
06 84
Class Loading – Cont’d
• What if we do not have an object of a class T? Use the following.
1. import java.lang.reflect.Method;
2. public class TestClassClass{
3. public static void main(String[] args) throws Exception {
4. Class test = Class.forName("TestClassClass");
5. System.out.println("\nClass name is: "+test.getName());
6. System.out.println("Superclass is: "+test.getSuperclass());
7. System.out.println("\nMethods are: ");
8. Method[] methods = test.getMethods();
9. for(int i = 0; i<methods.length; i++)
10. System.out.println(methods[i]);
11. }
12. }
06/12/25
Sahalu Junaidu Unit 01
06 85
Linking : Verification
• The next process handled by the class loader is Linking. This involves
three sub-processes: Verification, Preparation and Resolution.
• Verification is the process of ensuring that binary representation of a class
is structurally correct.
• The JVM has to make sure that a file it is asked to load was generated by a
valid compiler and it is well formed.
• Class B may be a valid sub-class of A at the time A and B were compiled,
but class A may have been changed and re-compiled.
• Example of some of the things that are checked at verification are:
– Every method is provided with a structurally correct signature.
– Every instruction obeys the type discipline of the Java language
– Every branch instruction branches to the start not middle of another
instruction.
06/12/25
Sahalu Junaidu Unit 01
06 86
Preparation
• In this phase, the Java virtual machine allocates memory for the class (i.e
static) variables and sets them to default initial values.
• Note that class variables are not initialized to their proper initial values
until the initialization phase - no java code is executed until initialization.
• The default values for the various types are shown below:
06/12/25
Sahalu Junaidu Unit 01
06 87
Resolution
• Resolution is the process of replacing symbolic names for types, fields and
methods used by a loaded type with their actual references.
• Symbolic references are resolved into a direct references by searching through
the method area to locate the referenced entity.
• For the class below, at the loading phase, the class loader would have loaded the
classes: TestClassClass, Circle, Shape, System, & Object.
1. public class TestClassClass{
2. public static void main(String[] args){
3. Circle circle = new Circle(10);
4. Class circleClassInfo = circle.getClass();
5. System.out.println("Parent is: "+circleClassInfo.getSuperclass());
6. }
7. }
• The names of these classes would have been stored in the constant pool for
TestClassClass.
• In this phase, the names are replaced with their actual references.
06/12/25
Sahalu Junaidu Unit 01
06 88
Class Initialization
• This is the process of setting class variables to their proper initial values - initial values desired by the programer .
1. class Example1{
2. static double rate = 3.5;
3. static int size = 3*(int)(Math.random()*5);
4. ...
5. }
• Initialization of a class consists of two steps:
– Initializing its direct superclass (if any and if not already initialized)
– Executing its own initialization statements
• The above imply that, the first class that gets initialized is Object.
• Note that static final variables are not treated as class variables but as constants and are assigned their values at
compilation.
1. class Example2{
2. static final int angle = 35;
3. static final int length = angle * 2;
4. ...
5. }
06/12/25
Sahalu Junaidu Unit 01
06 89
Class Instantiation
• After a class is loaded, linked, and initialized, it is ready for use. Its static
fields and static methods can be used and it can be instantiated.
• When a new class instance is created, memory is allocated for all its
instance variables in the heap.
• Memory is also allocated recursively for all the instance variables declared
in its super class and all classes up is inheritance hierarchy.
• All instance variables in the new object and those of its superclasses are
then initialized to their default values.
• The constructor invoked in the instantiation is then processed according to
the rules shown on the next page.
• Finally, the reference to the newly created object is returned as the result.
06/12/25
Sahalu Junaidu Unit 01
06 90
Class Instantiation – Cont’d
06/12/25
Sahalu Junaidu Unit 01
06 91
Example of Class Instantiation 1
1. class GrandFather{
2. int grandy = 70;
3. public GrandFather(int grandy){
4. this.grandy = grandy;
5. System.out.println("Grandy: "+grandy);
6. }
7. }
8. class Father extends GrandFather{
9. int father = 40;
10. public Father(int grandy, int father){
11. super(grandy);
12. this.father = father;
13. System.out.println("Grandy: "+grandy+" Father: "+father);
14. }
15. }
16. class Son extends Father{
17. int son = 10;
18. public Son(int grandy, int father, int son){
19. super(grandy, father);
20. this.son = son;
21. System.out.println("Grandy: "+grandy+" Father: "+father+" Son: "+son);
22. }
23. }
24. public class Instantiation{
25. public static void main(String[] args){
26. Son s = new Son(65, 35, 5);
27. }
28. } 06/12/25
Sahalu Junaidu Unit 01
06 92
Example of Class Instantiation 2
1. class Super {
2. Super() { printThree(); }
3. void printThree() {
4. System.out.println("three");
5. }
6. }
7. class Test extends Super {
8. int three = (int)Math.PI; // That is, 3
9. public static void main(String[] args) {
10. Test t = new Test();
11. t.printThree();
12. }
13. void printThree() {
14. System.out.println(three);
15. }
16.}
06/12/25
Sahalu Junaidu Unit 01
06 93
Exercises
1. Write a program to show that each loaded type has only one instance of
java.lang.Class associated with it, irrespective of how many times it is
used in a class.
2. Write a program to show that Loading may be caused either by creating
an instance of a class or by accessing a static member.
3. Write a class to show that class variables are initialized with their default
values when loaded. Also show that instance variables are initialized
with their default values when an object is created.
4. Demonstrate that Verification actually takes place in the Loading
process. To do this, write a class, Base, and a class, SubClass, that
extends Base. Compile both classes. Then modify Base by changing the
signature of one of its methods and compile it alone. Now write a test
program that uses Subclass and try to compile and run it.
06/12/25
Sahalu Junaidu Unit 01
06 94
Nested Classes
• Learning Outcomes
o List and distinguish between the different categories of nested classes.
o List and explain four applications/benefits of nested classes.
o Use nested classes in applications development.
• Introduction
• static Member Classes
• Non-static Member Classes
• Local Classes
• Anonymous Classes
• Exercises
06/12/25
Sahalu Junaidu Unit 01
07 95
Introduction to Nested Classes
• So far, our classes and interfaces were defined at top-level.
06/12/25
Sahalu Junaidu Unit 01
07 96
Introduction to Nested Classes
(cont’d)
• There are four categories of nested classes in Java:
1. static member classes and interfaces.
2. Member classes
3. Local classes.
4. Anonymous classes.
• static member classes and interfaces are defined with the static
keyword.
• Member, local and anonymous classes are non-static, collectively called
inner classes.
• Member classes are defined inside a class while local and anonymous
classes are defined inside a block of Java code.
• We refer to both static and non-static classes as nested classes.
06/12/25
Sahalu Junaidu Unit 01
07 97
Nested Classes at a Glance
1 class OuterClass{
2 static class StaticMemberClass {
3 // ...
4 }
5 static interface StaticMemberInterface{
6 void f();
7 }
8 class MemberClass {
9 // ...
10 }
11 public void myMethod(){
12 class LocalClass {
13 // ...
14 }
15 }
16 public StaticMemberInterface myMethod2(){
17 return new StaticMemberInterface(){
18 public void f(){}
19 };
20 }
21 }
06/12/25 Unit 01
07 98
Why Nested Classes?
06/12/25
Sahalu Junaidu Unit 01
07 99
static Member Classes
06/12/25
Sahalu Junaidu Unit 01
07 100
Introducing Our Working
Example
• Our working example involves a Course class containing students’ grades:
06/12/25
Sahalu Junaidu Unit 01
07 101
Example 1: static Member
Classes
1 import java.util.*;
2 class Course1{
3 private static double [] grades;
4 interface MaxMin{ void bestAndWorst();}
5 static class Pair implements MaxMin{
6 private double best;
7 private double worst;
8 public String toString(){
9 return "Best grade: "+best+"\nWorst grade: "+worst+"\n";
10 }
11 public void bestAndWorst(){
12 if(grades.length > 0){
13 best = grades[0];
14 worst = grades[0];
15 for(int i=1; i<grades.length; i++){
16 if (best < grades[i]) best = grades[i];
17 else if (worst > grades[i]) worst = grades[i];
18 }
19 }
20 }
21 }
06/12/25
Sahalu Junaidu Unit 01
07 102
Example 1 (cont’d)
22 Course1(int size){
23 grades = new double[size];
24 for(int i=0; i<size; i++)
25 grades[i] = 100*Math.random();
26 }
27 public MaxMin getPair(){
28 return new Pair();
29 }
30 }
31 public class Course1Test{
32 public static void main(String [] args){
33 Course1 c1 = new Course1(10);
34 Course1.MaxMin cs = new Course1.Pair();
35 cs.bestAndWorst();
36 System.out.println(cs);
37 }
38 }
06/12/25
Sahalu Junaidu Unit 01
07 103
Non-static Member Classes
• A member class is defined as a non-static member
of another class.
• A member class is analogous to an instance field or instance
method.
• Like other instance members, a member class can have any access
modifier.
• Every instance of a member class is linked with an instance of the
containing class.
• Member classes cannot have static fields, static methods or static
classes.
• Interfaces cannot be defined as member classes. Why?
06/12/25
Sahalu Junaidu Unit 01
07 104
Example 2: Member Classes
1 protected class Pair implements MaxMin{
2 public void bestAndWorst(){
3 if(grades.length > 0){
4 best = grades[0];
5 worst = grades[0];
6 for(int i=1; i<grades.length; i++){
7 if (best < grades[i]) best = grades[i];
8 else if (worst > grades[i]) worst = grades[i];
9 }
10 }
11 }
12 }
13 public class Course2Test{
14 public static void main(String [] args){
15 Course2 c2 = new Course2(10);
16 Course2.MaxMin cs = c2.new Pair();
17 cs.bestAndWorst();
18 System.out.println(cs);
19 }
20 }
06/12/25
Sahalu Junaidu Unit 01
07 105
Example 3: Can We Override
Member Classes
1 class Course3{
2 public Course3(){
3 System.out.println("Couse3 constructor.");
4 new Pair();
5 }
6 protected class Pair {
7 public Pair(){
8 System.out.println("Course3.Pair constructor.");
9 }}
10 }
11 class OverridingMemberClass extends Course3{
12 public OverridingMemberClass(){
13 System.out.println("OverridingMemberClass constructor.");
14 }
15 protected class Pair {
16 public Pair(){
17 System.out.println("OverridingMemberClass.Pair constructor."); }
18 }
19 public static void main(String [] args){
20 new OverridingMemberClass();
21 }
22 }
06/12/25
Sahalu Junaidu Unit 01
07 106
Example 3b: Inheriting Member
Classes
1 class Course4{
2 public Course4(){
3 System.out.println("Course4 constructor.");
4 }
5 protected class Pair {
6 public Pair(){
7 System.out.println("Course4.Pair constructor.");
8 }
9 void f(){
10 System.out.println("Method f() From Course4.Pair.");
11 }
12 }
13 }
14 class InheritingMemberClass extends Course4{
15 public InheritingMemberClass(){
16 System.out.println("InheritingMemberClass constructor.");
17 new Pair().f();
18 }
19 public static void main(String [] args){
20 new InheritingMemberClass().new Pair();
21 }
22 }
06/12/25
Sahalu Junaidu Unit 01
07 107
Using this Keyword in
Member Classes
• The this reference is applicable inside member classes.
• From within an instance of a member class we can refer to two
objects.
06/12/25
Sahalu Junaidu Unit 01
07 108
Example 4: Keyword this in
Member Classes
// code omitted
// code omitted
06/12/25
Sahalu Junaidu Unit 01
07 109
Review Exercises (cont’d)
3. Use appropriate examples to explain how nested classes provide
additional support for object orientation, code organization and
multiple implementation inheritance.
4. Can an interface be defined inside a member class? Give an
example or a counter example.
5. Compare and contrast static member classes and member classes.
6. Write a complete program to illustrate how to access object of an
outer class from an object of the inner class.
7. Let B be a member class inside another class A. Let another class
C extend B. Is it possible for class C to have a no-arg constructor?
06/12/25
Sahalu Junaidu Unit 01
07 110
Introduction to GUI Programming
• Learning Outcomes
o Explain the motivation for, and usefulness of GUIs.
o List and explain seven principles of good GUI design and their
benefits.
o Discuss what GUI programming involves, and explain how Java's
GUI library evolved.
• Introduction to User Interfaces
• GUI Design Issues
• GUI Programming Issues
• Self-check Exercise
• Java GUI Library Evolution
• Exercises
06/12/25
Sahalu Junaidu Unit 01
08 111
Introduction to User Interfaces
• A user interface (UI) is that part of a program that interacts with the user .
• A user interface can be based on text or graphics.
• In a text-based UI the commands are entered from the keyboard.
• In a graphical UI the user interacts with GUI objects.
• In a console program, the system usually
06/12/25
Sahalu Junaidu Unit 01
08 112
Principles of GUI Design
06/12/25
Sahalu Junaidu Unit 01
08 113
Benefits of Good GUIs
06/12/25
Sahalu Junaidu Unit 01
08 114
GUI Programming Issues
1. Graphics
2. Media
3. Windows
4. Events
5. Multithreading
06/12/25
Sahalu Junaidu Unit 01
08 115
Java GUI API Evolution
06/12/25
Sahalu Junaidu Unit 01
08 116
Java GUI API Evolution (cont'd)
• However, GUI components in AWT are abstract and rely on native peers.
06/12/25
Sahalu Junaidu Unit 01
08 117
Review Exercises
06/12/25
Sahalu Junaidu Unit 01
08 118
Java GUI Components and Events
Learning Outcomes
o Distinguish between GUI components and containers.
o Identify and distinguish top-level containers from other containers.
o Write simple programs to add components into containers.
o Explain what Events are, and distinguish between Event sources, Event
classes and Event listeners.
GUI Components and Containers
Swing's Top-level Containers
Adding Components to Containers
Self-check Exercise 1
GUI Events
GUI Events Classes
Self-check Exercise 2
Exercises
06/12/25
Sahalu Junaidu Unit 01
09 119
Introduction to Components
• A component is an object having a graphical representation that can be
displayed on the screen.
06/12/25
Sahalu Junaidu Unit 01
09 120
Introduction to Containers
A container is a special component that can hold other components.
• Example of containers in typical
GUI applications include:
o panels, windows, applets, frames
06/12/25
Sahalu Junaidu Unit 01
09 121
Swing’s Top-level Containers
06/12/25
Sahalu Junaidu Unit 01
09 122
Anatomy of Top-level Containers
• Each top-level container has only one component, JRootPane.
• The root pane consists of three other containers: the layered, content
and glass panes:
06/12/25
Sahalu Junaidu Unit 01
09 123
Anatomy of Top-level Containers
(cont’d)
• The root pane has a glass pane on top and a layered pane underneath.
• The glass pane component is
always painted last and appears
on top of the content pane and
menu bar.
06/12/25
Sahalu Junaidu Unit 01
09 127
Events Classes Hierarchy
• Event classes represent events and contain methods for getting information
on the events.
06/12/25
Sahalu Junaidu Unit 01
09 128
Events Source Classes
06/12/25
Sahalu Junaidu Unit 01
09 130
Events: A Pictorial View
06/12/25
Sahalu Junaidu Unit 01
09 131
Exercises
1. The Panel, Window and JComponent class each subclasses Component class.
Write down the similarities and differences between these classes in a tabular form.
2. Write down in tabular form the similarities and differences between top-level
components and other GUI components.
3. Write a Java program to display three frames as follows. The top-left corner of the
second frame should have the same coordinates as the bottom-right corner of the
first frame. Similarly, the top-left corner of the third frame should have the same
coordinates as the bottom-right corner of the second frame.
4. Run the program in Example 2. Try resizing the window and watch how the
components placements change. Modify this program by adding four more buttons.
Remove the setSize method call and replace it with the call to the pack method.
Re-run the program and notice the output.
5. Write short notes on
a. Event classes
b. Event sources
c. Event listeners
06/12/25
Sahalu Junaidu Unit 01
09 132
Event-Driven Programming
• Learning Outcomes
o Extend the example programs to write more interesting GUI
o Use nested classes and adapter classes to write medium-sized applications.
• Example 1: Handling Button Events
• Example 2: Handling Mouse Events
• Example 3: Handling Keyboard Events
• Self-check Exercise 1
• Adapter Classes
• Example 4: Handling Window Events
• Example 5: Handling Text Field Events
• Self-check Exercise 2
• Exercises
06/12/25
Sahalu Junaidu Unit 01
10 133
Handling Button Events
06/12/25
Sahalu Junaidu Unit 01
10 134
Example 1: Button Events
1 import java.awt.*;
2 import java.awt.event.*;
3 class ButtonEventTest extends AddingComponents
4 implements ActionListener{
5 private int sum;
6 public ButtonEventTest() {
7 button.addActionListener(this);
8 }
9 public void actionPerformed(ActionEvent ae) {
10 sum += 1;
11 textField.setText(sum+"");
12 Toolkit.getDefaultToolkit().beep();
13 }
14 public static void main(String args []) {
15 new ButtonEventTest();
16 }
17 }
06/12/25
Sahalu Junaidu Unit 01
10 135
Handling Mouse Events
• This example illustrates how mouse events can be responded to.
• It also shows how a single listener can register with many sources.
• The event listener in this case will implement the MouseListener
interface.
• MouseListener consists of five methods:
06/12/25
Sahalu Junaidu Unit 01
10 136
Example 2: Mouse Events
1 import java.awt.*; import java.awt.event.*;
2 public class MouseEventTest extends ButtonEventTest{
3 public MouseEventTest(){
4 class LightUpListener extends MouseAdapter {
5 public void mouseEntered(MouseEvent e) {
6 Component c = (Component)e.getSource();
7 c.setBackground(Color.green);
8 }
9 public void mouseExited(MouseEvent e) {
10 Component c = (Component)e.getSource();
11 c.setBackground(Color.red);
12 }
13 }
14 MouseListener listener = new LightUpListener();
15 button.addMouseListener(listener);
16 textField.addMouseListener(listener);
17 cp.addMouseListener(listener);
18 }
19 public static void main(String[] args) {
20 new MouseEventTest();
21 }
22 }
06/12/25
Sahalu Junaidu Unit 01
10 137
Handling Keyboard Events
• This example illustrates how keyboard events can be responded to.
• To receive KeyEvent, a component must have keyboard focus.
• We will be implementing the KeyListener interface.
• KeyListener consists of three methods:
• Notice that when you press a key, at least two events are generated.
06/12/25
Sahalu Junaidu Unit 01
10 138
Example 3: Keyboard Events
1 import java.awt.*; import java.awt.event.*;
2 import javax.swing.JApplet;
3 public class KeyEventTest extends JApplet implements KeyListener{
4 private String msg = "";
5 private int startX = 10, startY = 10;
6 public void keyPressed(KeyEvent ke){
7 showStatus("Key Down");
8 }
9 public void keyReleased(KeyEvent ke){showStatus("Key Up"); }
10 public void keyTyped(KeyEvent ke){
11 msg += ke.getKeyChar();
12 repaint();
13 }
14 public void init(){
15 requestFocus();
16 addKeyListener(this);
17 }
18 public void paint(Graphics g){
19 g.drawString(msg,startX,startY);
20 }
21 }
06/12/25
Sahalu Junaidu Unit 01
10 139
Introduction to Adapter
Classes
• From previous examples, listener interfaces can have several
methods.
• A particular listener may not be
interested in all the methods.
• Nevertheless, the listener must implement
all methods in the interface.
• Java provides adapter classes for
implementing handlers selectively.
• Adapter classes provide empty implementations for the handlers.
• Most listener interfaces with two or more methods have matching
adapter classes.
06/12/25
Sahalu Junaidu Unit 01
10 140
Handling Window Events
• This example shows how window events can be handled.
• The listener should implement the WindowListener interface.
• WindowListener consists of seven methods:
06/12/25
Sahalu Junaidu Unit 01
10 141
Example 4: Window Events
1 import javax.swing.*;import java.awt.event.*;
2 class WindowEventTest extends JFrame{
3 private String msg = "Are you sure you want to Quit Window?";
4 public WindowEventTest() {
5 super("Window Event Test"); setSize(300,300);
6 addWindowListener(new WindowAdapter(){
7 public void windowClosing(WindowEvent we) {
8 WindowEventTest obj = WindowEventTest.this;
9 int result = JOptionPane.showConfirmDialog(obj, msg);
10 if (result == JOptionPane.YES_OPTION)
11 System.exit(0);
12 else {
13 int keepOpen = WindowConstants.DO_NOTHING_ON_CLOSE;
14 setDefaultCloseOperation(keepOpen);
15 }
16 }});
17 }
18 public static void main(String args [] ) {
19 WindowEventTest wt = new WindowEventTest();
20 wt.setVisible(true);
21 }
22 }
06/12/25
Sahalu Junaidu Unit 01
10 142
Handling Text Field Events
• This example shows how texfield events are generated and handled.
• It also illustrates the use of multiple handlers.
• Two text fields are shown handling an ActionEvent in different ways.
• The program implements Celcius to Fahrenheit temperature conversions.
• You enter a temperature value in one text
06/12/25
Sahalu Junaidu Unit 01
10 143
Example 5: Text Field Events
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4 class TextFieldEventTest extends JFrame{
5 JTextField celcius = new JTextField(10);
6 JTextField fahrenheit = new JTextField(10);
7 Container c = getContentPane();
8 TextFieldEventTest(){
9 c.setLayout(new FlowLayout());
10 c.add(new JLabel("Celcius"));
11 c.add(celcius);
12 celcius.addActionListener(new ActionListener() {
13 public void actionPerformed(ActionEvent ae){
14 String cString = celcius.getText();
15 double cValue = Double.parseDouble(cString.trim());
16 double fValue = cValue*9.0/5.0+32.0;
17 fahrenheit.setText((int)fValue+"");
18 }
19 });
// code continues next page
06/12/25
Sahalu Junaidu Unit 01
10 144
Text Field Events – Cont’d
20 c.add(new JLabel("Fahrenheit"));
21 c.add(fahrenheit);
22 fahrenheit.addActionListener(new ActionListener() {
23 public void actionPerformed(ActionEvent ae){
24 String fString = fahrenheit.getText();
25 double fValue = Double.parseDouble(fString.trim());
26 double cValue = (fValue-32.0)*5.0/9.0;
27 celcius.setText((int)cValue+"");
28 }
29 });
30 } // end of constructor
31 public static void main(String [] args){
32 TextFieldEventTest t = new TextFieldEventTest();
33 t.pack();
34 t.show();
35 }
36 }
06/12/25
Sahalu Junaidu Unit 01
10 145
Review Exercises
1. Extend Example 1 by adding a Reset Total button. When the
Reset Total button is pushed, the running total should be reset to
zero.
2. Modify the program in Example 2 to work as a stand-alone application.
3. Modify the program in Example 3 to display its output on the
application’s JFrame window.
4. Modify the program in Example 4 to use an anonymous inner class to
implement the windowClosing() handler method.
5. Extend Example 5 to validate the data entered in both text fields to avoid
the spurious exceptions currently raised when invalid characters are
included in the input.
06/12/25
Sahalu Junaidu Unit 01
10 146
Review Exercises (cont’d)
6. A student has written a working applet. Write a step-by-step procedure
that guides the student to make his applet work as an application also.
7. Consider the program in Example 1. Write down all the events
generated from the time the frame is displayed up to the time the user
pushes the PushMe button. You may restrict your answer to the events
covered in this section.
06/12/25
Sahalu Junaidu Unit 01
10 147
GUI Layout Managers
• Learning Outcomes
o List and distinguish between the four most common, standard layout
managers in Java.
o Use these and other layout managers to build good GUI applications.
• Introduction
• FlowLayout Manager
• GridLayout Manager
• Self-check Exercise 1
• BorderLayout Manager
• GridBagLayout Manager
• Self-check Exercise 2
• Exercises
06/12/25
Sahalu Junaidu Unit 01
11 148
Introduction to GUI Layout
Managers
• A layout manager determines the placement of components with a
container.
• Each container has a default layout manager.
• A new layout manager can be installed using the setLayout method.
• Each layout manager implements
one of the two interfaces:
LayoutManger or LayoutManger2.
• Here are some common standard
layout managers of Java:
o FlowLayout
o GridLayout
o BorderLayout
o GridBagLayout
06/12/25
Sahalu Junaidu Unit 01
11 149
Introduction to Flow Layout
• FlowLayout places components sequentially from left to right in the order added.
• Components placement depends on the current size of the container.
• When the container is resized the components are automatically repositioned.
• FlowLayout is the default layout
for panels.
• FlowLayout has three constructors:
o FlowLayout()
o FlowLayout(int align)
06/12/25
Sahalu Junaidu Unit 01
11 150
Example 1: Flow Layout Test
1 import javax.swing.*;
2 class TestFlowLayout extends JFrame{
3 JPanel panel = new JPanel();
4 public TestFlowLayout(){
5 panel.add(new JButton("1"));
6 panel.add(new JButton("2"));
7 panel.add(new JButton("3"));
8 panel.add(new JButton("4"));
9 panel.add(new JButton("5"));
10 panel.add(new JButton("6"));
11 panel.add(new JButton("7"));
12 setContentPane(panel);
13 setSize(300,300);
14 setTitle("Flow Layout Test");
15 setVisible(true);
16 }
17 public static void main(String [] args){
18 new TestFlowLayout();
19 }
20 }
06/12/25
Sahalu Junaidu Unit 01
11 151
Introduction to Grid Layout
o GridLayout()
o GridLayout(int rows, int cols)
o GridLayout(int rows, int cols, int hgap, int vgap)
06/12/25
Sahalu Junaidu Unit 01
11 152
Example 2: Grid Layout Test
1 import java.awt.*; import javax.swing.*;
2 import javax.swing.border.*;
3 class TestGridLayout extends TestFlowLayout{
4 public TestGridLayout(){
5 panel.add(new JButton("8"));
6 panel.add(new JButton("9"));
7 panel.add(new JButton("*"));
8 panel.add(new JButton("0"));
9 panel.add(new JButton("#"));
10 JLabel jlb = new JLabel("03-860-4698", SwingConstants.CENTER);
11 Border b =BorderFactory.createBevelBorder(BevelBorder.RAISED);
12 jlb.setBorder(BorderFactory.createTitledBorder(b,"Telephone"));
13 panel.add(jlb);
14 setTitle("Grid Layout Test");
15 panel.setLayout(new GridLayout(0,3));
16 setVisible(true);
17 }
18 public static void main(String [] args){
19 new TestGridLayout();
20 }
21 }
06/12/25
Sahalu Junaidu Unit 01
11 153
Introduction to Border Layout
o BorderLayout()
06/12/25
Sahalu Junaidu Unit 01
11 156
Further GUI Programming
• Learning Outcomes
o Extend examples presented to write more useful applications.
o Write non-trivial, event-driven GUI applications.
• Introduction
• Example 1: Enhancing the Telephone Handset Example
• Example 2: Menu Test
• Self-check Exercise 1
• Example 3: File Dialog Test
• Example 4: Popup Menu Test
• Self-check Exercise 2
• Exercises
06/12/25
Sahalu Junaidu Unit 01
12 157
Introduction
06/12/25
Sahalu Junaidu Unit 01
12 158
Introduction to Example 1
06/12/25
Sahalu Junaidu Unit 01
12 159
Example 1: The Telephone Handset
1 import java.awt.*; import javax.swing.*; import java.awt.event.*;
2 class TelephoneTest extends TestGridBagLayout
3 implements ActionListener{
4 public TelephoneTest(){
5 Component components[] = getContentPane().getComponents();
6 JPanel cancelPanel = (JPanel)components[13];
7 JButton cancel = (JButton)cancelPanel.getComponent(0);
8 for(int i=0;i<components.length; i++){
9 if(components[i] instanceof JButton)
10 ((JButton)components[i]).addActionListener(this);
11 }
12 cancel.addActionListener(this);
13 }
14 public void actionPerformed(ActionEvent ae) {
15 if (ae.getActionCommand().equals("Cancel"))
16 display.setText("");
17 else
18 display.setText(display.getText()+ae.getActionCommand());
19 }
20 public static void main(String [] args){
21 new TelephoneTest().setVisible(true);
22 }}
06/12/25
Sahalu Junaidu Unit 01
12 160
Introduction to Example 2
• In this example we demonstrate how menus, separator,
mnemonic and accelerators can be added into an
application.
• The output of the example is as follows:
06/12/25
Sahalu Junaidu Unit 01
12 161
Class Hierarchy for Menus
06/12/25
Sahalu Junaidu Unit 01
12 162
Details of Program Output
06/12/25
Sahalu Junaidu Unit 01
12 163
Example 2: Menus and Mnemonics
1 import java.awt.event.*;
2 import javax.swing.*;
3 class MenuTest extends JFrame {
4 private JMenuBar menuBar = new JMenuBar();
5 protected JMenu fileMenu = new JMenu("File");
6 protected JMenuItem neW, open, quit, save, print;
7 private JMenuItem saveCurrent, saveAs, saveAll;
8 MenuTest(String title){
9 super(title);
10 setJMenuBar(menuBar);
11 menuBar.add(fileMenu);
12 fileMenu.setMnemonic('F');
13 fileMenu.add(neW = new JMenuItem ("New"));
14 fileMenu.add(open = new JMenuItem ("Open"));
15 open.setMnemonic('o');
16 fileMenu.add(save = new JMenu ("Save"));
17 save.add(saveCurrent = new JMenuItem ("Save Current"));
18 save.add(saveAs = new JMenuItem ("Save As"));
19 save.add(saveAll = new JMenuItem ("Save All"));
20 fileMenu.add(save);
21 fileMenu.add(print = new JCheckBoxMenuItem ("Print"));
22 fileMenu.addSeparator();
06/12/25
Sahalu Junaidu Unit 01
12 164
Menus and Mnemonics (cont’d)
06/12/25
Sahalu Junaidu Unit 01
12 165
Introduction to Example 3
06/12/25
Sahalu Junaidu Unit 01
12 166
Example 3: File Dialog Test
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4 class FileDialogTest extends MenuTest {
5 JEditorPane textPane= new JEditorPane();
6 FileDialogTest(String title){
7 super(title);
8 open.addActionListener( new ActionListener() {
9 public void actionPerformed(ActionEvent e ) {
10 FileDialog fd = new FileDialog(FileDialogTest.this);
11 fd.setVisible(true);
12 textPane.setText("Selected file: "+fd.getFile());
13 } });
14 getContentPane().add(textPane);
15 }
16 public static void main(String args[]){
17 FileDialogTest t = new FileDialogTest("File Dialog Test");
18 t.setVisible(true);
19
20 }
21 }
06/12/25
Sahalu Junaidu Unit 01
12 167
Introduction to Example 4
• This example extends Example 2 of the preceding section to add pop-up
menus..
• The output looks like:
• The menu consists of three colors that can be used to reset a component’s
background color.
06/12/25
Sahalu Junaidu Unit 01
12 168
Example 4: Popup Menu Test
1 import java.awt.*; import java.awt.event.*; import javax.swing.*;
2 public class PopupMenuTest extends TestGridLayout{
3 Component selectedComponent;
4 JPopupMenu colorMenu = new JPopupMenu();
5 JMenuItem blue, white, yellow;
6 public PopupMenuTest(){
7 setTitle("Popup Menu Test");
8 colorMenu.add(blue=new JMenuItem("Blue"));
9 colorMenu.add(white=new JMenuItem("White"));
10 colorMenu.add(yellow=new JMenuItem("Yellow"));
11 Component components[] = getContentPane().getComponents();
12 class MyListener extends MouseAdapter {
13 public void mousePressed(MouseEvent e){checkPopup(e);}
14 public void mouseClicked(MouseEvent e){checkPopup(e);}
15 public void mouseReleased(MouseEvent e){checkPopup(e);}
16 public void checkPopup(MouseEvent e) {
17 if (e.isPopupTrigger()){
18 selectedComponent = e.getComponent();
19 colorMenu.show(e.getComponent(),e.getX(),e.getY());
20 }
21 }
22 }
06/12/25
Sahalu Junaidu Unit 01
12 169
Popup Menu Test (cont’d)
23 MouseListener mylistener = new MyListener();
24 for(int i=0;i<components.length-1; i++){
25 JButton b = (JButton)components[i];
26 b.addMouseListener(mylistener);
27 }
28 blue.addActionListener(new ActionListener () {
29 public void actionPerformed(ActionEvent ae){
30 selectedComponent.setBackground(Color.blue);
31 }});
32 white.addActionListener(new ActionListener() {
33 public void actionPerformed(ActionEvent ae){
34 selectedComponent.setBackground(Color.white);
35 }});
36 yellow.addActionListener(new ActionListener() {
37 public void actionPerformed(ActionEvent ae){
38 selectedComponent.setBackground(Color.yellow);
39 }});
40 }
41 public static void main(String[] args) {
42 new PopupMenuTest().setVisible(true);
43 }
44 }
06/12/25
Sahalu Junaidu Unit 01
12 170
Review Exercises
06/12/25
Sahalu Junaidu Unit 01
12 171
Introduction to Searching and
Sorting
• Comparable Interface
• Comparator Interface
• Exercises
06/12/25
Sahalu Junaidu Unit 01
13 172
The Comparable Interface
• The Comparable interface of java.lang
public interface Comparable{
public abstract int compareTo(Object object);
}
• This interface may be used to order objects of a class that have a natural ordering.
• Several core Java classes implement Comparable.
• A user defined class that implements Comparable should implement the
compareTo method such that : object1.compareTo(object2) is:
0 if object1 “is equal to” object2
>0 if object1 “is greater than” object2
<0 if object1 “is less than” object2
06/12/25
Sahalu Junaidu Unit 01
13 173
The Comparable Interface
(cont’d)
• It is also preferable for object1.compareTo(object2) to return 0 if and only if
object1.equals(object2) is true.
• The compareTo method throws a ClassCastException if the type of this object and the type
of the object passed as parameter are not compatible for comparison.
• Example:
1. public class BankAccount implements Comparable{
06/12/25
Sahalu Junaidu Unit 01
13 175
The Comparator Interface
• The Java collection framework is a set of important utility classes and interfaces in the
java.util package for working with collections.
• A collection is a group of objects.
• The Comparator interface is one of the collections framework interfaces.
• Comparator defines how collection objects are compared.
public interface Comparator{
06/12/25
Sahalu Junaidu Unit 01
13 177
The Comparator Interface
(cont’d)
• Note: Since each class inherits the equals method from the Object class, it is not necessary for
a class that implements the Comparator interface to implement the equals method.
• Example: The reverse Comparator for strings
1. import java.util.*;
2. public class StringReverseComparator implements Comparator{
• 3. public int compare(Object object1, Object object2){
• 4. String string1 = object1.toString();
• 5. String string2 = object2.toString();
• 6. // Reverse the comparison
• 7. return string2.compareTo(string1);
• 8. }
• 9. }
06/12/25
Sahalu Junaidu Unit 01
13 178
The Comparator Interface
(cont’d)
import java.util.*;
class BankAccount implements Comparable{
private int accountNumber;
protected String name;
private double balance;
// . . .
public int compareTo(Object object){
BankAccount account = (BankAccount) object;
if(accountNumber < account.accountNumber)
return -1;
else if(accountNumber == account.accountNumber)
return 0;
else
return 1;
}
public String toString(){
return "Account#: " + accountNumber + " , Name: "
+ name + " , Balance: " + balance + " SR";
}
06/12/25
Sahalu Junaidu Unit 01
13 179
Example 1: The Comparator Interface
1 import java.util.*;
2 class MyComparator implements Comparator {
3 public int compare(Object obj1, Object obj2) {
4 int i1 = ((Integer)obj1).intValue();
5 int i2 = ((Integer)obj2).intValue();
6 return Math.abs(i2) - Math.abs(i1);
7 }
8}
9 public class TestCollections {
10 public static void main(String args[]) {
11 ArrayList array = new ArrayList();
12 array.add(new Integer(-200));
13 array.add(new Integer(100));
14 array.add(new Integer(400));
15 array.add(new Integer(-300));
16 Collections.sort(array);
17 System.out.println("Natural ordering: " + array);
18 Collections.sort(array, new MyComparator());
19 System.out.println("My own ordering : " + array);
20 }
21 }
06/12/25
Sahalu Junaidu Unit 01
13 180
The Comparator Interface
(cont’d)
06/12/25
Sahalu Junaidu Unit 01
13 181
Algorithm Complexity Classes
• Different algorithms require different amount of running time and space.
• The less amount of running time the more time-efficient the algorithm.
• The less amount of space requirements the more space-efficient the algorithm.
• The resources (such as time and space) required to solve a problem usually increase
with an increase in the size n of the problem.
• Several factors affect the time and space requirements of an algorithm: hardware,
language of implementation, Compiler being used, etc.
• The average running time of an algorithm is a function f(n) of the problem size n.
• Algorithms are classified into different groups (called complexity classes) based on
f(n)
06/12/25
Sahalu Junaidu Unit 01
13 182
Algorithm Complexity Classes
(cont’d)
06/12/25
Sahalu Junaidu Unit 01
13 183
Exercises
06/12/25
Sahalu Junaidu Unit 01
13 184
Searching and Sorting
• Linear Search
• Binary Search
• Selection Sort
• Insertion Sort
• Exercises
06/12/25
Sahalu Junaidu Unit 01
14 185
Linear Search
• Searching is the process of determining whether or not a given value exists in
a data structure or a storage media.
• We discuss two searching methods on one-dimensional arrays: linear search
and binary search.
• The linear (or sequential) search algorithm on an array is:
– Sequentially scan the array, comparing each array item with the searched value.
– If a match is found; return the index of the matched element; otherwise return –1.
06/12/25
Sahalu Junaidu Unit 01
14 186
Binary Search
The binary search algorithm can only be applied to an array that
is sorted; furthermore, the order of sorting must be known.
The binary search algorithm for an array sorted in ascending
order is:
06/12/25
Sahalu Junaidu Unit 01
14 187
Binary Search (cont’d)
The algorithm translates to the following Java method:
public static int binarySearch(Object[] array, Object key,
Comparator comparator){
return binarySearch(array, key, 0, array.length - 1, comparator);
}
private static int binarySearch(Object[] array, Object key,
int low, int high, Comparator comparator){
if(low > high)
return -1;
else{
int middle = (low + high)/2;
int result = comparator.compare(key, array[middle]);
if(result == 0) return middle;
else if(result < 0)
return binarySearch(array, key, low, middle - 1, comparator);
else
return binarySearch(array, key, middle + 1, high, comparator);
}
}
06/12/25
Sahalu Junaidu Unit 01
14 188
Selection Sort
• We discuss five sorting algorithms on one-dimensional arrays.
• Sorting is the process of arranging data in a data structure or a storage media such that it is in
increasing or decreasing order of some key in the date.
• The pseudo-code for Selection sort algorithm to sort an array in increasing is:
selectionSort(array){
for(k = 0; k < array.length – 1; k++){
select the minimum element among array[k]...array[array.length – 1];
swap the selected minimum with x[k];
}
}
• To sort an array in decreasing order, the maximum element is selected in each iteration (or
pass) of the algorithm.
06/12/25
Sahalu Junaidu Unit 01
14 189
Selection Sort (cont’d)
public static void selectionSort(Object[] array, Comparator comparator){
int minPos = 0;
Object temp;
for(int i = 0; i < array.length - 1; i++){
minPos = i;
for(int k = i + 1; k < array.length; k++){
if(comparator.compare(array[k], array[minPos]) < 0)
minPos = k;
}
temp = array[minPos];
array[minPos] = array[i];
array[i] = temp;
}
}
06/12/25
Sahalu Junaidu Unit 01
14 190
Selection Sort (cont’d)
• To sort an array with k elements, Selection sort requires k – 1 passes.
• Example:
06/12/25
Sahalu Junaidu Unit 01
14 191
Insertion Sort
• The Insertion sort pseudo-code algorithm is:
insertionSort(array){
for(i = 1; i < array.length; i++){
temp = array[i];
insert temp in its proper location in the sorted subarray array[0]...array[i -1]
}
06/12/25
Sahalu Junaidu Unit 01
14 194
Bubble Sort
• The Bubble (Exchange) sort pseudo-code algorithm is:
bubbleSort(array){
numberOfPasses = 1;
while(numberOfPasses < array.length){
for(k = 1; k <= array.length – numberOfPasses; k++)
swap array[k-1] and array[k] if they are out of order;
numberOfPasses++;
}
• Note: If no swaps occur in an iteration of the for loop, the array is sorted. A boolean
variable may be used to terminate the while loop prematurely.
06/12/25
Sahalu Junaidu Unit 01
14 195
Bubble Sort (cont’d)
public static void bubbleSort(Object[] array, Comparator comparator){
int pass = 1;
Object temp;
boolean sorted;
do{
sorted = true;
for(int m = 1; m <= array.length - pass; m++){
if(comparator.compare(array[m - 1], array[m]) > 0){
temp = array[m-1];
array[m-1] = array[m];
array[m] = temp;
sorted = false;
}
}
pass++;
}while(! sorted);
}
06/12/25
Sahalu Junaidu Unit 01
14 196
Bubble Sort (cont’d)
• To sort an array with k elements, Bubble sort requires k – 1 passes.
• Example:
06/12/25
Sahalu Junaidu Unit 01
14 197
Exercises on Searching
1. What is a sequential search?
2. What is a binary search?
3. Write an iterative binarySearch method on an Object array.
4. Write a recursive binarySearch method on a double array.
5. Write a recursive linearSearch method on an Object array.
6. Write an iterative linearSearch method on a double array.
7. A binary search of an array requires that the elements be sorted in ascending order.
8. Suppose it is known that an array is sorted. When is linear search better than binary Search?
9. Mention the advantages, if any, of linear search over binary search.
10. Mention the advantages, if any, of binary search over linear search.
11. Mention the disadvantages, if any, of binary search over linear search.
12. Mention the disadvantages, if any, of linear search over binary search.
13. Design a Java program that will determine the average running times of binary search and linear
search on sufficiently large integer arrays.
14. Each line of a text file contains the name of a person and his/her telephone number:
firstName secondName telephoneNumber
The names may not be unique and may also not be sorted. The telephone numbers are also not sorted. Write a Java telephone lookup
program that handles lookups by name as well as by telephone number. Use binary search for both lookups.
06/12/25
Sahalu Junaidu Unit 01
14 198
Exercises on Searching
(cont’d)
15. An integer array of size 100 stores contiguous integers. What is the minimum number of
comparisons to determine if:
(a) a value is in the array? (b) a value is not in the array?
16. The information of students taking two courses is maintained in two Object arrays, course1 and
course2. By defining an appropriate Student class, write a Java program to determine the
students who are:
(a) taking both courses. (b) not taking both courses.
17. The element being searched for is not in an array of 100 elements. What is the maximum number
of comparisons needed in a sequential search to determine that the element is not there if the
elements are:
(a) completely unsorted? (b) sorted in ascending order?
(c) sorted in descending order?
18. The element being searched for is not in an array of 100 elements. What is the average number
of comparisons needed in a sequential search to determine that the element is not there if the
elements are:
(a) completely unsorted? (b) sorted in ascending order?
(c) sorted in descending order?
06/12/25
Sahalu Junaidu Unit 01
14 199
Exercises on Searching
(cont’d)
19. Implement each of the following Java String search methods:
06/12/25
Sahalu Junaidu Unit 01
14 200
Exercises on Searching
(cont’d)
22. Consider the following array of sorted integers:
10, 15, 25, 30, 33, 34, 46, 55, 78, 84, 96, 99
Using binary search algorithm, search for 23. Show the sequence of array elements that are
compared, and for each comparison, indicate the values of low and high.
06/12/25
Sahalu Junaidu Unit 01
14 201
Exercises on Sorting
1. Write a method:
public static boolean isSorted(Object[] array, Comparator comparator)
that returns true if array is sorted; otherwise it returns false.
2. Write a recursive bubble sort on a double array.
3. Write a recursive insertion sort on a double array.
4. Write a recursive selection sort on an Object array of Comparable objects.
5. Many operations can be performed faster on sorted than on unsorted data. For which of the following operations is this the case?
(a) Finding an item with minimum value.
(b) Computing an average of values.
(c) Finding the middle value (the median).
(d) Finding the value that appears most frequently in the data.
(e) Finding the distinct elements of an array.
(f) Finding a value closest to a given value.
(g) Finding whether one word is an anagram (i.e., it contains the same letters) as another word.
(example: plum and lump).
6. Rewrite some of the sorting methods we have studied such that each sorts an Object array of Comparable objects.
7. Show the contents of the following integer array:
43, 7, 10, 23, 18, 4, 19, 5, 66, 14
Sahalu06/12/25 Unit 01
14 202
when the array is sorted in ascending order using:
Junaidu
(a) bubble sort, (b) selection sort, (c) insertion sort.
Exercises on Sorting (cont’d)
8. Implement an insertion sort on an integer array that in each pass places both the minimum and maximum elements in their proper locations.
9. In our implementation of bubble sort, an array was scanned top-down to bubble down the largest element. What modifications are needed to
make it work bottom-up to bubble up the smallest element?
10. A cocktail shaker sort is a modification of bubble sort in which the direction of bubbling changes in each iteration: In one iteration, the
smallest element is bubbled up; in the next, the largest is bubbled down; in the next the second smallest is bubbled up; and so forth.
Implement this algorithm.
11. Explain why insertion sort works well on partially sorted arrays.
06/12/25
Sahalu Junaidu Unit 01
14 203
Merge- and Quick Sort
• Merge Sort
• Quick Sort
• Exercises
06/12/25
Sahalu Junaidu Unit 01
15 204
Merge Sort
• The merge sort algorithm to sort an array from index low to high:
if(high > low){
Split the array into two halves
merge sort the left half
merge sort the right half
merge the two sorted halves into one sorted array
}
06/12/25
Sahalu Junaidu Unit 01
15 205
Merge Sort (cont’d)
• Note that in a merge sort, the splitting and merging process are intermingled. However, we
can view merge sort as:
• 1. Continually splitting the original array of size n until it has created n one element subarrays (each of which is a sorted subarray).
• 2. Adjacent sorted subarrays are then merged into larger and larger sorted subarrays, until the entire array is merged back.
06/12/25
Sahalu Junaidu Unit 01
15 206
Merge Sort (cont’d)
public static void mergeSort(Object[] array, Comparator comparator){
mergeSort(array, 0, array.length - 1, comparator);
}
06/12/25
Sahalu Junaidu Unit 01
15 207
Merge Sort (cont’d)
private static void merge(Object[] array,int leftLowIndex, int leftHighIndex,int rightLowIndex, int rightHighIndex,
Comparator comparator){
int low = leftLowIndex;
int index = leftLowIndex;
Object[] tempArray = new Object[array.length];
while(leftLowIndex <= leftHighIndex && rightLowIndex <= rightHighIndex){
if(comparator.compare(array[leftLowIndex], array[rightLowIndex]) < 0)
tempArray[index++] = array[leftLowIndex++];
else tempArray[index++] = array[rightLowIndex++];
}
while(leftLowIndex <= leftHighIndex)
tempArray[index++] = array[leftLowIndex++];
while(rightLowIndex <= rightHighIndex)
tempArray[index++] = array[rightLowIndex++];
for(int k = low; k <= rightHighIndex; k++)
array[k] = tempArray[k];
}
06/12/25
Sahalu Junaidu Unit 01
15 208
Merge Sort (cont’d)
• A recursive-tree for merge
sorting an array x with 7
06/12/25
Sahalu Junaidu Unit 01
15 209
Quick Sort
• The quick sort algorithm to sort an array from index low to high:
if(high > low){
1. Select a pivot element p to be used to partition the array into two partitions.
2. Scan through the array, moving all elements smaller than p to the lower partition,
and all elements equal to or greater than p to the upper partition.
3. Sort the low and upper partitions recursively using quick sort
}
06/12/25
Sahalu Junaidu Unit 01
15 213
Exercises
1. What is the advantage of the bubble sort algorithm we have studied over all the other sorting methods we have studied?
2. When are bubble, insertion, and selection sort methods more efficient than merge sort and quicksort?
3. What is the disadvantage of merge sort as compared to quicksort?
4. What role, if any, does the size of data objects play in a sort?
5. Give the merge sort recursion-tree for the array:
43, 7, 10, 23, 18, 4, 19, 5, 66, 14, 2
6. A merge sort is used to sort an array of 1000 integers in descending order. Which of the following statements is true?
(a) The sort is fastest if the original integers are sorted in ascending order.
(b) The sort is fastest if the original integers are sorted in descending order.
(c) The sort is fastest if the original integers are completely in random order.
(d) The sort is the same, no matter what the order of the original integers.
7. A different method for choosing the pivot for each partition in quicksort is to take the median of the first, last and central keys. Implement a
quicksort algorithm using this approach.
8. A different approach to the selection of a pivot in quicksort is to take the average of all the keys in a partition (assuming that the keys are
numeric) as the pivot for that partition. The resulting algorithm is called meansort. Implement a quicksort algorithm using this approach.
Note: The average of the keys is not necessarily one of the keys in the array.
06/12/25
Sahalu Junaidu Unit 01
15 214
Exercises (cont’d)
9. In quicksort, why is it better to choose the pivot from the center of the array rather from one of the ends?
10. What is the property of the best pivot in a quicksort?
11. What is the property of the worst pivot in a quicksort?
12. Suppose that, instead of sorting, we wish only to find the m th quicksort can be adapted to this problem, doing much less work than a
complete sort.
13. Implement a non-recursive mergesort, where the length of the array is a power of 2. First merge adjacent regions of size 1, then adjacent
regions of size 2, then adjacent regions of size 4, and so on.
14. Implement a non-recursive mergesort, where the length of the array is an arbitrary number.
Hint: Use a stack to keep track of which subarrays have been sorted.
15. Implement each of the sorting algorithms we have studied such that each displays the number of swaps and comparisons. Each of the
implementations should be used to sort integer arrays with the same 100 random integers.
06/12/25
Sahalu Junaidu Unit 01
15 215
Exercises (cont’d)
16. Design a test program to compare the execution times of bubble sort, selection sort, insertion sort, merge sort, and quick sort on integers
arrays of equal lengths with similar random integers. For shorter lengths, sort many arrays and obtain the average execution time.
06/12/25
Sahalu Junaidu Unit 01
15 216
Java Collections Framework: Interfaces
06/12/25
Sahalu Junaidu Unit 01
16 217
The Java Collections Framework
06/12/25
Sahalu Junaidu Unit 01
16 218
Why Develop the JCF?
06/12/25
Sahalu Junaidu Unit 01
16 219
Some Benefits of the JCF
• Benefits
– It reduces programming effort: by providing useful data structures. Programmer
can focus on problem at hand
– Improve program speed and quality: by providing high-performance, high-quality
implementations for the most common data structures
– Allows interoperability among unrelated APIs: If a network API provides a
Collection of node names, and a GUI toolkit expects a Collection of column
headings, they will interoperate seamlessly even though they were written
independently
– It fosters software reuse
• Concerns
– JCF data structures work only with objects, not primitive types
– A Collection can contain incompatible types at the same time
– JFC methods are generic; must always downcast from Object to our types
06/12/25
Sahalu Junaidu Unit 01
16 220
Collections Framework’s Interfaces
<<interface>>
Comparator
<<interface>>
Collections AbstractCollection Collection
<<interface>>
AbstractList
List
ArrayList AbstractSequentialList
<<interface>>
Iterator
LinkedList
<<interface>>
ListIterator
06/12/25
Sahalu Junaidu Unit 01
16 221
The Comparator Interface Revisited
• The interface:
06/12/25
Sahalu Junaidu Unit 01
16 222
Example 1: The Comparator Interface
1 import java.util.*;
2 class MyComparator implements Comparator {
3 public int compare(Object obj1, Object obj2) {
4 int i1 = ((Integer)obj1).intValue();
5 int i2 = ((Integer)obj2).intValue();
6 return Math.abs(i2) - Math.abs(i1);
7 }
8}
9 public class TestCollections {
10 public static void main(String args[]) {
11 ArrayList array = new ArrayList();
12 array.add(new Integer(-200));
13 array.add(new Integer(100));
14 array.add(new Integer(400));
15 array.add(new Integer(-300));
16 Collections.sort(array);
17 System.out.println("Natural ordering: " + array);
18 Collections.sort(array, new MyComparator());
19 System.out.println("My own ordering : " + array);
20 }
21 }
06/12/25
Sahalu Junaidu Unit 01
16 223
The Collection Interface
06/12/25
Sahalu Junaidu Unit 01
16 224
The List Interface
• Each element in a list has an index, or position. The indexes range from 0 to size() – 1.
• List extends Collection. It has the following additional methods to those it inherits and
overrides:
public abstract void add(int index, Object object);
public abstract Object get(int index);
public abstract int indexOf(Object object);
public abstract int lastIndexOf(Object object);
public abstract Object remove(int index);
public abstract Object set(int index, Object object);
public abstract ListIterator listIterator();
public abstract ListIterator listIterator(int index);
public abstract List subList(int fromIndex, int toIndex);
06/12/25
Sahalu Junaidu Unit 01
16 225
The Iterator Interface
06/12/25
Sahalu Junaidu Unit 01
16 226
The Iterator Interface (cont’d)
• The remove() method of an iterator removes the element whose reference was returned by the last call to
next(). For example, the following code removes the first element in a collection c:
06/12/25
Sahalu Junaidu Unit 01
16 227
Example 2: The Iterator Interface
1 import java.util.*;
2 public class TestIterator {
3 public static void main(String[] args) {
4 //LinkedList list = new LinkedList();
5 ArrayList list = new ArrayList();
6
7 for(int i = 0; i < 6; i++)
8 list.add(new Integer(i));
9
10 Iterator iter = list.iterator();
11
12 while (iter.hasNext()){
13 Integer myInt = (Integer)iter.next();
14 System.out.print(myInt+" ");
15 }
16 System.out.println();
17 }
18 }
06/12/25
Sahalu Junaidu Unit 01
16 228
The ListIterator Interface
• The ListIterator interface extends Iterator to allow bi-directional traversal of a list, and the modification of a list.
06/12/25
Sahalu Junaidu Unit 01
16 229
Example 3: The ListIterator Interface
1 import java.util.*;
2 public class TestListIterator {
3 public static void main(String[] args) {
4 //LinkedList list = new LinkedList();
5 ArrayList list = new ArrayList();
6
7 ListIterator iter2, iter1 = list.listIterator();
8
9 for(int i = 0; i < 6; i++)
10 iter1.add(new Integer(i));
11
12 iter2 = list.listIterator();
13 iter2.next(); // skip the first element
14 iter2.add(new Integer(25)); // add immediately after the first
15
16 System.out.println(list);
17 }
18 }
06/12/25
Sahalu Junaidu Unit 01
16 230
Example 4: The ListIterator Interface
1 import java.util.*;
2 public class TestListIterator2 {
3 public static void main(String[] args) {
4 ArrayList list = new ArrayList();
5 int bonus = 1;
6
7 for(int i = 0; i < 6; i++)
8 list.add(new Integer(i));
9
10 ListIterator iter = list.listIterator();
11
12 System.out.println("List before: " + list);
13
14 while (iter.hasNext()){
15 Integer myInt = (Integer)iter.next();
16 iter.set(new Integer(myInt.intValue()+bonus));
17 }
18 System.out.println("List after : " + list);
19 }
20 }
06/12/25
Sahalu Junaidu Unit 01
16 231
Java Collections Framework: Classes I
06/12/25
Sahalu Junaidu Unit 01
17 232
Collections Framework’s Classes
Object
<<interface>>
Collection
Collections AbstractCollection
AbstractList <<interface>>
List
ArrayList AbstractSequentialList
LinkedList
06/12/25
Sahalu Junaidu Unit 01
17 233
The ArrayList Class
• It extends the AbstractList class and implements the List interface of the JCF
• Before Java 1.2, the functionality of the ArrayList was provided by the Vector class
• ArrayList is very much like the Vector class except that ArrayList methods are not
synchronized
• Since this class is based on an array, it is better used in applications requiring fast
direct access to objects
• However, the LinkedList class will give better performance for applications
requiring frequent insertions and deletions
06/12/25
Sahalu Junaidu Unit 01
17 234
Example 1: Kinds of Objects a
Collection
1 import java.util.ArrayList;
2 import java.util.Collections;
3 class ArrayListOfAllKinds{
4 public static void main(String args []){
5 ArrayList theArray = new ArrayList();
6
7 theArray.add(new Double(3.7));
8 theArray.add(new Boolean(true));
9 theArray.add(new Integer(19));
10 theArray.add(new String(";-)"));
11
12 System.out.println(theArray);
13 }
14 }
06/12/25
Sahalu Junaidu Unit 01
17 235
Example 2: List of Lists
1 import java.util.ArrayList;
2 class ListOfLists{
3 public static void main(String s[]){
4 ArrayList kfupm=new ArrayList();
5 ArrayList ics=new ArrayList();
6 ArrayList coe=new ArrayList();
7 ArrayList mis=new ArrayList();
8 String[] icsBasics={"ics102", "ics103", "ics201", "ics202"};
9 String[] coeBasics={"coe200", "ics102", "ics201", "ics202"};
10 String[] misBasics={"mis105", "mis345", "mis301", "ics201"};
11 for (int i=0; i<icsBasics.length; i++) {
12 ics.add(icsBasics[i]);
13 coe.add(coeBasics[i]);
14 mis.add(misBasics[i]);
15 }
16 kfupm.add(ics);
17 kfupm.add(coe);
18 kfupm.add(mis);
19 System.out.println(kfupm);
20 }
21 }
06/12/25
Sahalu Junaidu Unit 01
17 236
Example 3: Using ArrayList
1 import java.util.*;
2 class MyArrayList extends ArrayList{
3 public MyArrayList(int size){
4 super(size);
5 }
6 public void removeRange(int x, int y){ //protected method of ArrayList
7 super.removeRange(x,y);
8 }
9}
10 class TestArrayList{
11 public static void main(String s[]){
12 MyArrayList c = new MyArrayList(100); //initial capacity
13 ListIterator iter = c.listIterator();
14 for(int i=0; i<6; i++)
15 iter.add(new Integer(i)); // using iterator's add
16 c.add(2,"ICS 201"); // using collection's add
17 System.out.println(c);
18 c.removeRange(3,6);
19 System.out.println(c);
20 }
21 }
06/12/25
Sahalu Junaidu Unit 01
17 237
Example 4: Using ArrayList
1 import java.util.*;
2 class TestArrayList2{
3 public static void main(String s[]){
4 ArrayList c, c1, c2 = new ArrayList(), c3 = new ArrayList();
5 ListIterator iter = c3.listIterator();
6 for(int i=0; i<s.length; i++)
7 iter.add(s[i]);
8 for(int i=0; i<10; i++)
9 c2.add(new Integer(i));
10 Collections.shuffle(c2);
11 System.out.println("Shuffled: "+ c2);
12 c1 = new ArrayList(c3);
13 c2.addAll(3,c1);
14 c = (ArrayList)c2.clone();
15 c.remove(3);
16 System.out.println(c);
17 System.out.println(c1);
18 System.out.println(c2);
19 System.out.println(c3.containsAll(c1));
20 }
21 }
06/12/25
Sahalu Junaidu Unit 01
17 238
The Collections Class
• The most common algorithms in this class are those for sorting and
searching
– We have already seen examples usage of Collections.sort() and Collections.shuffle().
06/12/25
Sahalu Junaidu Unit 01
17 239
Example 5: Searching Collections
1 import java.util.*;
2 class BankAccount implements Comparable{
3 private int accountNumber;
4 protected String name;
5 private double balance;
6 public BankAccount(int accountNumber, String name, double balance){
7 this.accountNumber = accountNumber;
8 this.name = name;
9 this.balance = balance;
10 }
11 public int compareTo(Object object){
12 BankAccount account = (BankAccount) object;
13 return accountNumber - account.accountNumber;
14 }
15 public String toString(){
16 return accountNumber + " " + name + " " + balance + " SR";
17 }
18 }
06/12/25
Sahalu Junaidu Unit 01
17 240
Example 5: Searching Collections (cont’d)
19 public class SortingAndSearching{
20 public static void main(String[] args){
21 ArrayList list = new ArrayList();
22 list.add(new BankAccount(9234, "Ahmad", 50000 ));
23 list.add(new BankAccount(8000, "Abubakar", 40000 ));
24 list.add(new BankAccount(6000, "Yusuf", 6000 ));
25 list.add(new BankAccount(9975, "Zubeir", 10000 ));
26 System.out.println("Sorted in increasing order of Account Number:");
27 Collections.sort(list); System.out.println(list);
28 System.out.println("Sorted in decreasing order of Customer name:");
29 Collections.sort(list, new Comparator(){
30 public int compare(Object object1, Object object2){
31 BankAccount account1 = (BankAccount) object1;
32 BankAccount account2 = (BankAccount)object2;
33 String string1 = account1.name;
34 String string2 = account2.name;
35 return string2.compareTo(string1);
36 }});
37 System.out.println(list);
38 BankAccount ba = new BankAccount(6000, "Ali", 7000);
39 System.out.println(Collections.binarySearch(list, ba));
40 }
41 }
06/12/25
Sahalu Junaidu Unit 01
17 241
Java Collections Framework: Classes II
• Introduction
06/12/25
Sahalu Junaidu Unit 01
18 242
The LinkedList Class
• If, on the other hand, there are frequent retrievals, then the ArrayList
Collection is a better choice for good performance.
• Two such data structures are singly linked list (SLL) and doubly linked list
(DLL)
• Next, we show the nodes declarations for these two flavors of linked lists.
06/12/25
Sahalu Junaidu Unit 01
18 243
Singly-Linked Lists: Nodes Declaration
tail
06/12/25
Sahalu Junaidu Unit 01
18 244
Doubly-Linked Lists: Nodes Declaration
public class DLLNode{
protected Object data;
protected DLLNode next;
protected DLLNode previous;
public DLLNode(Object data, DLLNode nxt, DLLNode prev){
this.data = data;
next = nxt;
if(next != null)
next.previous = this;
previous = prev;
if(previous != null)
previous.next = this;
}
public DLLNode(Object data){
this(data, null, null);
}
// . . . head
}
tail
06/12/25
Sahalu Junaidu Unit 01
18 245
Example 1: Merging Linked Lists
1 import java.util.*;
2 public class InterleaveLinkedLists {
3 public static void main(String[] args) {
4 LinkedList list1 = new LinkedList();
5 LinkedList list2 = new LinkedList();
6 for(int i = 20; i <= 30; i++)
7 list1.add(new Integer(i));
8 for(int i = 1; i <= 7; i++)
9 list2.add(new Integer(i));
10 System.out.println("list1 is: " + list1);
11 System.out.println("list2 is: " + list2);
12 ListIterator iter1, iter2;
13 for(iter1=list1.listIterator(),iter2=list2.listIterator(); iter2.hasNext();) {
14 if(iter1.hasNext())
15 iter1.next();
16 iter1.add(iter2.next());
17 }
18 System.out.println("The merged list is:");
19 System.out.println(list1);
20 }
21 }
06/12/25
Sahalu Junaidu Unit 01
18 246
Example 2: Reversing a Linked List
1 import java.util.*;
2 public class ReversingLinkedList {
3 public static void main(String[] args) {
4 ListIterator iter1, iter2;
5 LinkedList c = new LinkedList();
6 for(int i = 20; i <= 30; i++)
7 c.add(new Integer(i));
8 System.out.println("Original : " + c);
9 int j,size = c.size();
10 for(j=0,iter1 = c.listIterator(),iter2 = c.listIterator(size);
11 iter1.hasNext () && iter2.hasPrevious () && j<size/2;) {
12 exchange(c, c.indexOf(iter1.next ()), c.indexOf(iter2.previous()));
13 j++;
14 }
15 System.out.println("Reversed : " + c);
16 }
17 public static void exchange(List a, int i, int j) {
18 Object temp = a.get(i);
19 a.set(i, a.get(j));
20 a.set(j, temp);
21 }
22 }
06/12/25
Sahalu Junaidu Unit 01
18 247
The Stack Collection
• A stack is a LIFO (Last In First Out) data structure. The last element
inserted is the first element to be removed.
06/12/25
Sahalu Junaidu Unit 01
18 248
Using java.util.Stack
1 import java.util.Stack;
2 class TestStack{
3 public static void main(String args[]){
4 Stack s = new Stack();
5 s.push("One");
6 s.push("Two");
7 System.out.println("Top: " + s.peek());
8 s.push("Three");
9
10 while(!(s.isEmpty()))
11 System.out.println(s.pop());
12 }
13 }
06/12/25
Sahalu Junaidu Unit 01
18 249
Implementing Stacks using LinkedList
1 import java.util.*; 22 public void clear(){
2 class OurStack{ 23 list.clear();
3 protected LinkedList list; 24 }
4 public OurStack(){ 25 public boolean isEmpty(){
5 list = new LinkedList(); 26 return list.isEmpty();
6 } 27 }
7 public Object pop() throws NoSuchElementException{ 28 public int contains(Object obj){
8 if(list.isEmpty()) 29 return list.indexOf(obj);
9 throw new NoSuchElementException(); 30 }
10 else 31 public String toString(){
11 return list.removeFirst(); 32 return list.toString();
12 } 33 }
13 public void push(Object obj){ 34 }
14 list.addFirst(obj);
15 }
16 public Object peek() throws NoSuchElementException{
17 if(list.isEmpty())
18 throw new NoSuchElementException();
19 else
20 return list.getFirst();
21 }
06/12/25
Sahalu Junaidu Unit 01
18 250
Example 3: Reversing a Text File
1 import java.io.*;
2 public class ReverseTextFile{
3 public static void main(String[] args) throws IOException{
4
5 OurStack stack = new OurStack();
6
7 BufferedReader inputStream = new BufferedReader(new FileReader("myfile.txt"));
8 String inputLine, line;
9 while((inputLine = inputStream.readLine()) != null)
10 stack.push(inputLine);
11
12 inputStream.close();
13
14 PrintWriter outputStream = new PrintWriter(new FileWriter("myfile.txt"));
15 while(! stack.isEmpty())
16 outputStream.println(stack.pop());
17
18 outputStream.close();
19
20 System.out.println("The reversal process is complete");
21 }
22 }
06/12/25
Sahalu Junaidu Unit 01
18 251
Example 4: Evaluating Postfix Expressions
1 import java.util.*;
2 class EvaluatePostFix{
3 public static void main(String args[]){
4 Stack stack = new Stack();
5 String postFix = "3 4 - 5 3 * -";
6 int i;
7 double o1, o2;
8 Double obj, op1, op2, result;
9 char ch;
10 for(i=0; i<postFix.length(); i++){
11 ch = postFix.charAt(i);
12 if(isDigit(ch)){
13 obj = new Double(ch-'0');
14 stack.push(obj);
15 }else if(isOperator(ch)){
16 op2 = (Double)stack.pop();
17 o2 = op2.doubleValue();
18 op1 = (Double)stack.pop();
19 o1 = op1.doubleValue();
06/12/25
Sahalu Junaidu Unit 01
18 252
Evaluating Postfix Expressions (cont’d)
20 switch(ch){
21 case '+' :
22 result = new Double(o1+o2);
23 stack.push(result);
24 break;
25 case '-' :
26 result = new Double(o1-o2);
27 stack.push(result);
28 break;
29 case '*' :
30 result = new Double(o1*o2);
31 stack.push(result);
32 break;
33 case '/' :
34 result = new Double(o1/o2);
35 stack.push(result);
36 } // switch
37 } //else if
38 } // for
06/12/25
Sahalu Junaidu Unit 01
18 253
Evaluating Postfix Expressions (cont’d)
39 result = (Double)stack.pop();
40 System.out.println("Result = " + result.doubleValue());
41 } // main
42 public static boolean isOperator(char ch){
43 return ((ch == '+') || (ch == '-') ||
44 (ch == '*') || (ch == '/'));
45 }
46 public static boolean isDigit(char ch){
47 int value = ch - '0';
48 return (value < 10 && value > -1);
49 }
50 } // class
06/12/25
Sahalu Junaidu Unit 01
18 254
Implementing Queue Using
LinkedList
• A queue is a FIFO (First In First Out) data structure.
• There is no Queue class in the Java API but the ArrayList methods
addLast(), getFirst(), removeFirst() and isEmpty() can
be used to simulate a queue. front
rear
06/12/25
Sahalu Junaidu Unit 01
18 255
Implementing Queue (cont’d)
1 import java.util.*; 22 public void clear(){
2 public class OurQueue{ 23 list.clear();
3 protected LinkedList list; 24 }
4 public OurQueue(){ 25 public boolean isEmpty(){
5 list = new LinkedList(); 26 return list.isEmpty();
6 } 27 }
7 public Object dequeue() throws NoSuchElementException{ 28 public int contains(Object obj){
8 if(list.isEmpty()) 29 return list.indexOf(obj);
9 throw new NoSuchElementException(); 30 }
10 else 31 public String toString(){
11 return list.removeFirst(); 32 return list.toString();
12 } 33 }
13 public void enqueue(Object obj){ 34 }
14 list.addLast(obj);
15 }
16 public Object peek() throws NoSuchElementException{
17 if(list.isEmpty())
18 throw new NoSuchElementException();
19 else
20 return list.getFirst();
21 }
06/12/25
Sahalu Junaidu Unit 01
18 256
Introduction to Threads and Concurrency
• Introduction to Threads
• Multithreading Examples
• Life-cycle of a Thread
• Thread Priorities
• More Examples
06/12/25
Sahalu Junaidu Unit 01
19 257
Introduction: What is a
Thread?
• Just like human being can walk, talk, see, hear etc at the same time, computers
can also download documents, print a file, receive e-mail concurrently
• Each thread has its own stack, priority, and virtual set of registers
06/12/25
Sahalu Junaidu Unit 01
19 258
Single and Multithreaded
Programs
06/12/25
Sahalu Junaidu Unit 01
19 259
Introduction: Where are Threads Used?
• Threads are used by virtually every computer user in the following instances:
– In Internet browsers
– In databases
– In operating systems (for controlling access to shared resources etc)
• Benefits of threads
– More productivity to the end user (such as responsive user interface)
– More efficient use of the computer (such as using the CPU while
performing input-output)
– Sometimes advantageous to the programmer (such as simplifying program
logic)
06/12/25
Sahalu Junaidu Unit 01
19 260
Threads in Java
• Java is one of the few (the only?) languages that supports threads at the language level
• Writing multithreaded programs can be tricky: imagine reading three books by reading
few words from each book for a few seconds repeatedly in succession
• On windows (NT and 98) threads are timesliced and preemption occurs with higher as
well as with equal priority threads
06/12/25
Sahalu Junaidu Unit 01
19 261
Example 1: Extending java.lang.Thread
06/12/25
Sahalu Junaidu Unit 01
19 262
Example 2: Implementing java.lang.Runnable
06/12/25
Sahalu Junaidu Unit 01
19 263
Example 3: Creating Multiple Threads
1 public class SleepingThread extends Thread {
2 private int countDown = 5;
3 private static int threadCount = 0;
4 private int threadNumber = ++threadCount;
5 public SleepingThread() {
6 System.out.println("Making " + getName());
7 }
8 public void run() {
9 while(true) {
10 try { // don’t wake a sleeping thread before its sleep time expires!
11 System.out.println(getName() + " Executing.");
12 sleep((long)(Math.random()*5000));
13 }catch(InterruptedException ie){
14 System.out.println(getName() + " Interrupted.");
15 }
16 if(--countDown == 0) return;
17 } }
18 public static void main(String[] args) {
19 for(int i = 0; i < 5; i++)
20 new SleepingThread().start();
21 System.out.println("All Threads Started");
22 }}
06/12/25
Sahalu Junaidu Unit 01
19 264
Threads: Pictorial View of a Lifetime.
resume(),
notify(), or
notifyAll()
Thread created ready stop() finished
start()
running
blocked
suspend(),
sleep(), or wait()
06/12/25
Sahalu Junaidu Unit 01
19 265
Example 4: A Timer Thread
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4 class TimerThread extends JFrame implements Runnable{
5 private JTextField jtf = new JTextField(10);
6 private JButton jb = new JButton("Start/Stop");
7 private int counter = 0;
8 private boolean startStop = true;
9 TimerThread(){
10 Container cp = getContentPane();
11 cp.setLayout(new FlowLayout());
12 cp.add(jtf);
13 cp.add(jb);
14 pack();
15 setTitle("A Timer Thread");
16 show();
17 jb.addActionListener(new ActionListener(){
18 public void actionPerformed(ActionEvent ae){
19 startStop = !startStop;
20 } });}
06/12/25
Sahalu Junaidu Unit 01
19 266
Example 4: A Timer Thread (cont’d)
06/12/25
Sahalu Junaidu Unit 01
19 267
Example 5: A Visitor Thread
1 import java.util.*;
2 public class VisitorThread extends Thread {
3 private Object []array;
4 public VisitorThread(Object array[]) {
5 this.array = array;
6 }
7 public void run() {
8 Integer temp;
9 this.setName("The Visitor");
10 for(int i = 0; i < array.length; i++){
11 temp = (Integer)array[i];
12 array[i] = new Integer (temp.intValue() + i);
13 if(i%3 == 0) Thread.yield();
14 }
15 System.out.println(getName() + " done!");
16 }
17 }
06/12/25
Sahalu Junaidu Unit 01
19 268
Example 5: A Sorter Thread
1 import java.util.*;
2 public class SorterThread extends Thread {
3 private Object []array;
4 public SorterThread(Object array[]){
5 this.array = array;
6 }
7 public void run() {
8 int minPos = 0; Object temp;
9 for(int i = 0; i < array.length - 1; i++){
10 minPos = i;
11 if(i%3 == 0) Thread.yield();
12 for(int k = i + 1; k < array.length; k++){
13 if(((Integer)array[k]).compareTo(array[minPos]) < 0)
14 minPos = k;
15 }
16 temp = array[minPos];
17 array[minPos] = array[i];
18 array[i] = temp;
19 }
20 System.out.println(getName() + " done!");
21 }
22 }
06/12/25
Sahalu Junaidu Unit 01
19 269
Example 5: A Tester Thread
1 import java.util.*;
2 public class TesterThread extends Thread {
3 private static Object []array;
4 public TesterThread(int size) {
5 array = new Object[size];
6 }
7 public static void main(String args[]) {
8 Random r = new Random();
9 new TesterThread(100);
10 for(int i = 0; i < array.length; i++){
11 array[i] = new Integer(r.nextInt(100));
12 }
13 SorterThread sorter = new SorterThread(array);
14 VisitorThread visitor = new VisitorThread(array);
15 sorter.start();
16 visitor.start();
17 for(int i = 0; i < array.length; i++){
18 System.out.println(array[i]);
19 }
20 System.out.println(Thread.currentThread().getName() + " done!");
21 }
22 }
06/12/25
Sahalu Junaidu Unit 01
19 270
Threads Priorities
• As wehave seen, the run( ) methods of the threads in a program will be executed
“simultaneously”
• The programmer can influence the order of threads executions using threads’ priorities
• Each new thread inherits the priority of the thread that creates it
• Every thread has a name (including anonymous threads) for identification purposes
– More than one thread may have the same name
– If a name is not specified when a thread is created, a new name is generated for it
06/12/25
Sahalu Junaidu Unit 01
19 271
Example 6: Prioritizing the Visitor Thread
1 import java.util.*;
2 public class TesterThread extends Thread {
3 private static Object []array;
4 public TesterThread(int size) {
5 array = new Object[size];
6 }
7 public static void main(String args[]) {
8 Random r = new Random(); new TesterThread(100);
9 for(int i = 0; i < array.length; i++){
10 array[i] = new Integer(r.nextInt(100));
11 }
12 SorterThread sorter = new SorterThread(array);
13 VisitorThread visitor = new VisitorThread(array);
14 sorter.start(); visitor.start();
15 visitor.setPriority(Thread.MAX_PRIORITY);
16 Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
17 for(int i = 0; i < array.length; i++){
18 System.out.println(array[i]);
19 }
20 System.out.println(Thread.currentThread().getName() + " done!");
21 }
22 }
06/12/25
Sahalu Junaidu Unit 01
19 272
Further Threads Programming
06/12/25
Sahalu Junaidu Unit 01
20 273
Some Terminologies on Multithreading
06/12/25
Sahalu Junaidu Unit 01
20 274
Threads Synchronization
06/12/25
Sahalu Junaidu Unit 01
20 275
Example 1: Threads Synchronization
1 class BanckAccount{
2 private int balance;
3 public BanckAccount(int balance){
4 this.balance = balance;
5 }
6 void doNothing(){
7 depositWithdraw(10);
8 depositWithdraw(20);
9 depositWithdraw(30);
10 }
11 void depositWithdraw(int money){
12 try {
13 balance += money;
14 Thread.sleep((long)(Math.random()*1000));
15 balance -= money;
16 } catch(Exception e){}
17 }
18 int get(){
19 return balance;
20 }
21 }
06/12/25
Sahalu Junaidu Unit 01
20 276
Example 1: Threads Synchronization
(cont’d)
22 public class UnsafeBankAccount extends Thread{
23 BanckAccount ba;
24 public static void main( String[] args ){
25 BanckAccount ba = new
26 BanckAccount(0);
27 for(int i=0; i<9; i++)
28 new UnsafeBankAccount(ba).start();
29 }
30 public UnsafeBankAccount(BanckAccount ba){
31 this.ba = ba;
32 }
33 public void run(){
34 doWork();
35 }
36 public void doWork(){
37 System.out.println(getName()+" got balance: "+ba.get());
38 ba.doNothing();
39 System.out.println(getName()+" got balance: "+ba.get());
40 }
41 }
• Make depositWithdraw() and get() synchronized to solve this problem
06/12/25
Sahalu Junaidu Unit 01
20 277
Example 2: ‘Salaam Shabab’ Animation
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4 class AnimationPanel extends JPanel implements Runnable {
5 private Font myFont;
6 private int increment = 1;
7 public int xSize, ySize, yCoord = 0;
8 int delay;
9 Thread animator;
10 private boolean onOff=true;
11 public AnimationPanel(int delay) {
12 xSize=400;
13 ySize=350;
14 setSize(xSize, ySize);
15 myFont = new Font ("Serif", Font.ITALIC, 30);
16 animator = new Thread(this);
17 animator.start();
18 }
19 public void setOnOff(boolean onOff) {
20 this.onOff = onOff;
21 }
06/12/25
Sahalu Junaidu Unit 01
20 278
Example 2: ‘Shabab’ Animation (cont’d)
22 public void paintComponent(Graphics g) {
23 super.paintComponent(g);
24 g.setColor(Color.yellow);
25 g.fillRect(0,0,xSize, ySize);
26 g.setColor (Color.red);
27 g.setFont(myFont);
28 if(onOff) {
29 g.drawString ("Salaam ", xSize/2-100, ySize/2 + yCoord);
30 g.drawString ("Shabab!", xSize/2, ySize/2 - yCoord);
31 }
32 }
33 public void run () {
34 while(true){
35 yCoord = yCoord + increment;//yCoord min is -150 and max 150
36 if((yCoord == (ySize-50)/2 || (yCoord == -(ySize-50)/2)))
37 increment = -increment; // increment by -1 now
38 try{
39 Thread.sleep(delay);
40 } catch(InterruptedException e){}
41 repaint();
42 }
43 }
44 }
06/12/25
Sahalu Junaidu Unit 01
20 279
Example 2: ‘Shabab’ Animation (cont’d)
06/12/25
Sahalu Junaidu Unit 01
20 280
Example 3: Car Race Animation
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4 import java.util.*;
5 class DrivingPanel extends JPanel implements Runnable {
6 private int delay;
7 private Thread animator;
8 private Image car;
9 static final int WIDTH = 600;
10 static final int HEIGHT = 200;
11 private int xPosition, speed;
12 private Random random;
13 public DrivingPanel(Image car, int delay) {
14 this.car = car;
15 this.delay = delay;
16 setSize(WIDTH,HEIGHT);
17 xPosition = getWidth();
18 random = new Random();
19 speed = random.nextInt(5);//+1;
20 animator = new Thread(this);
21 animator.start();
22 }
06/12/25
Sahalu Junaidu Unit 01
20 281
Example 3: Car Race Animation (cont’d)
23 public void run() {
24 while (true) {
25 repaint();
26 speed = random.nextInt(5)+1;
27 xPosition -= speed;
28 if (xPosition < -car.getWidth(this))
29 xPosition = getWidth();
30 try {
31 Thread.sleep(delay);
32 } catch (InterruptedException e) {
33 break;
34 }
35 }
36 }
37 public void paintComponent(Graphics g) {
38 super.paintComponent(g);
39 g.setColor(Color.white);
40 g.fillRect(0, 0, getWidth(), getHeight());
41 g.drawImage(car, xPosition, getHeight()/2, this);
42 }
43 }
06/12/25
Sahalu Junaidu Unit 01
20 282
Example 3: Car Race Animation (cont’d)
• You can also obtain the rocket image for the next example.
06/12/25
Sahalu Junaidu Unit 01
20 283
Example 4: Rocket Launcher
1 import java.applet.*;
2 import java.awt.*;
3 import java.awt.event.*;
4 import javax.swing.*;
5 public class RocketLauncher extends JApplet implements Runnable, ActionListener {
6 private Image rocket;
7 private int x, y, sec=10;
8 private Thread myThread;
9 private Timer timer = new Timer(1000,this);
10 JTextField tf = new JTextField(5);
11 JButton b = new JButton("Start Count Down");
12 public void init() {
13 rocket = Toolkit.getDefaultToolkit().getImage("rocket.jpg");
14 x = 50;
15 y = getSize().height-rocket.getHeight(this)-380;
16 myThread = new Thread(this);
17 tf.setText(" "+sec+" ");
18 b.addActionListener(this);
19 }
06/12/25
Sahalu Junaidu Unit 01
20 284
Example 4: Rocket Launcher (cont’d)
File
Application Physical
Program memory
File
In order to overcome these limitations, a whole new area of Computer science called Database Applications (or simply Data Bases) evolved.
File
DBMS Physical
Application
Program ENGINE memory
File
Operating
System
06/12/25 Unit 01 296
Sahalu Junaidu Unit 21
Database Schema
The data dictionary is always accessed before any change to the physical
data is made. The following figure illustrates some of these concept.
06/12/25 Unit 01 297
Sahalu Junaidu Unit 21
DB System: Data Independence
Users Database
Schema
DBMS Data
Definition (logical)
Language
Data
Data Dictionary
Files
(physical)
Secondary Storage
06/12/25 Unit 01 298
Sahalu Junaidu Unit 21
Characteristics, Functions and
Uses of a DBMS
Characteristics :
It is a computerized record-keeping system.
It contains facilities that allow the user to . . .
Add and delete files to the system.
Insert, retrieve, update, and delete data in existing files.
It is collection of databases.
A DBMS may contain many databases that can be used for separate
purposes or combined to provide useful information.
Functions :
To store data
To organize data
To control access to data
To protect data
Uses :
To provide decision support
Managers and analysts retrieve information generated by the DBMS for
inquiry, analysis, and decision-making.
To provide transaction processing
Users input, update, and process data with transactions that generate
information needed by managers and other users or by other departments.
Advantages:
Centralized Data reduces management problems.
Data redundancy and consistency are controllable.
Program - data interdependency is diminished.
Flexibility of data is increased.
Disadvantages:
Reduction in speed of data access time.
Requires special knowledge.
Possible dependency of application programs to specific DBMS versions.
Application Languages need specific interface (Drivers) to interact with
DBMS
06/12/25 Unit 01 300
Sahalu Junaidu Unit 21
Three Aspects in DBMS and its
Marketplace
Three Aspects to Study in DBMS:
1. Modeling and design of databases.
Allows exploration of issues before committing to an implementation.
2. Programming: queries and DB operations like update.
SQL = “intergalactic dataspeak.''
3. DBMS implementation.
The DBMS Marketplace:
Relational DBMS companies --- Oracle, Informix, Sybase --- are among the
largest software companies in the world.
IBM offers its relational DB2 system. With IMS, a non-relational system, IBM is
by some accounts the largest DBMS vendor in the world.
Microsoft offers SQLServer, plus Microsoft Access for the cheap DBMS on the
desktop, answered by ``lite'' systems from other competitors.
Relational companies also challenged by “objectoriented DB” companies
But countered with “objectrelational” systems, which retain the relational core
while allowing type extension as in OO systems.
JDBC
SQL
A data model emphasizes features of interest to the user and makes its
interaction with a DBMS transparent.
Physical data models show how the data structures are organized so that
their resources are optimized.
Logical data models interprete the data in the context of the application.
2. SQL
Structured Query Language is used to write queries to the database in
order to get information from the database and to update the
information to the DB
Here we will see some simple queries [their format and some simple
examples]
SELECT
UPDATE
06/12/25 INSERT Unit 01 314
Sahalu Junaidu Unit 22
Communication with DB from Java
Application
SELECT
Format:
SELECT <LIST OF COLUMNS>
FROM <LIST OF TABLES>
[WHERE <CONDITION(S)>]
[GROUP BY <GROUPING COLUMN(S)>]
[ORDER BY <ORDERING COLUMN(S)>]
Explanation:
For <LIST OF COLUMNS>
a * is used to select all the columns of the
specified table(s).
Individual columns can be selected by
specifying the column names separated by
comas.
If columns from different table are needed, then
tablename.columnname is specified.
06/12/25 Unit 01 315
Sahalu Junaidu Unit 22
Communication with DB from Java
Application
For <LIST OF TABLES>
A table name or list of table name is used
For <CONDITION(S)>
The operators are relational and logical and the
operands are the column names
For <GROUPING COLUMN(S)> and <ORDERING
COLUMN(S)>]
List of columns are specified
Example:
SELECT StuId, StuName FROM STUDENT WHERE AdvId =
“66102”
The table Result of the query
978956 Al-
Quasim
981267 Al-
Helal
To be able to write simple queries and receive their results using methods
in Java programs
The JDBC (short for Java Database Connectivity) interface is a pure Java
API used to execute SQL statements.
The JDBC provides a set of classes and interfaces that can be used by
developers to write database applications.
Basic JDBC interaction, in its simplest form, can be broken down into
four steps:
1. Open a connection to the database
2. Execute a SQL statement
3. Process the SQL statement’s results
4. Close the connection to the database.
The Statement object created above has methods which are used to send SQL
statement to the DBMS. Which method is used, depends on the SQL statement
being sent. For a SELECT statement, the method to use is executeQuery() .
Whereas, for statements that create or modify tables, the method to use is
executeUpdate().
The cursor is initially positioned just above the first row of a ResultSet
object, the first call to the method next() moves the cursor to the first
row and makes it the current row.