Académique Documents
Professionnel Documents
Culture Documents
Sahalu Junaidu
Unit 01
Sahalu Junaidu
Unit 01
1. public class GraduateStudent extends Student{ 2. private String thesisTitle; 3. public GraduateStudent(...){...} 4. public String toString(){...} // overridden 5. public void defendThesis(){...} // added 6. }
Sahalu Junaidu
Unit 01
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.
1. public class Student{ 2. private String name; 3. private int id; 4. private double gpa; 5. //... 6. public String toString(){ 7. return "ID: "+id+ Name: "+name+ GPA: "+gpa; 8. } 9. //... 10. } 1. public class GraduateStudent extends Student{ 2. private String thesisTitle; 3. //... 4. public String toString() // overridden{ 5. return super.toString()+ Thesis Title: "+thesisTitle; 6. } 7. //... Sahalu Junaidu Unit 01 8. }
Overloading vs Overriding
Comparison between overloading and overriding
Overriding deals with two methods, one in a parent class and one in a child class with the same signature
Overloading deals with multiple methods in the same class with the same name but different signatures. Overloading lets you define a similar operation in different ways for different data
Unit 01 6
Overriding lets you define a similar operation in different ways for different object types
Sahalu Junaidu
Constructors are not inherited, even though they have public visibility. However, the super reference can be used within the child's constructor to call the parent's constructor. In that case, the call to parent's constructor must be the first statement.
public class GraduateStudent extends Student{ private String thesisTitle; //... public GraduateStudent(int id, String name, double gpa, String title){ super(id, name, gpa); thesisTitle = title; } //... }
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.
Unit 01
Sahalu Junaidu
Sahalu Junaidu
Unit 01
1. public class Student{ 2. protected String name; 3. protected int id; 4. protected double gpa; 5. //... 6. }
1. public class GraduateStudent extends Student{ 2. private String thesisTitle; 3. //... 4. public String toString(){ 5. return "ID: "+id+"Name: "+name+"GPA: "+gpa+"ThesisTitle: "+thesisTitle; 6. } 7. //... 8. }
Sahalu Junaidu Unit 01 9
Student
GraduateStudent defendThesis()
Sahalu Junaidu
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
Sahalu Junaidu 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.
This assigning is called up-casting, because we are going up the inheritance tree. Up-casting is considered to be a widening conversion since the subclass object has more methods than its superclass.
Sahalu Junaidu Unit 01 12
Why Up-Casting
The advantage of up-casting is that some methods apply to a superclass and all its subclasses. Such a method can be designed to accept a superclass reference so that it can be called with a superclass object or subclass object. For example, a method that generates pay-slip for all employees may have the following heading:
Now since the method is expecting Employee as argument, we can call it with an object of MonthlyEmployee or HourlyEmployee. MonthlyEmployee secretary = new MonthlyEmployee("Al-Amir", 8000); HourlyEmployee consultant = new HourlyEmployee("Umar", 500); //... generatePaySlip(secretary); generatePaySlip(consultant);
Unit 01 13
1. 2. 3. 4. 5.
Sahalu Junaidu
Exercises
Write each of the following classes: 1. A class, Person, with an instance variable, name. Write appropriate accessor and mutator methods for the class. Also write a toString method for the class. Employee, that extends Person, and has: two additional instance variables, ID and payRate; and an additional method, pay, that returns the payRate. Override the toString method accordingly.
2.
3.
Faculty, that extends Employee, and has two additional variables; officeHours of type String and teachingCourses, which is an array of Courses. Each course has course code and course title. Write appropriate accessor, mutator and toString methods for the class. TestPersons, that has two methods: void printPerson(Person p) that prints its argument. And a main method that creates an instance of each of the above classes and prints it using printPerson method.
Unit 01 14
4.
Sahalu Junaidu
Example
class A { String a = "A String"; String method1(){
Example Contd
public static void main(String args[]){ //A obj = new ShadowingVsOverriding(); ShadowingVsOverriding obj = new ShadowingVsOverriding(); System.out.println(obj.a); System.out.println(obj.method1()); System.out.println(obj.method2()); }
Sahalu Junaidu
Unit 01
16
Abstract Classes
What is an Abstract Class? Properties of an Abstract Class
Sahalu Junaidu
Unit 02
17
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.
The payRate field represents the montly pay for the employee. Notice that the pay method simply returns the value of this field.
Unit 02 19
Sahalu Junaidu
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.
Sahalu Junaidu Unit 02 20
1. abstract class Employee{ 2. private String name; 3. private double payRate; 4. 5. public Employee(String name, double payRate){ 6. this.name = name; 7. this.payRate = payRate; 8. } 9. public abstract double pay(); 10. 11. 12. 13. 14. } public void setPayRate(double newRate){ payRate = newRate; } //...
Sahalu Junaidu Unit 02 21
Thus, an abstract class essentially means a class that is "not completely" defined. The term, concrete class, is sometimes used to describe a class that is not abstract. Note: it is not necessary for an abstract class to have abstract methods. Even if all the methods in a class are implemented, the class will still be abstract if it is declared as such in its heading.
Sahalu Junaidu Unit 02 22
Although an abstract class cannot be used to create objects, it can be used to define reference variables. Similar to what we saw in inheritance, this variable can be assigned an object created using a concrete sub-class of Employee.
Sahalu Junaidu
Unit 02
24
In summary, an abstract class is just like a normal class except that it cannot be instantiated and is mainly used to factor out instance variables and methods that all classes in a class-hierarchy should have.
Sahalu Junaidu Unit 02 25
Sahalu Junaidu
Unit 02
27
1. public abstract class Shape{ 2. public String name(){ 3. return getClass().getName(); 4. } 5. public abstract double area(); 6. public abstract double perimeter(); 7. }
1. public class Circle extends Shape{ 2. public double radius; 3. public Circle(double r){ 4. radius = r; 5. } 6. public double area(){ 7. return Math.PI * (radius * radius); 8. } 9. public double perimeter(){ 10. return (2.0 * Math.PI )*radius; 11. } Sahalu Junaidu Unit 02 12. }
28
1. public class Square extends Rectangle{ 2. public Square(double length){ 3. super(length, length); 4. } Sahalu 5. } Junaidu Unit 02
29
Exercises
1. Write a class, TestEmpolyee, that has the following methods: a. printPay(Employee emp) : that prints the name and salary of emp. b. a main method that creates an instance of MonthlyEmployee and that of HourlyEmployee, and prints them using printPay method. Write a class, Manager, that extends MonthlyEmployee, and has another instance variables, bonus and an instance method, setBonus. Override the pay method and update TestEmployee accordinly. Write a class, TestShapes, that creates an instance of each of our shape classes and prints it. Suppose you wish to write an application that stores information about reading materials in a BookShop. Reading matrials could be books, journals, magazines and newspapers. Identify the classes (including abstract classes, if any) that are needed for this application. Draw a class diagram for the classes and implement them.
Unit 02 30
2.
3.
4.
Sahalu Junaidu
Interfaces
What is an Interface? Interface Declaration Syntax Implementing Interfaces Using Interfaces as Types Interfaces and Inheritance Interfaces Cannot Grow Abstract Classes Versus Interfaces
Sahalu Junaidu
Unit 03
31
What is an Interface?
We have seen that inheritance allows code reusability - a subclass inherits the properties of its super class.
All methods in an interface are automatically public and abstract. Thus, the above declaration is the same as the following:
1. public interface Instructor{ 2. public abstract String getOfficeHours(); 3. public abstract Course[] getTeachingCourses(); 4. }
Sahalu Junaidu Unit 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.
1. public class GraduateStudent extends Student implements Instructor{ 2. private String thesisTitle; 3. private String officeHours; 4. private Course[] teachingCourses; 5. public GraduateStudent(int id, String name, double gpa, String title){ 6. super(id, name, workLoad); 7. thesisTitle = title; 8. } 9. // ... other methods 10. public String getOfficeHours(){ 11. return officeHours(); 12. } 13. public Course[] getTeachingCourses(){ 14. return teachingCourses; 15. } 16. } Junaidu Sahalu Unit 03
35
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
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.
Sahalu Junaidu
Unit 03
37
Sahalu Junaidu
Unit 03
38
Sahalu Junaidu
Unit 03
39
This is because Interfaces are like foundation to a building. To make changes, the whole building must be destroyed.
If you add a single method to an interface or change the signature of a method, then all classes that implement the old Interface will break because they don't implement the interface anymore! The only solution in this case is to extend the interface.
Sahalu Junaidu Unit 03 40
Sahalu Junaidu
Unit 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.
Sahalu Junaidu Unit 03 42
Polymorphism
What is Polymorphism?
Down-Casting
Advantages of Polymorphism
Sahalu Junaidu Unit 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.
Sahalu Junaidu Unit 04 44
Sahalu Junaidu
Unit 04
45
The application creates each type of shape and prints its properties.
Sahalu Junaidu Unit 04 46
Sahalu Junaidu
Unit 04
47
The answer, as far as Java Compiler is concerned is I dont 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.
Sahalu Junaidu
Unit 04
48
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.
Sahalu Junaidu
Unit 04
49
Note that the toString method is calling the area and perimeter methods even though they are declared abstract.
Sahalu Junaidu Unit 04 50
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.
Sahalu Junaidu Unit 04
51
Down-Casting
We have seen that an object of a subclass can be assigned to a reference variable of type superclass Up-casting
In fact down-casting is only advisable if the object being down-cast is actually of the subclass type, which was up-cast to the superclass and now being down-cast back to the subclass.
Sahalu Junaidu Unit 04 52
Down-Casting Contd
A good question now is, why would it be necessary to go through this circle of up-casting and then down-casting? To answer this question, we take the following example:
1. import java.util.*; 2. public class TestShapes2{ 3. public static void main(String[] args){ 4. Vector shape = new Vector(3); 5. shape.add(new Rectangle(5, 10)) 6. shape.add(new Square(10)); 7. shape.add(new Circle(15)); 8. System.out.println("Shape\tArea"); 9. System.out.println("***************************"); 10. for(int i = 0; i<shape.size(); i++){ 11. Shape nextShape = (Shape)shape.get(i); 12. System.out.println(nextShape.name()+"\t"+nextShape.area()); 13. } 14. }}
Sahalu Junaidu Unit 04 53
Down-Casting Contd
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 downcast 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. }
Sahalu Junaidu Unit 04
54
Down-Casting Contd
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.
To avoid this, it is advisable to always use the instanceof operator to check the type of objected before down-casting it.
1. Employee emp1 = new MonthlyEmployee("Sahalu Junaidu"); 2. if(emp1 instanceof HourlyEmployee){ 3. HourlyEmployee emp2 = (HourlyEmployee)emp1; 4. emp2.addHours(60); 5. }
Sahalu Junaidu Unit 04 55
Advantages of Polymorphism
To conclude, we take a quick look at the advantages of polymorphism
Generic Code: Polymorphism allows us to write code that can be applied to different types of objects and get different result based on the object. There is no need to write separate code for each type.
Extensibility: It allows the functionality of a code to be extended. For example, if we define another subclass of Shape, Triangle, then the same code in our application can be used to process Triangle shapes as well.
Sahalu Junaidu
Unit 04
56
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.
Unit 04 57
Sahalu Junaidu
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.
Sahalu Junaidu Unit 04 58
Packages
What is a Package? Why use Packages?
Creating a Package
Naming a Package Using Package Members Managing Source and Class Files Visibility Modifiers
Sahalu Junaidu
Unit 05
59
What is a Package?
A package is a collection of related classes and interfaces that provides access protection and namespace management. The classes in Java API are organized into packages. For example: Applet classes are in java.applet package I/O classes are in java.io package
Sahalu Junaidu
Unit 05
60
You can allow classes within a package to have access to each other.
Sahalu Junaidu
Unit 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.
1. public abstract class Shape{ 2. public String name(){ 3. return getClass().getName(); 4. } 5. public abstract double area(); 6. public abstract perimter(); 7. public String toString(){ 8. return name()+"\nPerimeter: "+perimeter()+"\nArea: "+area(); 9. } 10. }
Sahalu Junaidu Unit 05 62
Creating a Package-Contd
The scope of the package statement is the entire source file, so if source file contains more than one class or interface,
Sahalu Junaidu
Unit 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
Naming a Package-Contd
Within one organization, it is clear that packages can be used to avoid conflict in class names. What about between different organizations? It is likely that two organizations working on similar projects may come up with the same package names and probably common class names. Thus, a user dealing with these two organizations may still face conflict. To avoid this, by convention, organizations use their reversed Internet domain name in their package names, like: com.company.package We shall name our packages in this course starting with the prefix, ics201. Example: ics201.graphics, ics201.lab01, etc.
Sahalu Junaidu Unit 05 65
Each of these methods is appropriate for different situations, as explained in the following sections.
Sahalu Junaidu Unit 05 66
Sahalu Junaidu
Unit 05
67
6. public class TestShapes{ 7. public static void main(String[] args){ 8. Shape[] shapes = new Shape[2]; 9. shape[0] = new Rectangle(5, 10); 10. shape[0] = new Square(10); 11. 12. for(int i = 0; i<shape.length; i++) 13. System.out.println(shape[i]); 14. } 15. }
As noted earlier, ics201 and ics201.graphics are independent packages, so the statement, import ics201.*; only imports ics201 package but not ics201.graphics.
Unit 05 69
Sahalu Junaidu
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.
Sahalu Junaidu
Unit 05
70
Sahalu Junaidu
Unit 05
71
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
Sahalu Junaidu
Unit 05
Sahalu Junaidu
Unit 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.
Sahalu Junaidu
Unit 05
74
Example
1. package package1; 2. public class A{ 3. public A(){
4.
5. 6. 7. 8. 9. 10. } }
11. }
12. }
Sahalu Junaidu Unit 05 75
Example (contd)
1. 2. 3. 4. package package2; import package1.*; public class B extends A{ public B(){
5.
6. 7. 8. 9. }
10.
11. 12. 13. 14.
}
public int method2(int x){ return x; } public static void main(String [] x){
15.
16. 17. 18. } }
B b = new B();
System.out.println(b.method1(3));
Sahalu Junaidu
Unit 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?
Sahalu Junaidu Unit 05 77
Linking
o Verification o Preparation o Resolution
Sahalu Junaidu
Unit 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.
Sahalu Junaidu
Unit 06
79
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.
Sahalu Junaidu Unit 06 80
Class Loading
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.
Sahalu Junaidu Unit 06 82
1. 2. 3. 4. 5. 6. 7.
Sahalu Junaidu
Sahalu Junaidu
Unit 06
84
import java.lang.reflect.Method; public class TestClassClass{ public static void main(String[] args) throws Exception { Class test = Class.forName("TestClassClass"); System.out.println("\nClass name is: "+test.getName()); System.out.println("Superclass is: "+test.getSuperclass()); System.out.println("\nMethods are: "); Method[] methods = test.getMethods(); for(int i = 0; i<methods.length; i++) System.out.println(methods[i]); } }
Sahalu Junaidu
Unit 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.
Sahalu Junaidu Unit 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:
Sahalu Junaidu
Unit 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.
1. 2. 3. 4. 5. 6. 7.
For the class below, at the loading phase, the class loader would have loaded the classes: TestClassClass, Circle, Shape, System, & Object.
public class TestClassClass{ public static void main(String[] args){ Circle circle = new Circle(10); Class circleClassInfo = circle.getClass(); System.out.println("Parent is: "+circleClassInfo.getSuperclass()); } }
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.
Unit 06 88
Sahalu Junaidu
Class Initialization
1. 2. 3. 4. 5.
This is the process of setting class variables to their proper initial values - initial values desired by the programer.
class Example1{ static double rate = 3.5; static int size = 3*(int)(Math.random()*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. ... Sahalu}Junaidu Unit 06 5.
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.
Sahalu Junaidu
Unit 06
90
2. If this constructor begins with an explicit invocation of another constructor in the same class (using this), then evaluate the arguments and process that constructor invocation recursively.
3. If this constructor is for a class other than Object, then it will begin with an explicit or implicit invocation of a superclass constructor (using super). Evaluate the arguments and process that superclass constructor invocation recursively. 4. Initialize the instance variables for this class with their proper values. 5. Execute the rest of the body of this constructor.
Sahalu Junaidu
Unit 06
91
92
Sahalu Junaidu
Unit 06
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. Write a program to show that Loading may be caused either by creating an instance of a class or by accessing a static member. 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. 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.
Unit 06 94
2. 3.
4.
Sahalu Junaidu
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
Unit 07 95
Sahalu Junaidu
Sahalu Junaidu
Unit 07
96
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.
Sahalu Junaidu Unit 07 97
Sahalu Junaidu
Unit 07
99
The class implementing MaxMin must have access to the grades array. To return the best and worst grades, we may define two methods. We define a class Pair that holds the best and worst grades.
Sahalu Junaidu Unit 07 101
Example 1 (contd)
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 }
Sahalu Junaidu Unit 07 103
Sahalu Junaidu
Unit 07
104
106
107
The next example demonstrates how this can be done. To refer to the outer class object, use the notation OuterClass.this
Sahalu Junaidu
Unit 07
108
1 public void bestAndWorst(){ 2 if(Course2.this.grades.length > 0){ 3 this.best = Course2.this.grades[0]; 4 this.worst = Course2.this.grades[0]; 5 for(int i=1; i<grades.length; i++){ 6 if (best < grades[i]) best = grades[i]; 7 else if (worst > grades[i]) worst = grades[i]; 8 } 9 } 10 }
// code omitted
Sahalu Junaidu Unit 07 109
Sahalu Junaidu
Unit 07
110
Sahalu Junaidu
Unit 08
Sahalu Junaidu
Unit 08
112
attractive.
Provide visual and audible feedback. Be responsive.
Sahalu Junaidu
Unit 08
113
Sahalu Junaidu
Unit 08
114
Sahalu Junaidu
Unit 08
115
Sahalu Junaidu
Unit 08
116
Sahalu Junaidu
Unit 08
117
Review Exercises
1. 2. 3. 4. 5. Explain the advantages of graphics-based over text-based user interfaces. What is a good and effective GUI? Why is it necessary to design GUI for all on-trivial applications? Explain.. Explain the implications of good as well as badly designed GUIs. What is JFC? What Swing? Why was the JFC enriched with Swing? AWT components are said to be heavy weight while Swing components are said to be light weight. Explain what these notions mean. Enumerate the major knowledge units that must be understood for developing effective GUI applications. Briefly explain each of these knowledge units.
6.
Sahalu Junaidu
Unit 08
118
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
Unit 09 119
Sahalu Junaidu
Introduction to Components
A component is an object having a graphical representation that can be displayed on the screen.
Example of components in a typical GUI include: buttons, text boxes, lables and pop-up menus
Sahalu Junaidu Unit 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
Functionality of most GUI components derive from the Component and Container classes.
Sahalu Junaidu
Unit 09
121
Sahalu Junaidu
Unit 09
123
Unit 09
126
Sahalu Junaidu
Unit 09
127
Sahalu Junaidu
Unit 09
128
Sahalu Junaidu
Unit 09
130
Sahalu Junaidu
Unit 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. 3. Write down in tabular form the similarities and differences between top-level components and other GUI components. 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
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
Sahalu Junaidu
Unit 10
133
Sahalu Junaidu
Unit 10
134
Sahalu Junaidu
Unit 10
135
Sahalu Junaidu
Unit 10
136
Notice that when you press a key, at least two events are generated.
Sahalu Junaidu
Unit 10
138
Sahalu Junaidu
Unit 10
140
Sahalu Junaidu
Unit 10
141
142
Sahalu Junaidu
Unit 10
143
Sahalu Junaidu
Unit 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. 3. Modify the program in Example 2 to work as a stand-alone application. Modify the program in Example 3 to display its output on the applications 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.
Sahalu Junaidu
Unit 10
146
Sahalu Junaidu
Unit 10
147
Introduction FlowLayout Manager GridLayout Manager Self-check Exercise 1 BorderLayout Manager GridBagLayout Manager Self-check Exercise 2 Exercises
Unit 11 148
Sahalu Junaidu
o FlowLayout()
o FlowLayout(int align)
Sahalu Junaidu
Unit 11
150
Unit 11
151
o GridLayout() o GridLayout(int rows, int cols) o GridLayout(int rows, int cols, int hgap, int vgap)
Sahalu Junaidu Unit 11 152
When you enlarge a container the center area grabs as much of the new space as possible.
BorderLayout is good for maintaining a row of buttons in one
Exercises
1. Move the call to the setVisible() method from the main() method to the TetFlowLayout constructor in Example 1. Then compile and run each of Examples 2, 3 and 4. You will notice some changes when displaying the frames. Explain. 2. Modify Example 2 to add two other types of borders to it. 3. Compare Example 2 and Example 3. In Example 2 we inherited a panel, added more components to it and then changed the panel layout manager. In Example 3 we had to create an additional panel. Can Example 3 be written in similar manner to Example 2 without the additional panel? If it is possible, write the equivalent program otherwise explain why it is not possible. 4. Change the fill constraint variable on Line 13 from BOTH to each of the following: NONE, HORIZONTAL and VERTICAL. Run the program in each case and study the effect.
Sahalu Junaidu
Unit 11
156
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
Sahalu Junaidu
Unit 12
157
Introduction
This is our concluding session on GUIs and event-driven programming. In our discussion on GUI-based programs so far, we have covered: GUI design issues, GUI components and containers. Basic event handling. Basic layout management. We now cover typical GUI elements found in Windows environment including: Menus and pop-up menus File dialogs Mnemonics and keyboard accelerator
With this coverage the student's knowledge base of the basics would
be broadened.
Unit 12 158
Sahalu Junaidu
Introduction to Example 1
This example builds on Example 4 of the preceding section. Example 4 of the preceding section developed a simple GUI for a
telephone handset.
We will now add event-handling code to display typed numbers. Here is a sample output of the program:
Sahalu Junaidu
Unit 12
159
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:
Sahalu Junaidu
Unit 12
161
o JMenuItem
o JMenu o JCheckButtonMenuItem
o JRadioButtonMenuItem
Sahalu Junaidu
Unit 12
162
Sahalu Junaidu
Unit 12
163
164
Sahalu Junaidu
Unit 12
165
Introduction to Example 3
This example extends Example 2 to launch a file dialog on selecting the Open menu. The selected file name is simply printed on another display window. The output is as follows:
Sahalu Junaidu
Unit 12
166
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 components background color.
Sahalu Junaidu Unit 12 168
169
170
Review Exercises
1 2 What are the event sources and event listeners in Example 1? Can the event handler in Example 1 be implemented in a single anonymous class? If not, why not? 3 Modify Example 1 to use two inner classes instead of one. Can the two inner classes both be anonymous? Is the program with one inner class better than the one with two? Explain. 4 Enhance Example 1 so that when the Redial button is pushed the last text displayed on the text component is displayed again. 5 Write a Java program to illustrate how a component event can be handled. 6 Modify Example 3 so that when a file is double-clicked from the file dialog indow the file is opened rather than displaying its name in the editor pane. 7 When you run Example 4, you will find that the lower part of the window is not responding to the popup menu. Modify this program to ensure that that part of the window also responds to the popup menu events like the buttons in the window.
Sahalu Junaidu
Unit 12
171
Exercises
Sahalu Junaidu Unit 13 172
Sahalu Junaidu
Unit 13
173
public class BankAccount implements Comparable{ private int accountNumber; // . . . public int compareTo(Object object){ BankAccount account = (BankAccount) object; if(accountNumber < account.accountNumber) return ; else if(accountNumber == account.accountNumber) return 0; else return 1; }}
Sahalu Junaidu
Unit 13
174
4. else 5. System.out.println(Different accounts); To define an ordering for objects that do not implement Comparable, or to define an ordering other than the natural ordering defined by Comparable, the java.util.Comparator interface should be used.
Sahalu Junaidu
Unit 13
175
the collection objects to be ordered do not have a natural ordering defined by the Comparable interface
the objects are to be ordered by not using their natural ordering.
Unit 13 176
Sahalu Junaidu
It is also preferable for the compare method to return 0 if and only if object1.equals(object2) is true. The compare method throws a ClassCastException if the type of object1 and that of object2 are not compatible for comparison. The equals method returns true if its parameter is a Comparator object and if it uses the same ordering as the invoking Comparator object; otherwise it returns false.
Sahalu Junaidu
Unit 13
177
Sahalu Junaidu
Unit 13
178
Sahalu Junaidu
Unit 13
181
Sahalu Junaidu
Unit 13
182
Sahalu Junaidu
Unit 13
183
Exercises
1.
2. Write a Comparator to compare names by middle name. Assume that each name to be compared, consists of three names: first, middle, and last.
3. Arrange algorithm complexity classes from the most time-efficient to the least time-efficient.
Sahalu Junaidu
Unit 13
184
Binary Search
Selection Sort Insertion Sort Bubble (or Exchange) Sort Exercises
Sahalu Junaidu Unit 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.
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.
Note: linear search can be applied to both sorted and unsorted arrays.
Sahalu Junaidu Unit 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:
if(there are more elements in the current array){ Compare the current middle array element with key (the value searched for). There are three possibilities:
1. 2. 3.
key == array[middle] the search is successful, return middle. key < array[middle] binary search the current lower half of the array. key > array[middle] binary search the current upper half of the array.
Sahalu Junaidu
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.
Sahalu Junaidu
Unit 14
189
minPos = k;
} temp = array[minPos]; array[minPos] = array[i]; array[i] = temp; } }
Sahalu Junaidu Unit 14 190
Sahalu Junaidu
Unit 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] }
//inserting to maintain ascending order temp = array[i]; k = i; while(k > 0 && array[k - 1] > temp){
Sahalu Junaidu
Unit 14
192
array[k] = temp;
} }
Sahalu Junaidu Unit 14 193
Sahalu Junaidu
Unit 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++)
Sahalu Junaidu
Unit 14
195
Sahalu Junaidu
Unit 14
196
Sahalu Junaidu
Unit 14
197
Exercises on Searching
1. 2. 3. 4. 5. 6. 7. 8. 9. What is a sequential search? What is a binary search? Write an iterative binarySearch method on an Object array. Write a recursive binarySearch method on a double array. Write a recursive linearSearch method on an Object array. Write an iterative linearSearch method on a double array. A binary search of an array requires that the elements be sorted in ascending order. Suppose it is known that an array is sorted. When is linear search better than binary Search? Mention the advantages, if any, of linear search over binary search.
10. Mention the advantages, if any, of binary search over linear search.
11. 12. 13. Mention the disadvantages, if any, of binary search over linear search. Mention the disadvantages, if any, of linear search over binary search. 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.
Sahalu Junaidu
Unit 14
198
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) (c) 18. completely unsorted? sorted in descending order? (b) sorted in ascending order?
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?
Sahalu Junaidu
Unit 14
199
20.
21. Write a binary search method: 21 public static Object binarySearch(Object[] array, Object key)
that returns null if the search is not successful; otherwise it returns a reference to the a matching object. Assume that the elements of the array are Comparable.
Sahalu Junaidu
Unit 14
200
Sahalu Junaidu
Unit 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. 3. 4. 5. Write a recursive bubble sort on a double array. Write a recursive insertion sort on a double array. Write a recursive selection sort on an Object array of Comparable objects. Many operations can be performed faster on sorted than on unsorted data. For which of the following operations is this the case? (a) (b) Finding an item with minimum value. Computing an average of values.
(c)
(d) (e) (f) (g)
Sahalu Junaidu
Unit 14
(c) insertion sort.
202
11.
Sahalu Junaidu
Unit 14
203
Sahalu Junaidu
Unit 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 }
Sahalu Junaidu
Unit 15
205
Sahalu Junaidu
Unit 15
206
private static void mergeSort(Object[] array, int low, int high, Comparator comparator){ if(last > first){ int mid = (low + high)/2; mergeSort(array, low, mid, comparator); mergeSort(array, mid + 1, high, comparator); merge(array, low, mid, mid + 1, high, comparator); } }
Sahalu Junaidu Unit 15 207
}
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]; }
Sahalu Junaidu
Unit 15
208
mergeSort(array, low, high){ if(high > low){ middle = (low + high) / 2; mergeSort(array, low, middle); mergeSort(array, middle + 1, high); merge(array, low, middle, middle + 1, high); } }
Sahalu Junaidu
Unit 15
209
Quick Sort
The quick sort algorithm to sort an array from index low to high:
if(high > low){ 1. 2. Select a pivot element p to be used to partition the array into two partitions. 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
array[pivotIndex] = pivotValue
array[pivotIndex + 1]...array[high] >= pivotValue quickSort(array, low, pivotIndex 1); quickSort(array, pivotIndex + 1, high); } Sahalu Junaidu
Unit 15
210
Sahalu Junaidu
Unit 15
211
Sahalu Junaidu
Unit 15
212
Sahalu Junaidu
Unit 15
213
Exercises
1. 2. 3. 4. What is the advantage of the bubble sort algorithm we have studied over all the other sorting methods we have studied? When are bubble, insertion, and selection sort methods more efficient than merge sort and quicksort? What is the disadvantage of merge sort as compared to quicksort? What role, if any, does the size of data objects play in a sort?
5.
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)
(d) 7.
The sort is fastest if the original integers are completely in random order.
The sort is the same, no matter what the order of the original integers.
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.
Sahalu Junaidu
Unit 15
214
Exercises (contd)
9. 10. 11. 12. 13. 14. In quicksort, why is it better to choose the pivot from the center of the array rather from one of the ends? What is the property of the best pivot in a quicksort? What is the property of the worst pivot in a quicksort? Suppose that, instead of sorting, we wish only to find the mth quicksort can be adapted to this problem, doing much less work than a complete sort. 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. 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.
Sahalu Junaidu
Unit 15
215
Exercises (contd)
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.
Sahalu Junaidu
Unit 15
216
Sahalu Junaidu
Unit 16
217
Other data structures, like linked list and trees, are better for some situations The JCF provides efficient implementations for these common data structures Using the JCF interfaces, these data structures can be manipulated in a uniform way
Sahalu Junaidu
Unit 16
219
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
Sahalu Junaidu
Unit 16
220
<<interface>> Comparator
Collections
AbstractCollection
<<interface>> Collection
AbstractList
<<interface>> List
ArrayList
Sahalu Junaidu
Unit 16
221
The interface: public interface Comparator { public abstract int compare(Object object1, Object object2); public abstract boolean equals(Object obj); }
Sahalu Junaidu
Unit 16
222
Sahalu Junaidu
Unit 16
Sahalu Junaidu
Unit 16
225
To visit all the elements of a collection object c, code such as such as the following may be used:
Iterator iter = c.iterator(); while(iter.hasNext( )){ Object obj = iter.next(); process(obj); }
Note: When next() is invoked, the iterator jumps over the next element, and it returns a reference to the object that it just passed.
Sahalu Junaidu Unit 16 226
It is illegal to call the remove() method of an iterator if it was not preceded by a call to next(). For example, the following is invalid:
Iterator iter iter.remove(); = c.iterator( );
Sahalu Junaidu
Unit 16
227
Sahalu Junaidu
Unit 16
228
Sahalu Junaidu
Unit 16
229
Sahalu Junaidu
Unit 16
230
Sahalu Junaidu
Unit 16
Sahalu Junaidu
Unit 17
232
<<interface>> Collection
Collections AbstractCollection
AbstractList
<<interface>> List
ArrayList
AbstractSequentialList
LinkedList
Sahalu Junaidu
Unit 17
233
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
Sahalu Junaidu Unit 17 234
Sahalu Junaidu
Unit 17
235
Sahalu Junaidu
Unit 17
239
Sahalu Junaidu
Unit 17
240
Using the LinkedList Collection Introduction to Stacks and Queues Implementing Stacks and Queues using LinkedList
Sahalu Junaidu
Unit 18
242
If, on the other hand, there are frequent retrievals, then the ArrayList Collection is a better choice for good performance. A linked data structure is a collection of nodes storing data and links
Next, we show the nodes declarations for these two flavors of linked lists.
Sahalu Junaidu
Unit 18
243
tail
Sahalu Junaidu
Unit 18
244
Sahalu Junaidu
Unit 18
245
247
Sahalu Junaidu
Unit 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 }
Sahalu Junaidu
Unit 18
249
22 public void clear(){ 23 list.clear(); 24 } 25 public boolean isEmpty(){ 26 return list.isEmpty(); 27 } 28 public int contains(Object obj){ 29 return list.indexOf(obj); 30 } 31 public String toString(){ 32 return list.toString(); 33 } 34 }
250
251
Sahalu Junaidu
Unit 18
252
Sahalu Junaidu
Unit 18
253
Sahalu Junaidu
Unit 18
254
is always done at the last queue position (rear), and removal (dequeing) is
always done at the first queue position (front). 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
Sahalu Junaidu
Unit 18
255
22 public void clear(){ 23 list.clear(); 24 } 25 public boolean isEmpty(){ 26 return list.isEmpty(); 27 } 28 public int contains(Object obj){ 29 return list.indexOf(obj); 30 } 31 public String toString(){ 32 return list.toString(); 33 } 34 }
256
Sahalu Junaidu
Unit 19
257
Each thread has its own stack, priority, and virtual set of registers
Every program has at least one thread Every Java applet or application is multithreaded
Sahalu Junaidu
Unit 19
258
Sahalu Junaidu
Unit 19
259
Sahalu Junaidu
Unit 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 Although Java is portable, its multithreading is platform dependent: a multithreaded program could behave differently on different platforms: Under Solaris implementation, an executing thread can run to completion or can be preempted by a higher priority thread On windows (NT and 98) threads are timesliced and preemption occurs with higher as well as with equal priority threads To create a thread, you extend java.lang.Thread or implement java.lang.Runnable
Sahalu Junaidu
Unit 19
261
Sahalu Junaidu
Unit 19
262
Sahalu Junaidu
Unit 19
263
264
ready
stop()
blocked
Sahalu Junaidu
Unit 19
265
Sahalu Junaidu
Unit 19
267
Sahalu Junaidu
Unit 19
268
269
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 Every Java thread has a priority in the range Thread.MIN_PRIORITY (a constant value, 1) and Thread.MAX_PRIORITY (a constant value, 10). The default priority is Thread.NORMAL_PRIORITY (a constant value, 5) 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
Sahalu Junaidu
Unit 19
271
272
Sahalu Junaidu
Unit 20
273
Sahalu Junaidu
Unit 20
274
Threads Synchronization
When a block of Java code guarded by the synchronized keyword, it can be executed by only one thread at any time A shared resource (implemented by a given code segment) may be corrupted if it is accessed simultaneously by multiple threads. E.g., unsynchronized threads accessing the same database Such blocks of code are usually called critical sections and must be executed in a mutually-exclusive way You can synchronize an entire method or just a few lines of code by using the synchronized keyword Note that code that is thread-safe (i.e, guarded by synchronized) is slower than code that is not
Sahalu Junaidu
Unit 20
275
Sahalu Junaidu
Unit 20
278
Sahalu Junaidu
Sahalu Junaidu
Unit 20
280
281
Sahalu Junaidu
Unit 20
Download the car image used in the example from here. You can also obtain the rocket image for the next example.
Sahalu Junaidu
Unit 20
283
Sahalu Junaidu
Unit 20
284
Sahalu Junaidu
Unit 20
285
286
Exercises
1. Modify Example 2 so that when the animation is stopped, the strings Salaam and Shabab remain displayed on the animation screen. 2. Modify Example 2 so that the strings Salaam and Shabab move in opposite direction horizontally rather than vertically. 3. Improve the car race animation by
1. 2. 3. 4. Adding a button to control when to start the next race Incorporating up to four cars in the race Displaying the winning car after every race Incorporating different car models
4. Modify each of the preceding examples so that each of them can work as an applet as well as a standalone application.
Sahalu Junaidu Unit 20 287
Introduction to Databases
Overview
Objectives of this lecture. History and Evolution of Databases. Basic Terms in Database and Definitions of Database and DBMS.
Sahalu Junaidu
Sahalu Junaidu
Unit 21
Sahalu Junaidu
File
Sahalu Junaidu
Unit 21
In order to overcome these limitations, a whole new area of Computer science called Database Applications (or simply Data Bases) evolved. DBMS overcomes limitations Eliminates separation and isolation of data Reduces Data Redundancy Eliminates dependence between Program and Data Allows for representation of data from the users view Increases Data Flexibility
Unit 21
Sahalu Junaidu
Sahalu Junaidu
Unit 21
Sahalu Junaidu
File
Application Program
DBMS
ENGINE
Physical memory
File
Operating System
Sahalu Junaidu Unit 21
Database Schema
Database Schemas: This is a logical design of a database. It consists of a set of tables of the data types used, giving the names of entities and attributes and the relationship among them. Schemas are classified as internal when they correspond to physical database and external when they correspond to data in application programs. The capability to change the internal schemas as needed without affecting the external schema is called data independence. Schemas are generally written in a data definition language which generates the schema tables stored in a file called a data dictionary. The data dictionary is always accessed before any change to the physical data is made. The following figure illustrates some of these concept.
Unit 21
Sahalu Junaidu
DBMS
(logical)
Data Files
Data Dictionary
(physical)
Secondary Storage
Sahalu Junaidu Unit 21
Sahalu Junaidu
Unit 21
Sahalu Junaidu
JDBC
SQL Preview: Data Communications
Sahalu Junaidu
Unit 22
Sahalu Junaidu
Unit 22
Sahalu Junaidu
Unit 22
Popular approaches to logical data models include: 1. Entity-Relationship model 2. Hierarchical and Network models. 3. Relational model.
Next we briefly discuss the Relational model.
Sahalu Junaidu
Unit 22
Relational Model
The most popular logical data model in use today is the relational model which is noted for its consistency, simplicity and data independence. It is composed of relations, attributes, domains, keys, tuples and their representations. A relation is a table of rows and columns. Each column of the table is an attribute. The domain of each attribute is the collection of values that can be assigned to a particular attribute. A principal key is one or more attribute values that uniquely identify an entity instance. A tuple is an ordered sequence of elements. Example the sequence (p,q,r,s,t,u) is a 6-tuple. Each row is an entity instance represented by a tuple.
Sahalu Junaidu
Unit 22
Sahalu Junaidu
Relation
Typically, relations have a representation consisting the relation name, followed by a list of attributes in form of a tuple with the principal key highlighted. e.g., ADVISOR (AdvId, Adv-Name, Adv-Phone)
The following shows a typical relational data model called an instance table. RELATION = ADVISOR primary key: AdvId
AdvId 66101 66102 66103 66104 Adv Name Adv Phone Sahalu Al-Ghamdi Sadiq Badhusha 333-2111 405-8888 501-8241 222-2357
Sahalu Junaidu
Unit 22
Relations (cont.)
The following table defines another relation for the entity Student with attributes StuID, StuName, StuPhone and AdvId. RELATION = STUDENT StuId StuName StuPhone AdvId 452-7634 66104 66102 66101 66102
987654 Al-Amer
In relational databases, new relations can be generated from others. For example, the relation is advised by can be defined between the relations STUDENT and ADVISOR.
Sahalu Junaidu
Unit 22
Foreign key A foreign key is an attribute in a relation that is also a primary key in another relation. This foreign key-primary key match allows references between relations in order to locate information.
Sahalu Junaidu Unit 22
987654 Al-Amer
993421 Al-Ali
981267 Al-Helal
865-3476
894-2384
66101
66102
Sahalu Junaidu
Unit 22
1.
Sahalu Junaidu
Unit 22
DB
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 INSERT
Unit 22
Sahalu Junaidu
Sahalu Junaidu
Unit 22
Sahalu Junaidu
Unit 22
993421
981267
Al-Ali
Al-Helal Format
865-3476
894-2384
66101
66102
UPDATE UPDATE <TABLE NAME> SET <COLUMN NAME> = <VALUE> [WHERE <CONDITION>]; --if the Where clause is left out, all rows will be updated according to the Set statement.
987654 Al-Amer
987654 Al-Amer
452-7634
66104
66102 66109 66102
Sahalu Junaidu
Unit 22
987654 Al-Amer
987654 Al-Amer
452-7634
66104
66102 66109 66102
66102
66101 66102
865-3476 894-2384
66105
Introduction to JDBC
Overview Objectives of this lecture JDBC and its Drivers Connecting to Databases (Javas Connection class) Querying a Database (Javas Statement class) Obtaining Query Results (Javas ResultSet class) Preview: Introduction to Data Communications
Sahalu Junaidu
Unit 23
To have an acquintance of JDBC drivers To know the basic issues required to connect to a database from a Java application
To be able to write simple queries and receive their results using methods in Java programs
Sahalu Junaidu
Unit 23
JDBC Basics
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 statements results 4. Close the connection to the database.
Sahalu Junaidu
Unit 23
JDBC Drivers
As mentioned in Lecture 28, a Java application can communicate to a DBMS using specialized programs called Drivers. The JDBC supports two database access models: two-tier and three-tier. Using a two-tier model, a Java application talks directly to the database. This is accomplished through the use of a JDBC driver, which sends commands directly to the database. With a two-tier database access model, the JDBC driver and the database communicate through a middle-tier system. Sun Microsystems has defined four JDBC driver types: JDBC-ODBC bridge plus ODBC Driver Native-API Partly-Java Driver JDBC-Net Pure Java Driver Native-Protocol Pure Java Driver
Sahalu Junaidu
Unit 23
Sahalu Junaidu
Unit 23
Sahalu Junaidu
Unit 23
Establishing a Connection
Making the Connection involves creating a Connection object that links the driver to the DBMS. Connection con = DriverManager.getConnection(url, "myLogin", "myPassword"); or Connection con = DriverManager.getConnection(url); where url = jdbc:odbc:DataSetName Since we are using the JDBC-ODBC Bridge driver, the JDBC URL will start with jdbc:odbc: . The rest of the URL is generally the data source name defined in the configuration of ODBC The second version assumes you do not need to login to the computer hosting the database file. Connection con = DriverManager.getConnection(url);
Sahalu Junaidu
Unit 23
The next step after establishing a connection is to create a Statement object using the Connection object as follows: Statement statement = con.createStatement();
Creating JDBC Statements and Sending SQL statements to the data source
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(). String query = "select * from table1"; ResultSet result = statement.executeQuery(query);
Notice that executeQuery() method returns an object of ResultSet which contains the result of the query.
Sahalu Junaidu Unit 23
Creating JDBC Statements and Sending SQL statements to the data source
The executeUpdate() is similar, except that we are not expecting result from the data source. String query2 = "INSERT INTO table1 VALUES (a', b', c', 1)"; statement.executeUpdate(query2);
Sahalu Junaidu
Unit 23
Sahalu Junaidu
Unit 23
Sahalu Junaidu
Unit 23