Object Oriented Programming
Object Oriented Programming
Department of Mathematics
Object Oriented Programming I By Prof. S.B. Junaidu
(sahalu@abu.edu.ng)
Object-Oriented Programming I
Content
1. Computer Systems Anatomy 2. Overview of Programming Languages 3. Programming Languages Translation 4. Fundamental Data Types 5. Algorithms 6. Basic OO Concepts 7. Introduction to Strings 8. Introduction to Console I/O 9. Introduction to Classes I 10. Introduction to Classes II 11. Selection 12. Iteration 13. More About Methods I 14. More About Methods II
Sahalu Junaidu, Math Dept., ABU, Zaria
15.String Tokenization 16.Exception Handling 17. Text File I/O 18. 1-D Arrays 19. Dynamic Arrays 20. 2-D Arrays 21. Inheritance I 22. Inheritance II 23. Introduction to Applets I 24. Introduction to Applets II 25. Introduction to Recursion
Object-Oriented Programming I
What is a Computer?
Anatomy of a Computer System Computer Software Computer Hardware Fetch-Decode-Execute Cycle CPU Families Exercises
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
3
input
processing
output
memory Input data of a computer may represent numbers, words, pictures etc
Programs that control the operations of the computer are stored inside the computer
Object-Oriented Programming I
Object-Oriented Programming I
Systems Software
System software manages computer resources and makes computers easier to use
Applications Software
An applications software enables a computer user to do a particular task Example applications software include:
Word processors Game programs Spreadsheets (or Excel sheets) Database systems Graphics programs Multimedia applications
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
7
Computer Hardware
Object-Oriented Programming I
I/O (Input/Output)Devices
Input devices are used to enter programs and data into a computer system.
Examples: keyboard, mouse, microphone, and scanner.
Object-Oriented Programming I
Computer Memory
The main function of computer memory is to store software. Computer memory is divided into primary memory and secondary memory. Primary memory is divided into random access memory (RAM) and readonly memory (ROM):
The CPU can read and write to RAM but the CPU can read from ROM but cannot write to ROM RAM is volatile while ROM is not.
Secondary memory
Examples of secondary memory devices are: hard disks, floppy disks and CD ROMs
10
Object-Oriented Programming I
Primary Memory
Object-Oriented Programming I
11
The CPU
The CPU is the "brain" of the computer system.
The CPU directly or indirectly controls all the other components.
The CPU has a limited storage capacity. Thus, the CPU must rely on other components for storage.
The CPU consists of:
1. 2. 3. The Arithmetic and Logic Unit (ALU). The Control Unit (CU). Registers.
The CPU components are connected by a group of electrical wires called the CPU bus.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
12
Object-Oriented Programming I
13
Object-Oriented Programming I
14
Control Unit
2 Decode
cpu
RAM
Store
Arithmetic/Logic Unit
Object-Oriented Programming I
15
CPU Families
Different people understand different natural languages. Similarly, each processor family understands its own machine language. The fundamental difference between computers that are not compatible is in their processors. Here are some CPU families:
Pentium Power PC SPARC
The question now is: Is it possible to write a single program that can be understood and correctly executed on machines with different processors?
Well address this question in a subsequent lecture.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
16
Drill Questions
1. Write short notes explaining the functions of each of the following
1. Computer memory 2. The CPU 3. Computer software
2. I/O devices can be used to input into and output from a computer system. Then, is computer memory necessary? Explain. 3. Since the OS controls the hardware and software in a computer system, which programs control the loading of an OS onto a computer system? 4. The system bus consists of three buses. Mention them and explain each of them briefly. 5. Since different CPUs understand different instructions, how are we able to exchange information between machines with different CPUs?
Object-Oriented Programming I
17
Object-Oriented Programming I
18
Computer Programming
The functions of a computer system are controlled by computer programs A computer program is a clear, step-by-step, finite set of instructions
A computer program must be clear so that only one meaning can be derived from it,
A computer program is written in a computer language called a programming language
Object-Oriented Programming I
19
Programming Languages
There are three categories of programming languages:
1. 2. 3. Machine languages. Assembly languages. High-level languages.
Machine languages and assembly languages are also called low-level languages
Object-Oriented Programming I
20
Advantages
Fast and efficient
Machine friendly No translation required
Disadvantages
Not portable Not programmer friendly
Object-Oriented Programming I
21
Assembly Language
Assembly language programs use mnemonics to represent machine instructions Each statement in assembly language corresponds to one statement in machine language. Assembly language programs have the same advantages and disadvantages as machine language programs. Compare the following machine language and assembly language programs:
1010 0001 0000 0000 0000 0000 MOV AX , var1 0000 0011 0000 0110 0000 0000 0000 0010 ADD AX , var2 1010 0011 0000 0000 0000 0000 MOV var1 , AX
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
22
A HLL language program consists of English-like statements that are governed by a strict syntax.
Advantages
Portable or machine independent Programmer-friendly
Disadvantages
Not as efficient as low-level languages Need to be translated
Programming Paradigms
Why are there hundreds of programming languages in use today?
Some programming languages are specifically designed for use in certain applications. Different programming languages follow different approaches to solving programming problems
A programming paradigm is an approach to solving programming problems. A programming paradigm may consist of many programming languages.
Object-Oriented Programming I
24
Advantages
Low memory utilization Relatively efficient The most common form of programming in use today.
Disadvantages
Difficulty of reasoning about programs
Difficulty of parallelization.
Tend to be relatively low level.
Object-Oriented Programming I
25
Advantages
Conceptual simplicity Models computation better Increased productivity.
Disadvantages
Can have a steep learning curve, initially Doing I/O can be cumbersome
26
Object-Oriented Programming I
Disadvantages
Difficulty of doing input-output Functional languages use more storage space than their imperative cousins
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
27
Example: Prolog
Advantages
Good support for reasoning about programs Can lead to concise solutions to problems
Disadvantages
Slow execution Limited view of the world That means the system does not know about facts that are not its predicates and rules of inference. Difficulties in understanding and debugging large programs
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
28
Object-Oriented Programming I
29
Review Questions
1. List two advantages and two disadvantages of low-level languages. 2. Explain the similarities and differences between an assembly language and a machine language. 3. Mention the programming paradigm to which each of the following languages belongs: Visual Basic, Java, C#, Haskell, Lisp, Prolog, Pascal. 4. Which programming paradigms give better support for reasoning about programs? 5. Which programming paradigms give better support for doing I/O?
Object-Oriented Programming I
30
Java Programming Language Translating High-level Languages The Java Virtual Machine Java Program Structure Exercises
Object-Oriented Programming I
31
Here are some reasons why Java is popular: 1. Simple. Compared to many modern languages, the core of the Java language is simple to master. 2. Object-oriented. Java is an object-oriented language and therefore it has all the benefits of OO languages described earlier. 3. Secure. The Java system controls what parts of your computer a program access. 4. Architecture neutral. A Java program will run identically on every platform. We will explain how Java achieves this portability later in this session. 5. Java is for Internet applications
Java was designed so that it can download programs over the Internet and execute them.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
32
A language translator is that translates a high-level language program or an assembly language program into a machine language program. There are three types of translators:
1. Assemblers. 2. Compilers. 3. Interpreters.
Object-Oriented Programming I
33
Compilers
A compiler is a program that translates a high-level language program, written in a particular high-level language, into a particular machine language.
Interpreters
An interpreter is a program that translates a high-level language program, one instruction at a time, into machine language. As each instruction is translated it is immediately executed. Interpreted programs are generally slower than compiled programs because compiled programs can be optimized to get faster execution.
Note that:
Some high-level languages are compiled while others are interpreted. There are also languages, like Java, which are first complied and then interpreted
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
34
Object-Oriented Programming I
35
Object-Oriented Programming I
36
The Java bytecode is then interpreted by the Java Virtual Machine (JVM) interpreter.
Notice that each type of computer system has its own Java interpreter that can run on that system. This is how Java achieves compatibility.
It does not matter on what computer system a Java program is compiled, provided the target computer has a Java Virtual machine.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
37
A Java program consists of essential elements called classes. The classes in a program are used to create specific things called objects.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
38
You must type this program and save it in a file named Greeting.java Java is case sensitive and has a free-form layout The words public, class, static, void, main and etc are called reserved or keyword words The meaning of the words is fixed by the language. For now, they must appear in the places shown.
Object-Oriented Programming I
39
The first line, public class Greeting, start s a new class called Greeting. Classes are a fundamental concept in java. Their role is as factories for objects. But here we are using the Greeting class as a container for our programs instructions. Java requires that all program instructions be placed inside methods and that every method must be placed inside a class.
Thus we must define methods that would contain our instructions and a class that holds the methods.
In our program, main() is our only method while Greeting is our class.
Object-Oriented Programming I
40
as a necessary part of the plumbing that is required to write a java program. The construction
public static void main (String[] args){ ...
Object-Oriented Programming I
41
Object-Oriented Programming I
43
Escape Sequences
An escape sequence is a special two-character sequence representing another character. Suppose you want to display a string containing quotation marks, such as Hello, World! you cant use System.out.println(Hello, World!); To display quotation marks in the above example, you should write: System.out.println(Hello, \World\!); Therefore, \ is an escape sequence representing quotation mark . Similarly, \n an escape sequence representing a new line or line feed character. Printing a new line starts of a new line on the display. For example the statement: System.out.println(*\n ** \n *** \n);
Object-Oriented Programming I
45
Escape Sequences
An escape sequence is a special two-character sequence representing another character. Suppose you want to display a string containing quotation marks, such as Hello, World! You shouldnt use System.out.println(Hello, World!); To display quotation marks in the above example, you should write: System.out.println(Hello, \World\!); Therefore, \ is an escape sequence representing quotation mark . Similarly, \n an escape sequence representing a new line or line feed character. Printing a new line starts of a new line on the display. For example the statement: System.out.println(*\n ** \n *** \n); prints the following * ** ***
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
46
Example 2
An agent sold a property worth N50000. If the buyer pays the agent 7% of the sale amount, find the agents commission and the total amount that the buyer must pay. The following program computes the agents commission and the total amount the buyer must pay. Study the program and try to relate it with the above java fundamentals you learned so far. What would be the output of the program?
public class Interest{ public static void main (String[] args) {
Primitive Data Types Variable declaration Numbers and Constants Arithmetic Operators Arithmetic Operator Precedence The Math Class Assignment statement Increment and Decrement operators Writing Algebraic Expressions in Java Math Functions: Examples Casting
Object-Oriented Programming I
48
double
char
8 bytes
2 bytes
1.7E308 to 1.7E308
A single character
boolean
1 byte
true or false
Variable Declaration
A variable can be declared to hold a data value of any of the primitive types. A variable is a named memory location in which a value is stored. A variable name is a sequence of letters and digits starting with a letter.
int int long long float float double double char char boolean boolean
counter; numStudents = 583; longValue; numberOfAtoms = 1237890L; gpa; batchAverage = 0.406F; e; pi = 0.314; gender; grade = B; safe; isEmpty = true;
Object-Oriented Programming I
50
One use of the modifier final is to indicate symbolic constants. By convention, symbolic constants are written in uppercase letters. Underscores separate words:
final double SPEED_OF_LIGHT = 3.0E+10; final double CM_PER_INCH = 2.54; final int MONTH_IN_YEAR = 12;
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
51
Arithmetic Operators
A simple arithmetic expression has the form: op1 Operator op2 where: Operator + * / % Description Adds op1 and op2 Subtracts op2 from op1 Multiplies op1 by op2 Divides op1 by op2 Remainder of dividing op1 by op2
Object-Oriented Programming I
52
The operators give results depending on the type of the operands. If operand1 and operand2 are integer, then the result is also integer. But if either operand1 and/or operand2 is double, then the result is double. Examples: Arithmetic expression
1 / 2
86 / 10 86 / 10.0
Value
0
8 8.6
86.0 / 10
86.0 / 10.0 86 % 10
8.6
8.6 6
Object-Oriented Programming I
53
An expression is a sequence of variables, constants, operators, and method calls that evaluates to a single value. Arithmetic expressions are evaluated according to priority rules. All binary operators are evaluated in left to right order. In the presence of parenthesis, evaluation starts from the innermost parenthesis. Operators + - (unary) * / % + - (binary) Priority (Precedence) 1 2 3 Expression 3+7%2 (2 5) * 5 / 2 25+3 Value 4 -7 0
Object-Oriented Programming I
54
Many mathematical functions and constants are included in the Math class of the Java library. Some are:
Function /constant Meaning
sqrt(x)
abs(x) cos(a), sin(a), tan(a) exp(x)
log(x)
max(x, y) , min(x, y) pow(x, y) PI
Assignment Statement
Syntax: variable = expression;
The expression on the right hand side is evaluated and the result is assigned to the variable on the left-hand side.
The left-hand side must be a variable. Examples: a b b c a = = = = + 5; a; b + 12; // valid: assignment operator , =, is not an equality operator a + b; b = c; // invalid: left side not a variable
Object-Oriented Programming I
56
Object-Oriented Programming I
57
Java provides a number of short hand assignment operators: Short-Form op1 += op2 op1 -= op2 op1 *= op2 op1 /= op2 op1 %= op2 Equivalent to op1 = op1 + op2 op1 = op1 op2 op1 = op1 * op2 op1 = op1 / op2 op1 = op1 % op2
Example: a += 5;
// equivalent to a = a + 5;
Object-Oriented Programming I
58
Increment/decrement operations are very common in programming. Java provides operators that make these operations shorter.
Operator Use Description
++ ++ ---
Example:
int y = 20; x = 10, z; y++ ; z = x + y;
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
59
All operators must be explicit especially multiplications. For a fraction, you must use parenthesis for the numerator or denominator if it has addition or subtraction.
Algebraic expression
Java expression z = (4 * x + y) / x2 2 * y
Z X Y
Object-Oriented Programming I
60
Example1
The following example computes the roots of a quadratic equation using the formula:
Algorithm:
a=1 b = -5 c=6 root1 = (-b + sqrt(b * b 4 * a * c ) ) / ( 2 * a) root2 = (-b - sqrt(b * b 4 * a * c ) ) / ( 2 * a) print root1, root2
Java code:
public class QuadraticEquation { public static void main(String[] args) { double a = 1, b = -5, c = 6; double root1 = (-b + Math.sqrt(b*b - 4*a*c))/(2*a); double root2 = (-b - Math.sqrt(b*b - 4*a*c))/(2*a); System.out.println("The roots are: "+root1 + " ,"+root2); } }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
61
Example2
Algorithm:
radius = 3 area = pi * radius2 circumference = 2 * pi * radius print area, circumference
public class Circle { public static void main(String[]args) { double area, circumference; int radius = 3; area = Math.PI * Math.pow(radius, 2); circumference = 2 * Math.PI * radius; System.out.println("Area = " + area + square cm); System.out.println("Circumference = " + circumference + cm); } }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
62
Casting
A cast is an explicit conversion of a value from its current type to another type. The syntax for a cast is: (type) expression Two of the cases in which casting is required are:
Note: The cast operator has higher priority than all arithmetic operators. 2. When a type change will result in loss of precision
int sum = 100;
int
long
float double
loss of precision
63
Algorithms
Sequential Statements Examples
Object-Oriented Programming I
64
Problem Solving
Solving a problem means that we know the way or the method to follow manually from the start till the end. Having the method known, the same method is used by the computer to solve the problem but faster and with higher precision. If we do not know how to solve a problem ourselves, the computer will not be of any help in this regard.
The strategy for solving a problem goes through the following stages: Analysis: in this stage, we should find what the problem should do. Design : the way or method of how your problem is solved is produced Implementation: the method found in design is then coded here in a given programming language. Testing: here we verify that the program written is working correctly Deployment : finally the program is ready to use
Object-Oriented Programming I
65
Object-Oriented Programming I
66
Algorithms
An algorithm is a sequence of instructions that solve a problem. An algorithm has the following properties: No ambiguity in any instruction No ambiguity which instruction is next Finite number of instructions Execution must halt
The description of the instructions can be given in English like statements called pseudo-code
The flow control of instructions has three types: Sequential Selection Iteration
Object-Oriented Programming I
67
Sequential Statements
Instructions in this type of flow control are executed one after the other in sequence These statements include: Assignment statement Method calls
Object-Oriented Programming I
68
Example1
Write a program that assigns the Cartesian coordinates of two points (x1, y1) and (x2, y2) and displays the distance between them using the following formula.
d ( x1 x2 )2 ( y1 y2 )2
Algorithm: Get a value for x1 (e.g., x1 = 1) Get a value for y1 (e.g., y1 = 1) Get a value for x2 (e.g., x2 = 4) Get a value for y2 (e.g., y2 = 6) Calculate the distance using the formula:
Object-Oriented Programming I
69
Example1 (cont'd)
Java code:
public class Distance { public static void main(String[] args) { double x1, y1, x2, y2, dist; x1 = 1.0; y1 = 1.0; x2 = 4.0; y2 = 6.0; dist = Math.sqrt(Math.pow(x2-x1,2)+ Math.pow(y2-y1,2)); System.out.println("The distance is " + dist); } }
Object-Oriented Programming I
70
Example2
Write a program that finds the area of a triangle given the length of its sides: a, b, c. Use a = 3, b = 4, c = 5 to test your solution.
area s s a s b s c abc s 2
Algorithm: Get the value of a (e.g., a = 3) Get the value of b (e.g., b = 4) Get the value of c (e.g., c = 5) Calculate s using the formula s = (a + b + c) / 2 Calculate area using the formula area = sqrt( s* (s a) * (s b) * (s c) ) print area
Object-Oriented Programming I
71
Example2 (cont'd)
Java code:
public class Distance { public static void main(String[] args) { double a, b, c, area; a = 3.0; b = 4.0; c = 5.0; s = (a + b + c ) / 2.0; area = Math.sqrt(s * (s - a) * (s b) * (s c) ); System.out.println("The area is " + area); } }
Object-Oriented Programming I
72
What is an Object?
What is a Class?
Object-Oriented Paradigm
To truly understand Java, we need to understand the paradigm on which it is built on: the Object-Oriented Paradigm (OOP). OOP is a model whereby a problem domain is modeled into objects, so that problem solving is by interaction among objects. OOP is a more natural model compared to other models since OOPs approach is exactly the way humans view problem solving. We take a closer look at the main ingredients of the model: Objects and Classes.
Object-Oriented Programming I
74
What is an Object?
An object is an individual, identifiable entity, either real or abstract, that has a well-defined boundary. An object has two main properties, namely: State: each object has attributes, whose values represent its state. Behavior, each object has a set of behavior. Example of an object: You, the student following this Lecture, are an object. Your attributes include your name, your GPA, your major, etc. You also have a set of behavior, including attending lectures, solving home works, telling someone your GPA, sleeping, etc.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
75
What is an Object?
Other examples of objects are: The instructor delivering this lecture. This room. This lecture. This University. CSC211. Your Bank Account
Try to list some of the attributes and set of behavior for each of the above objects. Also look around you and identify the objects you can see or imagine.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
76
What is a Class?
A class is a general specification of attributes and behavior for a set of objects. Each object is an instance of a class. It shares the behavior of the class, but has specific values for the attributes. Thus, a class can be viewed as an abstract specification, while an object is a concrete instance of that specification.
An example of a class is Student, an abstract entity that has attributes and a set of behavior. However, unless we have an actual student, we cannot say what the ID number is or what the major is.
77
Object-Oriented Programming I
Instructor
University Course Bank Account
Sahalu Junaidu
ABU CSC211 Ahmads Bank Account
Identify the classes for the objects you identified in the exercise on Slide#68.
Object-Oriented Programming I
78
Our main task is to design and implement classes to be used in creating objects.
Object-Oriented Programming I
79
The relationship between the reference variable, thisStudent, and the object created is shown by the following figure:
Object-Oriented Programming I
80
In the real world, problems are solved by interaction among objects. If you have a problem with your car, you take it to a mechanic for repair. Similarly, in OO programming languages, problems are solved by interactions among objects. Objects interact by sending messages among themselves.
Object-Oriented Programming I
81
Object-Oriented Programming I
Encapsulation
Having understood the main ingredients of OOP, we can now take a closer look at its main features. One of the key features is the bringing together of data and operations Encapsulation. Encapsulation, also called information hiding, allows an object to have full control of its attributes and methods. The following shows how an object encapsulates its attributes and methods.
Object-Oriented Programming I
83
Inheritance
For example, the following shows a Student class and its related subclasses:
The advantage is code-reusability. After implementing the Student class, to implement the GraduateStudent, we inherit the code of Student.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
84
We conclude this introduction to OOP by summarizing its main advantages: It allows the production of software which is easier to understand and maintain. It provides a clear mapping between objects of the problem domain (real world objects) and objects of the model. It supports code reuse and reduces redundancy. It allows "off the shelf code libraries to be reused.. It allows the production of reliable (secure) software..
Object-Oriented Programming I
85
What is a String?
A String is a sequence of characters enclosed in double quotes. E.g. Salaam Shabaab A is a string but A is a character String processing is a very frequent application. Thus, Java provides special support for strings. A string is an instance of Javas built in String class. Thus, strings are objects. Like any object, a string object can be created using the new operator as in: String greeting = new String(Salaam Shabaab); Java allows a String object to be created without the use of new, as in: String greeting = Salaam Shabaab;
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
87
For example, the statement: char letter = greeting.charAt(5); stores the character m in the character variable letter.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
88
Object-Oriented Programming I
89
For example, the statement: String sub2 = greeting.substring(7) creates the substring Shabaab that is referred to by sub2. For example, the statement: String sub1 = greeting.substring(0, 6); creates the substring Salaam that is referred to by sub1. What is the effect of the following statement? String sub3 = greeting.substring(8, 12);
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
90
Concatenating Strings
Concatenation means joining two or more strings together.
Java allows two strings to be concatenated using the + operator. Example: String firstName = Amr; fullName String lastName = Al-Ibrahim; String fullName = lastName+ +firstName;
Al-Ibrahim Amr
If one of the operands in an expression is a string, Java automatically converts the other to a string and concatenates them. ICS102
Example: courseCode String course = ICS; int code = 102; String courseCode = course+code; We frequently use the concatenation operator in println statements:
System.out.println(The area =+area); You need to be careful with concatenation operator. For example, what is the output of the following statement?: System.out.println(Sum =+5+6);
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
91
Comparing Strings
Strings are compared by comparing their characters left to right. Unicode codes are used in the comparison. Note that lowercase letters are different from uppercase letters. The String class has the following methods for checking whether two strings are equal: boolean equals(String another) Returns true if another is the same as this string.
Returns true if another is the same as this string, treating lower and upper case letters as the same.
The following table shows some examples of applying these methods. Assuming the following
declarations: String s1 = Salaam; String s2 = Shabaab; String s3 = SALAAM; s1.equals(s2) s1.equals(Salaam) s1.equals(s3)
false
true false
s2.compareTo(s1)
a positive number
The table below shows some examples, assuming the declaration: String greeting = Salaam Shabaab;
1
12 10 8
94
Object-Oriented Programming I
For example, the statements: String greeting = Salaam Shabaab; String greeting2 = greeting.toUpperCase(); create two string objects. The object referenced by greeting2 stores SALAAM SHABAAB
String trim()
For example, the statement: String s = Salaam .trim(); stores Salaam in the string referenced by s. Note that return \r, tab \t, new line \n and space are all white space characters. All the methods of the String class can also be applied to anonymous string objects (also called string literals) as shown in the above example.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
95
The fact that Strings are immutable makes string processing very efficient in Java.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
96
Program Example
The following shows a program that uses some String methods. It breaks a full path for a file into drive letter, path, file name and extension and prints the result in upper case.
public class BreakPath { public static void main(String[] args) { String fullPath = "c:/ics102/lectures/Example1.java"; fullPath = fullPath.toUpperCase(); char driveLetter = fullPath.charAt(0); int lastSlashIndex = fullPath.lastIndexOf('/');
Output:
}
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
97
Object-Oriented Programming I
98
Scanner
Reading Strings Numeric Input
Object-Oriented Programming I
99
char
double float int long byte boolean void
Sahalu Junaidu, Math Dept., ABU, Zaria
Character
Double Float Integer Long Byte Boolean Void
Object-Oriented Programming I
100
Long
parseLong(string)
Object-Oriented Programming I
101
int numStudents = Integer.parseInt(500); String inputLine = 3.5; double studentGPA = Double.parseDouble(inputLine); val = Integer.parseInt(str);
102
System.in stream
In Java I/O is handled by streams. An input stream is an object that takes data from an input source and delivers that data to a program. An output stream is an object that takes data from a program and delivers it to an output destination. [ e.g., System.out that corresponds to the monitor]
In Java, console input is usually accomplished by reading from the input stream System.in of the class java.lang.System
System.in represents the standard input stream (i.e., it corresponds to the keyboard).
Object-Oriented Programming I
103
Scanner Class
To be able to read characters, strings, or numbers, System.in must be wrapped in other objects.
java.util.Scanner class is used to read strings and primitive types, and must be imported into a program to be used. A Scanner object can be set up to read input from various sources, including the user typing values on the keyboard The following line creates a Scanner object that reads data typed by the user from the keyboard: Scanner input = new Scanner (System.in);
Object-Oriented Programming I
104
created, the Scanner object can be used to invoke various input methods, such as: name = input.nextLine();
The
nextLine method reads all of the input until the end of the line is
found
import java.util.Scanner; public class ReadString{ public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.println(Enter a line of text:); String message = input.nextLine(); System.out.println(You entered: + message); } }
Object-Oriented Programming I
105
}
}
Object-Oriented Programming I
106
Introduction to Classes
Motivation Class Components Instance Variables
Constructors
The Student Class Exercises
Object-Oriented Programming I
107
Object-Oriented Programming I
108
Object-Oriented Programming I
109
Class Components
A class has following elements: Identity Attributes
Methods
Graphical Representation of a class (UML diagram): Identity Attributes Methods Example:
Student
studentID name gpa getName changeGPA getID
Object-Oriented Programming I
110
Class Identity
Class naming convention: Noun or Noun phrase First letter of each word capitalized. No underscores. Examples: Tree, DatePalm, Student, GraduateStudent, BankAccount, InputStreamReader Syntax: modifier class ClassName{ attributes methods } classes are unique
Class Attributes
Attributes are the distinctive characteristic, quality, or feature that contribute to make objects of a class unique.
Syntax:
accessModifier type attributeName; accessModifier type attributeName = initialValue;
Example:
private int id; private double gpa;
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
113
Methods
Methods are the actions that an object performs. Through methods objects interact and pass messages to other objects.
The behavior of an object depends on its attribute values and the operations performed upon it.
Object-Oriented Programming I
114
Method naming convention: Verb or verb phrase Starts with small letter and each phrase's first letter capitalized
getName
changeGPA
GetName
studentInformation
registerCourse
playfootball
Syntax: modifier returnType methodName(parameterType parameter,...){ statements return expression; } Example: public double calculateAverage(int value1, int value2){ double average = (value1 + value2) / 2.0; return average; }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
115
Instance Variables
State of an object: the set of values that describe the object. Each object stores its state in one or more instance variables. private double gpa ; Scope of an Instance variable: the part of the program in which you can access the variable. In Java, the scope of a variable is the block in which that variable is declared. Private instance variables can be accessed directly only in the methods of the same class. We can gain access to private instance variables through public methods in that class. Each object of a class has its own copy of an instance variable.
Object-Oriented Programming I
116
Constructors
In addition to instance variables and methods, a class may have one or more constructors. Constructors are used to initialize the instance variables of an object at the time of creating the object. What is the difference between a constructor and a method? A constructor:
Note: Two or more classes may be placed in a single Java file. In that case:
Only one class can be public; namely the class containing the main method.
The name of the Java file must be that of the public class.
Object-Oriented Programming I
119
Exercises
What is the difference between a constructor and a method? What are constructors used for? How are they defined? Think about representing an alarm clock as a software object. Then list some characteristics of this object in terms of states and behavior. Draw the class in UML diagram. Repeat the previous question for a Toaster Object.
Object-Oriented Programming I
120
Introduction to Classes II
Car Example
Exercises
Object-Oriented Programming I
121
Default Constructor
Question: What happens if a constructor is not defined in a class? Answer: A default constructor is created automatically. A default constructor:
Has no parameter Initializes instance variables with default values Is not provided if a constructor is already defined class Student{
private int id; private String name; private double gpa; // no constructor defined public String getName(){ return name; } }
Sahalu Junaidu, Math Dept., ABU, Zaria
short
int long float
(short) 0
0 0L 0F
double
char object reference
0D
\u0000 null
Object-Oriented Programming I
122
Overloading Constructors
class Student{
Java allows more than one Constructor Problem: All constructors will have the same name! Solution: Overloading Each constructor will have different parameters
// . . .
}
Object-Oriented Programming I
123
this Keyword
class Student{
Reference to the current object Two usages of this keyword: 1. To refer to the fields and methods of this object Purpose: resolve conflict in naming. From a constructor of a lass call another constructor of the same class.
2.
// . . .
}
Object-Oriented Programming I
124
Knowing these information items, the consumption (in km per liters) = (finalOdometerReading - initialOdometerReading)/litersUsed
Object-Oriented Programming I
125
Object-Oriented Programming I
127
Exercises
1. Add a boolean method called isEconomyCar to the Car class. This method will return true if the fuel consumption is less that 5 kilometers per liter.
2.
3.
This method will return true if the fuel consumption is more that 15 KM/Liter
4. Implement a class Product. A product has a name and a price. Supply methods printProduct( ) , getPrice( ) , and setPrice().
5. Write a test program that makes two products, prints them, reduces their prices by 5 Naira, and then prints them again.
6. Implement a class Circle that has methods getArea ( ) and getCircumference (). In the constructor, supply the radius of the circle.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
128
Selection
Object-Oriented Programming I
129
Outline
Relational Operators Boolean Operators Truth Tables Precedence Table Selection and Algorithms The if -else statement Variations of if-else statement The switch statement
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
130
Relational Operators
In addition to arithmetic operators which produce numeric results, relational operators are used in comparisons. Operator
==
!= > >= < <=
Meaning
equal
not equal greater than greater than or equal less than less than or equal
Boolean Operators
Connecting relational expressions requires another set of operators called boolean operators:
Operator && || !
Examples:
Truth Tables
true
true
false false
false
true false q true false true false
false
false false p||q true true true false
133
Object-Oriented Programming I
Precedence Table
Operator Type Code
postfix unary
expr++
expr--expr !
Highest precedence
creation or cast
Multiplicative Additive relational equality Logical AND
new
* + < == && / >
(type)expr
% <= >=
!=
Logical OR
assignment
||
= += -= *= /= %=
Lowest precedence
Object-Oriented Programming I
134
Statements
Statements can be simple or compound. A number of statements can be grouped together to form one compound statement by enclosing these statements in curly brackets { }
Object-Oriented Programming I
135
We have seen that flow control is divided into three types: Sequential Selection Iteration In Selection, we select one alternative based on a criterion (condition)
Object-Oriented Programming I
136
Assume that we want to find the status of a student given his GPA. Algorithm: Get GPA if GPA >= 2 status = good standing else status=under probation
Object-Oriented Programming I
137
The condition is evaluated first; statement1 is executed if result is true otherwise statement2 is executed.
true condition false
statement1
statement2
Object-Oriented Programming I
138
Example
public String getStatus( ) { String status; if(gpa >= 2) status = good standing; else status = under probation; return status; }
Object-Oriented Programming I
139
statement
false
true
condition1
false true
condition2
false true
condition3
. . .
statementM
true
false
conditionM
false
statementN
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
141
switch(controllingExpression) { case value1 : Statements; break; case value2 : Statements; break; ... default : Statements; }
A case label value must be a unique constant value or a constant expression of type byte, char, short, or int.
The statements of the case label that equals the value of the controllingExpression are executed; otherwise if there is no matching case label, the statements of the default label, if present, are executed.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
143
Example
import java.io.*; class DayOfWeek2 { public static void main(String[] args) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter a number [1 .. 7]: "); String input=stdin.readLine(); int dayNumber=Integer.parseInt(input); switch(dayNumber){ case 1: System.out.println("Saturday"); break; case 2: System.out.println("Sunday"); break; case 3: System.out.println("Monday"); break; case 4: System.out.println("Tuesday"); break; case 5: System.out.println("Wednesday"); break; case 6: System.out.println("Thursday"); break; case 7: System.out.println("Friday"); break; default: System.out.println("Wrong input"); } }}
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
144
// . . . System.out.println(Enter a character: ); char ch = (stdin.readLine()).charAt(0); if(! Character.isLetter(ch)) System.out.println(ch + IS NOT A LETTER); else{ switch(ch){ case a: case A: case e: case E: case i: case I: case o: case O: case u: case U: System.out.println(ch + IS A VOWEL); break; default: System.out.println(ch + IS A CONSONANT); } } // . . .
Note: Character is a wrapper class for the primitive type char. It contains several methods to process characters. It is defined in java.lang package
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
145
Outline
Object-Oriented Programming I
146
In the third control, a statement/statements will be executed repeatedly, a number of times, based on a criterion (condition)
Object-Oriented Programming I
147
Algorithm
sum = 0 index = 1 while index <= n
sum = sum + index index = index + 1
Object-Oriented Programming I
148
statement
Object-Oriented Programming I
149
Example
public static int sum1toN(int n){ int sum = 0, index = 1; while ( index <= n ) { sum += index; index++; } return sum; } Notes: when using the while loop notice the following: use braces if more than one statement to be repeated initialize the variable used in the condition before the loop update the variable inside the loop
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
150
condition
false
true statement
update
Evaluate condition again, if it was true in the previous case, and continue as in the step above
151
Object-Oriented Programming I
Example
public static int sum1toN(int n){ int sum = 0, index = 1; for ( index = 1; index <= n; index++) sum += index; return sum; }
Object-Oriented Programming I
152
true
condition
false
Object-Oriented Programming I
153
Example
public static int sum1toN(int n){ int sum = 0, index = 1; do { sum += index; index++; }while ( index <= n ); return sum; }
Object-Oriented Programming I
154
Nested Loops
Loops can be nested and will be executed such that for every iteration of the outer loop, all the iterations of the inner loop. The inner loop must be completely inside the outer loop. Loop indexes must be different.
Object-Oriented Programming I
155
Example
public static void multiplicationTable(int n){ int row, col; for (row = 1; row <= n; row++) { for (col =1; col <= n; col++) System.out.print(row*col + \t); System.out.println( ); } }
Object-Oriented Programming I
156
Introduction to Methods
Method Calls
Parameters
Return Type Method Overloading Accessor & Mutator Methods Student Class: Revisited
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
157
Method Calls
The set of methods defined for an object determines the behavior of that object. For example, for an object of Student class; methods: getID, setGPA, and getName will make the behavior of this object known to us.
After creating an object from a class, a series of methods are called to accomplish some tasks.
The following code creates a Student object, then it increments the GPA of this student by 0.1: Student s = new Student(243, Husam , 3.1); double gpa = s.getGPA(); s.setGPA(gpa + 0.1) ;
Object-Oriented Programming I
158
Object-Oriented Programming I
159
Parameters
//main method Student adel = new Student(987623," Adel", 1.9); double increment = 0.1; adel.setGPA(adel.getGPA()+ increment);
Actual parameter: Constant, variable or expression in method call. Example: 2.0 and adel (implicit actual parameter).
//method in Student Class public void setGPA(double gpa){ this.gpa = gpa; }
Formal parameter: Variable in the method definition Example: grade and this (implicit formal parameter).
Object-Oriented Programming I
160
Self-check Exercise
What is the difference between actual parameters and formal parameters? What are the problems in the following two program segments of method headers and method calls? // method call double a = 1.5; int b = 4; objectReference.methodA(a, // method header public void methodA(int n, // method call double a = 1.5; int b = 4, c = 2; objectReference.methodB(a, // method header public void methodB(double
b, c);
x,int n) {.....}
Return Type
The return type indicates the type of value the method returns a primitive type or object reference. If no value or reference is returned by a method, the return type is specified as void. public double getGPA(){ return gpa; } public void setGPA(double newGPA){ gpa = newGPA; } A Java method cannot return more than one value.
Object-Oriented Programming I
162
Method Overloading
Methods can be overloaded. Overloaded methods:
Two or more methods of the same class with the same name but different signatures. The return type of a method is not counted as part of its signature .
Formal parameters of overloaded constructors and methods must NOT have the same type, order, and count. Example: Valid overloading:
public public public double double double compute(int num, int num2){. . compute(int num, double num2){. compute(int num) {. . .} .} . .}
Object-Oriented Programming I
163
Accessor Methods
Encapsulation: Data + Methods to operate on the data. Only methods of the same class can directly access its private instance variables. A public method that returns the private value of an instance variable of an object is called an accessor method. public class Student{ private int id; private String name; private double; public String getName(){ return name; } public int getID(){ return id; } public double getGPA(){ return gpa; } }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
164
Mutator Methods
A method that changes the value of some instance variable is called a mutator method. public class Student{ private int id; private String name; private double gpa; // . . . public void setGPA(double newGPA){ gpa = newGPA; } // . . . }
Classes that do not have any mutator methods are called immutable classes. (Example: String class).
Object-Oriented Programming I
165
Student class
public class Student{ private int id; private String name; private double gpa; public Student(int id String name, double gpa){ this.id = id; this.name = name; this.gpa = gpa; } public Student(int id, String name){ this(id, name, 0.0); } }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
166
public String getName(){ return name; } public int getID(){ return id; } public double getGPA(){ return gpa; } public void setGPA(double newGPA){ gpa = newGPA; }
Exercises
Write a test program for the Student class. Create two students. Test all accessor and mutator methods.
Add another constructor to the Student class such that it will take only the name as argument. The ID will be set to 000 and GPA to 0.0
Add a method called evaluate(gpa). This method will return strings "honor". "good standing" or "under probation" according to the value of gpa.
Object-Oriented Programming I
167
Introduction to Methods
Type of Variables Static variables Static & Instance Methods The toString equals methods Memory Model Parameter Passing
Object-Oriented Programming I
168
Types of Variables
There are four types of variables in Java:
variable
instance variable
declaration
Outside all methods, not proceeded by keyword static
scope
Throughout the class definition
life-time
Throughout the object life
comment
Property of each object
Outside all methods, proceeded by keyword static. Example: public static int numberOfCircles;
Within a method body In a method or constructor header
Property of the class. All objects of this class share one copy of the variable.
Property of each object Property of each object
formal parameter
public void setRadius(double newRadius){ radius = newRadius; } public double getArea(){
local variable
} } Sahalu Junaidu, Math Dept., ABU, Zaria
Object-Oriented Programming I
170
How to call?
When to use?
Implement a task that is not specifically related to an object or that does not need an object.
Object-Oriented Programming I
171
Object-Oriented Programming I
172
Example
class Circle{ private static int numberOfCircles; private double radius; public Circle(double theRadius){ radius = theRadius; numberOfCircles++; } public class StaticTest{ public static void main(String[] args){ System.out.println(Circle.getCount()); Circle circle1 = new Circle(4.0); Circle circle2 = new Circle(2.5); System.out.println(circle2.getCount()); circle1 = null; /* Request the garbage collector to perform a garbage-collection pass */ System.gc(); System.out.println(Circle.getCount()); } }
Output: 0 2 1
Object-Oriented Programming I
173
toString Method
Prints the content of an object. It is recommended to add toString() method when designing a new class. When toString() is provided it is automatically invoked when object name is used where string is expected (print, concatenation) When toString() is NOT provided, toString() of standard Object class is used, with the following format: ClassName@memoryLocation Example:
class Student{ private int id; private String name; private double gpa; // . . . public String toString(){ return "Name: " + name } }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
174
Student student = new Student(123, Ahmad, 3.5); System.out.println(student); Output: Name: Ahmad, ID: 123, GPA: 3.5
equals Method
Compares between the contents of two objects. Operator == compares only references of two objects. It is important to provide equals method when designing a class. When this method is not provided the equals method of standard Object class is used (compares only the references) Example:
class Student{ private int id; private String name; private double gpa; public Student(int id, String name, double gpa){ this.id = id; this.name = name; this.gpa = gpa; } public boolean equals(Student student){ return this.id == student.id ; public class TestStudent{ public static void main(String[] args){ Student s = new Student(123,"Ahmed",3.2); Student x = new Student(123,"Ahmed",3.2);
Student y = new Student(456, Yusuf, 2.0);
Output:
true false false
Object-Oriented Programming I
175
} }
Sahalu Junaidu, Math Dept., ABU, Zaria
heap
Object-Oriented Programming I
176
Stack
class A{ void method1(){ method2(); } void method2(){ method3(); method4 (); } void method3(){ statements ; ) void method4() statements ; } }
Activation Record:
local variables and parameters reference to objects created by the method return address and return value of the method
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
177
Parameter Passing
Actual parameters of a method call may contain: Simple or primitive data types (int, double, etc.) Object References. In case of simple data type: The value is copied in corresponding formal parameters. Thus, changing the value in the method will not affect the original value. In case of object reference: Another reference is created which points to the same object. This other reference may be used to change the values of the object.
Object-Oriented Programming I
178
Object-Oriented Programming I
179
String Tokenization
What is String Tokenization?
Object-Oriented Programming I
180
Object-Oriented Programming I
181
Constructor
StringTokenizer(String str)
function
Creates a StringTokenizer object that uses white space characters as delimiters. Creates a StringTokenizer object that uses the characters in delimiters as separators.
Creates a StringTokenizer object that uses characters in delimiters as separators and treats separators as tokens.
Object-Oriented Programming I
182
StringTokenizer Methods
The following are the main methods of the StringTokenizer class: Method String nextToken() throws NoSuchElementException function Returns the next token as a string from this StringTokenizer object. Throws an exception if there are no more tokens. Returns the count of tokens in this StringTokenizer object that are not yet processed by nextToken() -- initially all. Returns true if there are more tokens not yet processed by nextToken().
int
countTokens()
boolean
hasMoreTokens()
Object-Oriented Programming I
183
int tokenCount = tokenizer.countTokens(); for(int k = 1; k <= tokenCount; k++){ String token = tokenizer.nextToken(); // process token }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
184
Example 1
The following program reads grades from the keyboard and finds the average. The grades are read in one line. import java.util.Scanner; import java.util.StringTokenizer; public class TokenizerExamplel{ public static void main(String[] args)throws IOException{ Scanner input = new Scanner(System.in); System.out.print("Enter grades in one line:"); String inputLine = input.nextLine(); StringTokenizer tokenizer = new StringTokenizer(inputLine); int count = tokenizer.countTokens(); double sum = 0; while(tokenizer.hasMoreTokens()) sum += Double.parseDouble(tokenizer.nextToken()); System.out.println("\nThe average = "+ sum / count); } }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
185
Example 2
This example shows how to use the second constructor of StringTokenizer class. It tokenizes the words in a string, such that the punctuation characters following the words are not appended to the resulting tokens. import java.util.StringTokenizer; public class TokenizerExample2{ public static void main(String[] args){ String inputLine = "Hi there, do you like Java? I do;very much."; StringTokenizer tokenizer = new StringTokenizer (inputLine, ",.?;:! \t\r\n"); while(tokenizer.hasMoreTokens()) System.out.println(tokenizer.nextToken()); } }
Object-Oriented Programming I
186
Example 3
This example shows how to use the third constructor of StringTokenizer class. It tokenizes an arithmetic expression based on the operators and returns both the operands and the operators as tokens.
import java.util.StringTokenizer; public class TokenizerExample3{ public static void main(String[] args){ String inputLine = "(2+5)/(10-1)"; StringTokenizer tokenizer = new StringTokenizer(inputLine,+*/()",true); while(tokenizer.hasMoreTokens()) System.out.println(tokenizer.nextToken()); } }
Output: ( 2 + 5 ) / 10 1 )
187
Object-Oriented Programming I
Exception Handling
Introduction to Exceptions How exceptions are generated A partial hierarchy of Java exceptions Checked and Unchecked Exceptions
Unreachable catch-blocks
The semantics of the try statement Recovering from Exceptions
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
188
Introduction to Exceptions
A program may have one or more of three types of errors: Syntax errors or Compile-time errors. Run-time or Execution-time errors. Logic errors. A Java exception is an object that describes a run-time error condition that has occurred in a piece of Java code or in the Java run-time System. All Java exception classes are subclasses of the Throwable class. Most exception classes are defined in the java.io and java.lang packages. Other packages like: java.util, java.awt, java.net, java.text also define exception classes. A piece of Java code containing statements to handle an exception is said to catch the exception; otherwise it is said to throw that exception.
Object-Oriented Programming I
189
if(withdrawAmount < 0) throw new InvalidArgumentException(Error Negative withdraw amount); else balance -= withdrawAmount;
Object-Oriented Programming I
190
Object-Oriented Programming I
191
Object-Oriented Programming I
192
A method that does not handle checked exceptions it may generate, must declare those exceptions in a throws clause; otherwise a compile-time error occurs.
A method may or may not declare, in a throws clause, unchecked exceptions it may generate but does not handle.
Syntax of a throws clause:
accessSpecifier returnType methodName(parameters)throws ExceptionType1, ExceptionType2, ..., ExceptionTypeN { // method body }
Note: When a method declares that it throws an exception, then it can throw an exception of that class or any of its subclasses.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
193
Statement will generate ArithmeticException if num3 is zero. The method may or may not contain a throws ArithmeticException clause
Object-Oriented Programming I
194
Object-Oriented Programming I
195
try-catch blocks have the form: try{ statementList } catch(ExceptionClass1 variable1){ statementList } catch(ExceptionClass2 variable2){ statementlist } . . . catch(ExceptionClassN variableN){ statementlist } A statement or statements that may throw exceptions are placed in the try-block. A catch-block defines how a particular kind of exception is handled.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
196
Unreachable catch-blocks
A catch-block will catch exceptions of its exception class together with any of its subclasses.
Example: Since ArithmeticException is a subclass of Exception, the following code will cause compile-time error because of unreachable code:
try{ int a = 0; int b = 42 / a; } catch(Exception e){ System.out.println(e); } catch(ArithmeticException e){ System.out.println(There is an arithmetic exception); }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
197
1. No exception is generated:
All the statements in the try block are executed . No catch block is executed. Processing continues with the statement following all the catch blocks for the try block.
Object-Oriented Programming I
200
Object-Oriented Programming I
201
I/O streams
Files can be classified into two major categories: Binary files and Text files. A binary file is a file whose contents must be handled as a sequence of binary digits. A text file is a file whose contents are to be handled as a sequence of characters.
Why use files for I/O? Files provide permanent storage of data. Files provide a convenient way to deal with large quantities of data. Recall that in In Java, I/O is handled by objects called streams.
The standard streams are System.in, System.out, and System.err.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
202
Where filename is a File object or a constant string or a String variable containing the name or the full path of the file to be read. o Example of valid filenames: myinput.txt, C:\\homework\\StudentTest.java, C:/homework/StudentTest.java
File class belong to the java.io package, it must be imported for it to be used.
Object-Oriented Programming I
203
Closing a Stream
When a program has finished writing to or reading from a file, it should close the stream connected to that file by calling the close method of the stream: streamName.close(); Eg. input.close(); The close method is defined as: public void close() When a stream is closed, the system releases any resources used to connect the stream to a file.
If a program does not close a stream before the program terminates, then the system will
automatically close that stream.
Object-Oriented Programming I
204
The nextLine method reads a line of input from the file and returns that line as a string.
Object-Oriented Programming I
205
}catch(FileNotFoundException e){
System.out.println("Error - File myinput.txt not found"); System.exit(1); }
while(inputLine = inputStream.hasNext()){ tokenizer = new StringTokenizer(inputLine); id = tokenizer.nextToken(); count = tokenizer.countTokens(); sum = 0.0; while(tokenizer.hasMoreTokens()) sum += Double.parseDouble(tokenizer.nextToken( )); System.out.println(id + " } }} Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
207
+ sum / count);
Object-Oriented Programming I
208
Object-Oriented Programming I
209
PrintWriter
outputStream =
outputStream.println(message);
outputStream.close(); } }
Object-Oriented Programming I
210
Object-Oriented Programming I
One-Dimensional Arrays
What are and Why 1-D arrays? 1-D Array Declaration Accessing elements of a 1-D Array Initializer List
Object-Oriented Programming I
213
Object-Oriented Programming I
214
for the second scan --inconvenient double grade, average, sum = 0; for(int i = 1; i <= 30; i++){ grade = Double.parseDouble(stdin.readLine()); sum += grade; } average = sum / 30; int count = 0; for(int i = 1; i <= 30; i++){ grade = Double.parseDouble(stdin.readLine()); if(grade > average) count++; } Is there a better approach? - Yes, this is what 1-D arrays are for. An array is a contiguous collection of variables of the same type, referenced using a single variable. The type is called the "base type" of the array.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
215
For any type T, T[ ] is a class, whose instances are arrays of type T. Thus, the following statement declares a reference variable, b, of type T array: T[] b; For any positive integer n, the following expression creates a new T[ ] object of size n and stores its reference in b: b = new T[n] ; As usual, the two expressions can be combined together as: T[] b = new T[n] ; For example, the following declares an int[] , grades, of size 10: int[] grades = new int[10];
Object-Oriented Programming I
216
The declaration of an array of size n creates n variables of base type. These variables are indexed starting from 0 to n-1. Each array object has a public instance variable, length, that stores the size of the array. Thus, the following statement prints 10, the size of grades: System.out.println(grades.length); Other examples of 1D-array declaration are: double[] price = new double[500]; boolean[] flag = new boolean[20];
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
217
The following example, initializes each variable with twice its index: int[] grades = new int[10]; for(int i = 0; i < grades.length; i++) grades[i] = 2*i;
0 2 4 6 8 10 14 16 18
Note: Trying to access an element with an invalid index causes a run-time error: ArrayIndexOutOfBoundsException: int x = grades[10]; // run-time error
219
Object-Oriented Programming I
Initializer List
Initializer list can be used to instantiate and initialize an array in one step:
int[] prime = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
char[]
letterGrade
{A,
B,
C,
D,
F};
It is actually the compiler that fills the gap. Thus, in the first example, the compiler would add the following:
int[] prime = prime[0] = 2; new int[10]; prime[1] = 3; ... prime[9] = 29;
Observe that when an initializer list is used: The new operator is not required. The size is not required; it is computed by the compiler.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
220
public static void doubleArray(int[] a){ for(int i = 0; i < a.length; i++) a[i] = a[i] * 2; }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
221
}
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
223
Object-Oriented Programming I
224
Array of Objects
So far, our examples have been on arrays of primitive types. We can equally create arrays whose elements are objects. We can create an array to store 10 Student objects as follows: Student[] student = new Student[10]; However, only the references to the Student objects are stored. The figure shows the array after adding two Student objects. student[0] = new Student(993546, "Suhaim Adil", 3.5); student[1] = new Student(996789, "Jan Usam", 3.9);
student reference
2
null
3
null
4
null
5
null
6
null
7
null
8
null
9
null
Object-Oriented Programming I
226
Dynamic Arrays
Why Dynamic Arrays? A Dynamic Array Implementation The Vector Class
Program Example
Array Versus Vector
Object-Oriented Programming I
229
Object-Oriented Programming I
We can create an instance of our DynamicArray class as follows: DynamicArray c = new DynamicArray(20);
c can be viewed as an int array of size 20. However, c can store more than 20 integers. How we access and modify content of c is also slightly different:
1. 2. 3. Corresponding to: b[i] , we use a function call: c.getElement(i) Corresponding to: b[i]=value; , we use a function call: c.set(i,value); Corresponding to: b.length , we use a function call: c.capacity()
Object-Oriented Programming I
233
Vector(int initialCapacity)
Adding an Element
The base type of our DynamicArray is int What about Vector? The base type of Vector is Object. Thus, primitive types must be wrapped using wrapper classes. Elements can be added using the following add method: add(Object element) Adds element to the next empty cell, increases the capacity if necessary.
The following adds 10 objects into a vector of initial capacity 4: Vector v = new Vector(4); for(int i = 0; i < 10; i++) v.add(new Integer(i*2)); The capacity is automatically increased to take the 10 objects
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
235
Adds element at index, shifts element at index and beyond, if any, by 1. Increases capacity if necessary. If index < 0 or index > size, it throws IndexOutOfBoundsException.
The following adds 6 objects into a vector, it then inserts an Integer object with value of 20 at index 3:
Vector v = new Vector(4); for(int i = 0; i < 6; i++) v.add(new Integer(i*2)); v.add(3, new Integer(20)); v
0
reference
20
10
Note that this method does not allow an empty cell in-between:
v.add(8, new Integer(100)); // Run-time error, cell 7 will be empty
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
236
Returns the element at index. throws IndexOutOfBoundsException if index < 0 or index > size.
However since the return type is object, we have to cast-down to get the original object. The following prints the result of dividing the element at index 3 with 2: Integer element = (Integer) v.get(3); System.out.println(element.intValue() / 2); To modify an element we use the set method:
Object set(int index, Object element)
Replaces the object at index with element and returns the replaced object. Throws IndexOutOfBoundsException if index < 0 or index > size.
The following replaces the element at index 3 with 100: v.set(3, new Integer(100));
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
237
If you also need to know the index of the object when found, use:
int indexOf(Object element)
int size()
size() is more useful. It is usually used in a loop to process all the vector elements
public static void main(String[] args){ Vector v = new Vector(4); System.out.println(SIZE\tCAPACITY); for(int i = 0; i < 10; i++){ v.add(new Integer(i*2)); System.out.println(v.size()+\t + v.capacity());
Output:
SIZE 1 2 3 4 5 6 7 8 CAPACITY 4 4 4 4 8 8 8 8 16 16 2 4 6 8 10 12 14 16 18 239
}
for(int i = 0; i < v.size(); i++) System.out.println(v.get(I) + } Sahalu Junaidu, Math Dept., ABU, Zaria );
9 10 0
Object-Oriented Programming I
Removing an Element
An element can be removed from a vector using any of the following methods:
boolean remove(Object element) Object remove(int index)
Removes element from the vector and returns true if successful; returns false if element is not found. The elements after the removed element are shifted to the left Removes element at index and returns it; throws IndexOutOfBoundsException if index < 0 or index > size. The elements after the removed element are shifted to the left
The following removes 100 from a vector v and prints a message if successful:
if(v.remove(new Integer(100)) System.out.println(100 removed); else System.out.println(100 not found);
Does the capacity of a vector shrink automatically after a deletion?: No. However, we can use the following method to shrink it:
void trimToSize()
Sahalu Junaidu, Math Dept., ABU, Zaria
Program Example
The following example reads an unknown number of grades, it then prints the average and the grades above the average: public static void main(String[] args)throws IOException{ Vector grade = new Vector(); readGrades(grade); double average = getAverage(grade); System.out.print(The average grade is: + average); System.out.print(Grades above average are: ); printAboveAverage(grade, average); } public static void readGrades(Vector v)throws IOException{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.print(Enter grade: ); double value = Double.parseDouble(stdin.readLine()); while(value >= 0){ v.add(new Double(value));
System.out.print(Enter next grade(negative value to terminate): );
value = Double.parseDouble(stdin.readLine()); } }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
241
Object-Oriented Programming I
242
Object-Oriented Programming I
243
Multi-Dimensional Arrays
Why do we Need 2-D arrays? 2-D Array Declaration Referencing Elements of a 2-D Array What is the Meaning of length in a 2-D array? 2-D Array Initializers Processing 2-D arrays
Object-Oriented Programming I
244
Object-Oriented Programming I
247
Suppose a matrix is declared as a 2D-array as: int[][] matrix = new int[3][4]; Then matrix.length returns the number of rows in matrix; 3 in this case. We can use this number to process a particular column:
int sumColumn0 = 0; for(int rowIndex = 0; rowIndex < matrix.length; rowIndex++) sumColumn0 = somColumn0 + matrix[rowIndex][0];
To manipulate a particular row n, We use the expression: matrix[n].length to obtain its length:
int sumRow2 = 0;
for(int columnIndex = 0; columnIndex < matrix[2].length; columnIndex++)
2D-Array Initializers
We can declare and initialize a 2D-array in one statement as follows:
int[][] matrix = {{5, 3, 6}, {1, 2, 3}};
Object-Oriented Programming I
249
The following method takes two matrices of equal dimensions and return their sum.
public int[][] sum2Darray(int[][] a, int[][] b){ int[][] matrix = new int[a.length][a[0].length]; for(int rowIndex = 0; rowIndex < matrix.length; rowIndex++)
for(int columnIndex = 0; columnIndex < matrix[rowIndex].length; columnIndex++)
matrix[rowIndex][columnIndex] = a[rowIndex][columnIndex]+ b[rowIndex][columnIndex] ;
return matrix; }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
251
Then the following method takes a 2D Student array representing a multi-section course and returns the overall average:
public double overallAverage(Student[][] student){
double sum = 0; int numberOfStudents = 0; for(int section = 0; section < student.length; section++) for(int count = 0; count < student[section].length; count++){ sum = sum + student[section][count].getGrade() ; numberOfStudents++; } return sum / numberOfStudents; }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
252
Although this is natural, in Java a 2D-array is actually a 1D-array whose elements are references to
1D-array objects.
Here is the actual representation:
Object-Oriented Programming I
253
2. The creation of a 1D-array whose elements are references to 1D-arrays: matrix = new int[3][];
Object-Oriented Programming I
254
Ragged Arrays
Since each column of a 2-D array is actually a separate 1D-array, each column may have a different length. For example, we could have the following: int[][] matrix = new int[3][]; matrix[0] = new int[4]; matrix[1] = new int[2]; matrix[2] = new int[3];
This type of 2D-array where the columns are not of the same size is called a ragged array. Ragged arrays can be used to save memory space in some programming situations.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
255
The following method returns a ragged array representing Pascals triangle of n rows:
public static int[][] pascalTriangle(int n){ int[][] b = new int[n][]; for(int i = 0; i < n; i++){ // Create row I of Pascals triangle b[i] = new int[i+1]; b[i][0] = 1; for(int k = 1; k < i; k++) b[i][k] = b[i - 1][k - 1] + b[i - 1][k]; b[i][i] = 1; } return b; }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
256
Introduction to Inheritance
Final Classes
Class Hierarchy Subclass Constructors Example Exercises
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
257
What is Inheritance?
Inheritance is a mechanism for enhancing existing, working classes. A new class can inherit from a more general existing class.
For Class Child: Attributes: Inherited: a , b not inherited: c Methods: Inherited: op1( ) , op2( ) not inherited: op3( )
Child c op3( )
Note: Constructors and private members of a class are not inherited by its subclasses. Java supports single inheritance: A subclass has one parent only. In multiple inheritance a subclass can have more than one parent.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
258
Student
GraduateStudent
ShortCourse
OnLineCourse
defendThesis( )
produceCertificate( )
deliverLecture( )
Object-Oriented Programming I
259
isA relationship
A subclass-superclass pair defines isA relationship: A graduate student is a student. A short course is a course. An online course is a course. A graduate student is a student. Course
Student
GraduateStudent
ShortCourse
OnLineCourse
defendThesis( )
produceCertificate( )
deliverLecture( )
Object-Oriented Programming I
260
Why Inheritance?
Through inheritance we gain software reuse. Helps in writing structured programs. It is more natural and closer to real world.
Object-Oriented Programming I
261
Subclass Syntax
class SubclassName extends SuperclassName { variables
methods
} Example: class GraduateStudent extends Student { String thesisTitle; . . .
defendThesis(){. . .}
. . . }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
262
Final Classes
A class that is declared as final cannot be extended or subclassed.
final class className
{
variables methods }
Examples of final classes are: java.lang.System. The primitive type wrapper classes: Byte, Character, Short, Integer, Long, Float, and Double.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
263
Class Hierarchy
In Java, every class that does not extend another class is a subclass of the Object class. that is defined in the java.lang package. Thus, classes in Java form a hierarchy, with the Object class as the root. Example of a class hierarchy:
Object-Oriented Programming I
264
Subclass Constructors
To initialize instance variables of a superclass, a subclass constructor invokes a constructor of its superclass by a call of the form: super(paraneters); This statement must be the first statement within the constructor of the subclass. Example:
public GraduateStudent(int id, String name, double gpa, String thesisTitle){ super(id, name, gpa); this.thesisTitle = thesisTitle; }
If the first statement in a constructor does not explicitly invoke another constructor with this or super; Java implicitly inserts the call: super( );. If the superclass does no have a no-argument constructor, this implicit invocation causes compilation error.
Constructor calls are chained; any time an object is created, a sequence of constructors is invoked; from subclass to superclass on up to the Object class at the root of the class hierarchy.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
265
Example
class Vehicle{ private String vehicleIdNumber ; private String vehicleChassisNumber ; private String model ; public Vehicle(String vin, String vcn, String model){ vehicleIdNumber = vin; vehicleChassisNumber = vcn; this.model = model; } public String toString( ){ return "Vehicle ID = " + vehicleIdNumber + "\nVehicle Chassis Number = " + vehicleChassisNumber + "\nVehicle Model = " + model; } public boolean equals(Vehicle vehicle){ return this.vehicleChassisNumber == vehicle.vehicleChassisNumber; } } class Bus extends Vehicle{ private int numberOfPassengers ;
public Bus(int numPassengers, String vin, String vcn, String model){
super(vin, vcn, model) ; numberOfPassengers = numPassengers ; } public int getNumberOfPassengers( ){ return numberOfPassengers ; } }
Object-Oriented Programming I
266
Example (contd)
class Truck extends Vehicle{ private double cargoWeightLimit ;
public Truck(double weightLimit, String vin, String vcn, String model){
super(vin, vcn, model) ; cargoWeightLimit = weightLimit ; } public double getCargoWeightLimit( ){ return cargoWeightLimit ; } }
public class VehicleTest{ public static void main(String[] args){ Vehicle vehicle = new Vehicle ("QMY 489", "MX-0054322-KJ", "BMW 500"); Bus bus1 = new Bus(30, "TMK 321", "AF-987654-WR", "MERCEDEZ BENZ"); Bus bus2 = new Bus(30, "2348976", "AF-987654-WR", "MERCEDEZ BENZ"); Truck truck = new Truck(10.0, "DBS 750", "RZ-70002345-PN", "ISUZU"); System.out.println(vehicle) ; System.out.println(bus1) ; System.out.println(truck) ; if(bus1.equals(bus2)) System.out.println("Bus1 and Bus2 are the same") ; else System.out.println("Bus1 and Bus2 are not the same") ; } }
Object-Oriented Programming I
267
Exercises
Question 1: What inheritance relationships would you establish among the following classes: Student, Professor, Teaching Assistant, Employee, Secretary, DepartmentChairman, Janitor, Person, Course, Seminar, Lecture, ComputerLab Question 2: In the following pairs of classes, identify the superclass and the subclass: Manager -Employee, Polygon -Triangle, Person - Student, Vehicle - Car, Computer-Laptop, Orange - Fruit.
Object-Oriented Programming I
268
Introduction to Inheritance
Access Modifiers Methods in Subclasses Method Overriding Converting Class Types Why up-cast? Why Down-cast? Exercises
Object-Oriented Programming I
269
Access Modifiers
Access Modifier
private protected
Methods of their own class. Methods of subclasses and other classes in the same package. Methods of subclasses in different packages.
Methods of their own class. Methods of subclasses and other classes in the same package.
Object-Oriented Programming I
270
Methods in Subclasses
A method in a subclass can be: A new method defined by the subclass. A method inherited from a superclass. A method that redefines (i.e., overrides) a superclass method.
public class GraduateStudent extends Student{
New method
Overridden method
}
Method Overriding
A subclass overrides a method it inherits from its superclass if it defines a method with
the same name, same return type, and same parameters as the supercalss method. Each of the following causes compilation error: The overriding method has a weaker access privilege than the method it is overriding.
The overriding method has the same signature but different return type to the method
it is overriding. A method declared as final, final returnType methodName( . . .) , cannot be overridden. A subclass can access an overridden method can by a call of the form:
super.methodName(parameters) ;
Note: We have already come across examples of method overriding when we discussed the
redefinition of the toString and the equals methods in the previous lectures.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
272
A narrowing conversion (down casting) requires a class cast; otherwise a compile time error occurs:
Object object = new Object(); String string = object ; // Compile time error
Object-Oriented Programming I
275
Object-Oriented Programming I
Why Up-cast?
One use of up-casting is to write methods that are general. Example:
class Vehicle{ private String vehicleIdNumber ; private String vehicleChassisNumber ; private String model ; // . . . public boolean equals(Vehicle vehicle){ return this.vehicleChassisNumber == vehicle.vehicleChassisNumber; } } class Truck extends Vehicle{ private double cargoWeightLimit ; // . . . } public class VehicleTest{ public static void main(String[] args){ // . . . boolean x = vehicle1.equals(vehicle2); boolean y = bus1.equals(bus2); boolean z = truck1.equals(truck2); // . . . }
Object-Oriented Programming I
277
Why down-cast?
Example:
public class Employee { }
compile time error. getDepartmentName( ) is not a member of Employee. Use down-casting to overcome the difficulty.
Manager m = (Manager)e; String string = m.getDepartmentName();
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
278
Exercises
1. Question 1: a) Write a class Employee with a name and salary. b) Make a class Manager inherit from Employee. Add an instance variable, named department, of type String. Supply a method toString that prints the manager's name, department, and salary. c) Make a class Executive inherit from Manager. Supply a method toString that prints the string "Executive", followed by the information stored in the Manager superclass object. d) Supply a test program that tests these classes and methods. Question 2: a) Implement a superclass Person. A person has a name and a year of birth. b) Make two classes, Student and Instructor, inherit from Person. A student has a major, and an instructor has a salary. Write the class definitions, the constructors, and the method toString for all classes. c) Supply a test program that tests these classes and methods.
2.
Object-Oriented Programming I
279
Introduction to Applets
What is an Applet? General Form of an Applet Applet initialization and termination The paint method
Colors
Fonts Executing a Java Applet
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
280
What is an Applet?
HTML (Hypertext Markup Language): A language used to define Web pages.
Web browser: A Web browser is software that retrieves HTML documents and formats them for viewing.
A browser is the primary vehicle for accessing the worldwide web. Java programs can be classified into two categories: Applications and applets: Java application: A Java program that can be run without the use of a Web browser. Applet: A Java program whose bytecode is linked into an HTML document. The bytecode is retrieved and executed using a Javacompatible Web browser or an applet viewer.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
281
import import
java.awt.*; javax.swing.*;
extends JApplet{ . . } . . . } . } . .} . .}
paint(Graphics
g ){ .
method
init()
comment
Applets do not usually have main method; instead they have the init method that, like main, is invoked by the execution environment. It is the first method called for any applet. It is called only once during the run time of an applet. called by the execution environment when an applet should start or resume execution. It is automatically called after init when an applet first begins. called to suspend execution of the applet. Once stopped, an applet is restarted when the execution environment calls start.
start()
stop()
destroy() called just before the applet is terminated. Your applet should override this method if it
The paint method is called by the execution environment each time your applets output must be redrawn. The paint method that is inherited from the class Applet is an empty method. In order for anything to be displayed on the applet window, the paint method must be overridden, in your Applet subclass, with behavior to display text, graphics, and other things. The paint method takes an object of class Graphics as an argument. This object is passed to the paint method by the execution environment. public } void . . paint(Graphics g){ .
It is the AWT that takes care of creating the Graphics object passed to paint. An object of class Graphics represents a particular drawing surface and it contains methods for drawing, font manipulation, color manipulation, etc.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
286
The Graphics class has a subclass called Graphics2D that has more functionality than the Graphics class. Since an object of class Graphics is passed to paint, to use the functionality provided by the Graphics2D class, the object must be converted to a Graphics2D object. This is done by a down-cast: public void paint(Graphics g){ Graphics2D g2 = (Graphics2D) g; . . . }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
287
Note: The drawString method does not recognize the new line character '\n'.
Example: The following applet displays the string: Hello World in default colors: black on a light gray background.
import javax.swing.*; import java.awt.*; public class HelloApplet extends JApplet{ public void paint(Graphics g){ Graphics2D g2 = (Graphics2D)g; g2.drawString("Hello world!", 50, 25); } }
The class file indicated by the CODE attribute must be in the same folder as the Web page containing
the applet, unless a CODEBASE attribute is used. CODEBASE specifies the location of the applet class file relative to the applet's HTML file. Example:
<APPLET CODE= "AppletName.class" CODEBASE="..\" WIDTH=500 HEIGHT=200> </APPLET>
It is customary, but not necessary, to give the HTML file the same name as that of the applet class inside.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
289
Colors
The class Color of java.awt package defines several static variables that hold references to various Color objects. All colors can be specified as a mix of three primary colors: red, green, and blue.
A particular color can be specified by either three integers, each between 0 and 255, or by three float
values, each between 0.0 and 1.0
Color Color.black Color.blue Color.cyan Color.gray Color.darkGray RGB Value (float) 0.0F, 0.0F, 0.0F 0.0F, 0.0F, 1.0F 0.0F, 1.0F, 1.0F 0.5F, 0.5F, 0.5F 0.25F, 0.25F, 0.25F RGB Value (integer) 0, 0, 0 0, 0, 255 0, 255, 255 128, 128, 128 64, 64, 64 Color Color.magenta Color.orange Color.pink Color.red RGB Value (float) 1.0F, 0.0F, 1.0F 1.0F, 0.8F, 0.0F 1.0F, 0.7F, 0.7F 1.0F, 0.0F, 0.0F RGB Value (integer) 255, 0, 255 255, 200, 0 255, 175, 175 255, 0, 0
Color.white
Color.yellow
Color.lightGray
Color.green
Object-Oriented Programming I
290
Colors (contd)
You can create your own color objects, using one of the following Color constructors: Color(int red, int green, int blue) Color(float red, float green, float blue) Example: import . . java.awt.Color; . c1 = new Color(255, 100, 18);
Color
Color
. .
c2
.
new
Color(0.2F,
0.6F,
0.3F);
By default, displays on the applet window are in black on a light gray background. This default can be changed by using the methods: setBackground, setForeground, setColor: void void void setBackground(Color newColor) setForeground(Color newColor)
setColor(Color newColor)
Object-Oriented Programming I
291
Colors (contd)
Although it is possible to set the background and foreground colors in the paint method, a good place to set these colors is in the init method:
import java.awt.*; import javax.swing.*; public class MyApplet extends JApplet{
Graphics2D g2 = (Graphics2D)g; g2.drawString("A yellow string", 50, 10); g2.setColor(Color.red) ; g2.drawString("A red string", 50, 50); g2.drawString("Another red string", 50, 90); g2.setColor(Color.magenta) ; g2.drawString("A magenta string", 50, 130); } }
Object-Oriented Programming I
292
Fonts
By default, strings are drawn using the default font, plain style and default font size. To change the font, style or size, we need to create an object of class java.awt.Font and pass it to the setFont method of the graphics object used in the paint method. To create such a Font object, we need to specify the following parameters: The font name The Style (Font.PLAIN, Font.BOLD, Font.ITALIC, or Font.BOLD + Font.ITALIC) The font size
The font name can be the name of any font available on the particular computer (such as: TimesRoman, Courier, Helvetica etc.,) or any of the logical names shown in the table below:
Serif A font with small segments at the end, e.g. Times New Roman
SansSerif
Monospaced Dialog DialogInput
Font (contd)
Example: The following applet displays the word Applet in large SansSerif font. import javax.swing.*; import java.awt.*; public class BigFontApplet extends JApplet{ public void paint(Graphics g){ Graphics2D g2 = (Graphics2D)g; final int SIZE = 48; Color myColor = new Color(0.25F, 0.5F, 0.75F); Font myFont = new Font("SansSerif", Font.BOLD, SIZE); g2.setColor(myColor); g2.setFont(myFont); g2.drawString("Applet",5,60); } }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
294
Font (contd)
If an applet will use several fonts, it is good to create the font objects in the init method: import javax.swing.*; import java.awt.*; public class FontExamples extends JApplet{ private Font f, fb, fi, fbi; public void init(){ setBackground(Color.yellow); f = new Font("TimesRoman", Font.PLAIN, 18); fb = new Font("Courier", Font.BOLD, 20); fi = new Font("TimesRoman", Font.ITALIC, 18); fbi = new Font("Helvetica", Font.BOLD + Font.ITALIC, 25); } public void paint(Graphics g){ Graphics2D g2 = (Graphics2D)g; g2.setColor(Color.blue); g2.setFont(f); g2.drawString("This is TimesRoman plain font", 10, 25); //... } }
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
295
When a Web page containing an APPLET tag is opened, the associated bytecode is downloaded from the location specified by the CODE or CODEBASE attribute. This location can be in the local machine or in a machine across the Web.
A Java interpreter embedded in the Java-compatible Web-browser then executes the applet. Note: A Java applet can be executed by an Applet viewer, a utility that comes with the Java Software Development Kit.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
296
Object-Oriented Programming I
297
Introduction to Applets
Passing parameters to an Applet Displaying images in an Applet Using Sound in Applets
Object-Oriented Programming I
298
The getParameter method returns null if no PARAM tag contains parameterName. Since getParameter returns a string; if you want a parameter to be some other type, you have to convert it yourself. Example, to get the size parameter from the previous HTML file, we can have:
String s = int theSize getParameter("size") ; = Integer.parseInt(s) ;
Object-Oriented Programming I
300
Object-Oriented Programming I
303
Object-Oriented Programming I
307
50);
soundFilename,
40,
stop()
when
you
change
to
Object-Oriented Programming I
308
Introduction to Recursion
Introduction to Recursion Example 1: Factorial Example 2: Reversing Strings
Example 3: Fibonacci
Infinite Recursion Review Exercises
Object-Oriented Programming I
309
Introduction to Recursion
We saw earlier that a method can call another method leading to the creation of activation records on the runtime stack. Recursion is one of the powerful techniques of solving problems. A recursive method is a method that calls itself directly or indirectly A well-defined recursive method has: A base case that determines the stopping condition in the method A recursive step which must always get closer to the base case from one invocation to another. The code of a recursive method must be structured to handle both the base case and the recursive case. Each call to the method sets up a new execution environment, with new parameters and local variables.
Sahalu Junaidu, Math Dept., ABU, Zaria Object-Oriented Programming I
310
public class Factorial{ public static void main(String[] args){ long answer = factorial(5); System.out.println(answer); }
Object-Oriented Programming I
311
(6*factorial(5)) (6*(5*factorial(4))) (6*(5*(4*factorial(3)))) (6*(5*(4*(3*factorial(2))))) (6*(5*(4*(3*(2*factorial(1)))))) (6*(5*(4*(3*(2*1))))) (6*(5*(4*(3*2)))) (6*(5*(4*6))) (6*(5*24)) (6*120) 720
Object-Oriented Programming I
312
Object-Oriented Programming I
313
fibonacci(n) =
fibonacci(n-1) + fibonacci(n-2),
if n >= 2
public class Fibonacci{ public static void main(String[] args){ long answer = fibonacci(4); System.out.println(answer); } }
public static long fibonacci(int n) { if (n < 2) return 1L; else return fibonacci(n-1) + fibonacci(n-2); }
Object-Oriented Programming I
314
else
return fibonacci(n-1) + fibonacci(n-2); }
Object-Oriented Programming I
315
Infinite Recursion
A recursive method must always call itself with a smaller argument Infinite recursion results when: The base case is omitted. Recursive calls are not getting closer to the base case. In theory, infinite recursive methods will execute forever In practice, the system reports a stack overflow error.
Object-Oriented Programming I
316
Drill Questions
1. Write a recursive method public int sumUpTo(int n) which adds up all integers from 1 to n. Write a recursive method public int multiply(x,y) that multiplies two integers x and y using repeated additions and without using multiplication. Write a recursive method public int decimalToBinary(int n) that takes and integer parameter and prints its binary equivalent.
2.
3.