Procedural programming in Java - PowerPoint PPT Presentation

1 / 105
About This Presentation
Title:

Procedural programming in Java

Description:

if the string represents a palindrome - i.e. a word which ... command line argument is not a palindrome. If the number of command line arguments is not equal ... – PowerPoint PPT presentation

Number of Views:228
Avg rating:3.0/5.0
Slides: 106
Provided by: petem7
Category:

less

Transcript and Presenter's Notes

Title: Procedural programming in Java


1
Procedural programming in Java
1
Dr. Peter Martin - Room 2P16
1 hour lecture 1 hour practical per
week Programming language - Java2 Text Book -
Lewis Loftus - Java Solutions Web page -
www.csm.uwe.ac.uk/pcsmarti Working from home -
BURKS CD-ROM
2
2
Procedural programming in Java
Example program
What does this program do ?
3
3
Procedural programming in Java
Or this ?
4
4
Procedural programming in Java
Example program
Or this ?
5
5
Procedural programming in Java
Example program - Hello World
All programs are placed inside a class. Class
names start with an upper-case letter. Java is
case sensitive. The code is placed in a file
called HelloWorld.java. The program is always
called main. The class is delimited by braces

6
6
Procedural programming in Java
Example program - Hello World
7
7
Procedural programming in Java
Example program - Hello World
8
8
Procedural programming in Java
Example 2 - Using command-line arguments for
input.
9
9
Procedural programming in Java
Example 3 - Handling integer values
10
10
Procedural programming in Java
Strings in
Java Creating string variables String
greeting Hello String text
text
args0 Comparing strings
text.equals(Hello)
text.compareTo(args1) Determining the length
of strings int len text.length() Concaten
ating strings String message text -
args1 Picking off parts of a string char
ch text.charAt(0) message
text.substring(3,6) Changing case String
big text.toUpperCase() The String class has
48 methods. Take a careful look at these by
reference to Java2 SDK -gt java.lang -gt String
11
11
Procedural programming in Java
Basic data types in
Java Integer (whole number) types byte
tiny //8 bits, range -128 .. 127
short x,y 5,z //16 bits, range -32768 ..
32767 int count 0 //32 bits, range
approx -2000,000,000 long dist -53
//64 bits, range approx -10 zillion Fractional
values (floating-point) types float height
-3.4e22 //32 bits, 7 significant digits
double fine 123.5 //64 bits, 15 significant
digits Single characters char ch X
//16 bits - Unicode character Logical (truth)
values boolean ok true //1 bit -
constants - true, false Conversion (casting)
between types Automatic if no loss of info,
e.g. count tiny fine dist Explicit
otherwise, e.g. tiny (byte)count dist
(long)fine
12
12
Procedural programming in Java
Command-line
arguments Determining number of arguments
int numberOfArgs args.length //Note - no
brackets For any array, arrayName.length
gives length Conversion to integer int
value Integer.parseInt(args0)
parseInt() raises NumberFormatException if a non
numeric value is entered. Conversion to
float double volume Double.parseDouble(arg
s1) Again this can raise
NumberFormatException Dealing with exceptions
13
13
Procedural programming in Java
public class Program3 public static void
main(String args) int value1,
value2, sum //declare variables if
( args.length ! 2 )
System.err(Incorrect number of arguments)
System.exit(-1) //end if
try //attempt to convert
args to integers value1
Integer.parseInt(args0) value2
Integer.parseInt(args1) //end
try catch(NumberFormatException nfe)
System.err(Arguments must be
integers) System.exit(-1)
//end catch sum value1
value2 System.out.println(Sum is
sum) //end main //end class Program3
Revised version of addition program. Checks
number of arguments Checks that arguments
are numbers.
14
14
Procedural programming in Java
Arithmetic expressions
assignment Arithmetic operators , -- ,
, - increment, decrement, unary plus minus
count //same effect as count
count 1 , /, multiply,
divide remainder after division 5
6 / 2 is 30, 7 / 2 is 3, 7 2
is 1 , - binary addition
subtraction Order of evaluation Bracketed
expressions first Highest precedence
first Left to right ( 6 4 / 2
) 4 / 3 is equal to ??? Assignment
operation Right hand side expression
evaluated and result placed in variable
named on left hand side x 3 y - p
/ q Other operators exist, e.g. , -,
, /, etc
15
15
Procedural programming in Java
Boolean
conditions Comparison operators lt, gt, lt,
gt, , ! less than, greater than, etc
count lt 25 //watch out for and
Boolean operators , , !
and, or, not count lt 25
count gt 0 Note expressions containing and
as well as or should be bracketed -
count lt 25 count gt 0 ch X
//not this ( count lt 25 count gt 0
) ch X //but this Boolean variables
Boolean variables contain truth values and
can be used directly - boolean
ok false text.length() lt 10
count lt 25 ok //is false ok
count ! 100 ch ! X //assigning a value
16
16
Procedural programming in Java
Selection - the if
statement Format of the if statement if (
ltconditional expressiongt )
//statements executed when condition is true
else //statements executed when
condition is false //end if Examples
if ( count gt 25 )
System.out.println(Count greater than 25)
else System.out.println(Count less
than or equal to 25) //end if if (
ok ) System.out.println(Everything is
fine) //next statement
17
17
Procedural programming in Java
Complex if statements
if statements can be nested, but rapidly become
complicated to understand. The following code
finds the minimum of three values -
Nested ifs
Non-nested ifs if (val1 lt val2 )
if ( val1 lt val2 val1 lt val3)
if ( val3 lt val1 )
System.out.println(val1)
System.out.println(val3) else if (val2 lt
val3 ) else
System.out.println(val2)
System.out.println(val1) else else

System.out.println(val3) if (val3 lt val2)
//next statement
System.out.println(val3) else
System.out.println(val2) //next statement
18
18
Procedural programming in Java
Example use of if statements
19
19
Procedural programming in Java
Loops - while do/while
loops The while loop This is the only
repetition control structure actually needed
in Java - the others are there purely for
convenience. while ( ltconditional
expressiongt ) //statements to
be repeated //end while The
while loop tests the condition first and stops as
soon as it evaluates to false - which could
be immediately. The do while loop This
has the form - do
//statements in loop while (
ltconditional expressiongt ) The condition
is evaluated at the end of the loop, so it is
guaranteed to execute at least once.
20
20
Procedural programming in Java
The break continue
statements The break statement It is
possible to break out of a loop prematurely at
some point within it. i.e. not executing
all the statements - e.g. while (
count lt 100 )
System.out.println(count is less than 100)
balance balance - amount
count
System.out.println(now going to check
balance) if ( balance lt 0 )
break System.out.println(Keep
going - still in credit) //end
while System.out.println(Stopped
spending) The continue statement This
skips to the end of the current loop iteration
but continues with the next iteration.
21
21
Procedural programming in Java
A simple programming
problem Problem definition A program is
required which will take a string as a command
line argument of any length and determine if the
string represents a palindrome - i.e. a word
which reads the same backwards as forwards. If
the word is a palindrome, a message -
ltcommand line argumentgt is a palindrome should
be displayed. If not, the message should be -
ltcommand line argumentgt is not a palindrome If
the number of command line arguments is not
equal to 1 an error message should be displayed.
22
22
Procedural programming in Java
A simple programming
problem Program design word
string represents command line argument
length integer represents
length of word if there is one
command line argument then
set word command line argument
set length length of word
for all characters at pos in the first half of
the word if char at
pos not equal to char at length-pos then
exit for
end if end for
if premature exit from loop then
display not a palindrome
else
display palindrome end if
else display
error message end if
23
23
Procedural programming in Java
A simple programming
problem Program code public class
Palindrome public static void
main(String args) String
word int length, pos 0
if ( args.length 1 )
word args0
length word.length()
while ( pos lt length / 2)
if ( word.charAt(pos) !
word.charAt(length - 1 - pos))
break
pos //end
while if ( pos gt length
/ 2 )
System.out.println(word is a palindrome)
else
System.out.println(word is not a
palindrome) else
System.err.println(One command
line argument only) //end main
//end class Palindrome
24
24
Procedural programming in Java
Loops - the for
loop The for loop provides a convenience when a
variable is to be incremented each time the loop
executes. It has the form - for
(ltinitialisationgt ltconditiongt ltchangegt)
//statements of the loop
//end for Initialisation - here a loop
counter is given an initial value
e.g. i 0 Condition - this
is just a boolean condition as for while,
do..while and if
conditions Change - change to be made
to loop counter at end of
an iteration of loop - e.g. i a) counter
is initialised, b) condition is tested, c)if
true the loop is executed, d) counter changed -
repeat from b)
25
25
Procedural programming in Java
The for
loop Comparison with while loop The for loop
is a more appropriate loop to use for the last
problem as the following comparison shows
- int pos 0 while ( pos lt length / 2 )
if ( word.charAt(pos) ! word.charAt(length - 1
- pos) break pos //end
while int pos for ( pos 0 pos lt length/2
pos) if ( word.charAt(pos) !
word.charAt(length - 1 - pos) break
26
26
Procedural programming in Java
The switch
statement The final control structure in Java is
the switch statement which allows multi-way
branching on the basis of the value of a variable
or expression. It has the form -
switch ( ltexpressiongt ) case
ltvaluegt //statements
break
default //statements if no match
//end switch the expression can be anything
from a single variable to a complex arithmetic
expression, but the result must be discrete -
i.e. either integer or character. The default is
optional and individual cases may have any number
of statements, including none !
27
27
Procedural programming in Java
Example of switch
statement int count 5 switch ( count )
case 0 System.out.println(count is 0)
break case 1
System.out.println(count is 1)
break case 2 case 3
case 4 System.out.println(count is between 2
and 4) break default
System.out.println(count lt 0 or gt 4) //end
switch
28
28
Procedural programming in Java
Exercise in use of control
structures Problem specification A program is
to be written which will take three command line
arguments. The first and third should be integers
and the second should be an arithmetic operator
- , -, , /, , (this last is an
invention and here
means raise to power of, e.g. 2 3
8) The program will check for errors -
First or third parameter non integer Less
than or more than 3 parameters Second
parameter not one of the above and produce
suitable error messages. If all is well, the
calculation is performed and result displayed.
29
29
Procedural programming in Java
Exercise in use of control
structures Test plan
30
30
Procedural programming in Java
Pseudo-code
31
31
Procedural programming in Java
32
32
Procedural programming in Java
Progress test - part 1
1. Which of the following variable 2.
What data types are most identifiers are
inappropriate ? suitable for these
items ? a) book3
a) age in
years to nearest year b) first-time
b)
height in inches to 2 dec places c)
4tune
c) distance to the moon to nearest
metre d) sx
d) indication of
value being valid or not e ) Amount
e)
first init of name 3. Given the following
4. Given the previous 5. Given these
declarations, variable declarations,
declarations, what is what is the value
of the which of these assignments the
value of these following expressions
? are valid ?
expressions ? int i 5, j 3
a) i
a) !(i 5 double k 23.1
b) j 8
b) !b (i lt j k gt 20) boolean b
true c) i j
c) b j gt 0 a) i
k d) i / j
d) !(j ! 5)
b) k i e)
((k - 3)(I - j))/2 4 e) b (I gt j)
c) i (float)k d) i (int)k
23.5 e) i i 6.5
33
33
Procedural programming in Java
Progress test - part 2
6. What is wrong with the following 7.
What value does result have after execution
if statement ?
Of this for loop ? if (i gt 5)

int result 0
System.out.println("igt5")
for ( int I 0 I lt 12 I 3) else
if(i lt 0)
result 5
System.out.println("ilt0")
else System.out.println("i is between 0
and 5") 8.What value does result 9. What
output is produced 10. What output is
produced have after execution
by this segment of code ? By the
following code ? of this loop ?
int result 0, i 5
int val 5
int val 4 while (i lt 10 )
do
switch (val - 3) i
System.out.println(val)
case 0 System.out.println(A) if ( i
9 ) break val--
case 1
System.out.println(B) result 3
while ( val gt 6)
case 2 System.out.println(C)

//end
switch
34
Procedural Programming in Java
34
The square root algorithm
The square root of a number can be calculated by
taking a series of estimates. Each successive
estimate is derived from the previous using the
following formula - new estimate
average of (old estimate value/old estimate)
This can be expressed as pseudo-code as follows
- value integer value whos square root
is required e1 real first
estimate e2 real next estimate e2
value / 2 a crude way to start off with a
first guess do set e1 to e2 set e2 to (e1
value/e1)/2 while positive difference between
e1 and e2 gt accuracy required Note In order
to repeat the loop, the new estimate must become
the old one next time round. Hence the
need for - set e1 to e2
35
Procedural Programming in Java
35
Implementation of square-root program
36
Procedural Programming in Java
36
Sub-programs in Java
37
Procedural Programming in Java
37
Parameterless methods
Here, the method chatter() needs no additional
information to do its job. Hence, nothing is
passed to it as parameters and nothing is
returned.
38
Procedural Programming in Java
38
Method with parameters
In this version of chatter(), the method needs to
be told how often to repeat the message - the int
repeat in the method header is a formal
parameter, the 2 x and the 5 in the method
calls are actual parameters.
39
Procedural Programming in Java
39
Method with parameters
Here, chatter() needs to be told what to say and
how often. Formal parameters consist of lists of
data type followed by name - int repeat, String
message Actual parameters consist of a
corresponding set of values - 5 , args0
40
Procedural Programming in Java
40
Method which return results
Here, chatter() needs to be told what to say and
how often. Formal parameters consist of lists of
data type followed by name - int repeat, String
message Actual parameters consist of a
corresponding set of values - 5 , args0
41
Procedural Programming in Java
41
Prompted keyboard input
So far we have obtained program input from the
command line arguments. This limits us to only a
few values and we are unable to prompt the
user. The usual way of getting input is to issue
a prompt and then receive data from the keyboard
within the program as follows -
42
Procedural Programming in Java
42
Prompted keyboard input
Input operations can cause run-time exceptions.
The previous program chose not to catch them but
to propogate them out of main - hence the throws
IOException clause. Here, we catch such
exceptions within the program.
import java.io. //provides visibility of io
facilities public class Greeting public
static void main(String args)
String name try
InputStreamReader isr new InputStreamReader(Syst
em.in) BufferedReader in new
BufferedReader(isr)
System.out.print(Enter your name )
//prompt for input name
in.readLine()
//get it //end try
catch(IOException ioe)
System.out.println(Welcome to Java - name)
//end main //end class Greeting
43
Procedural Programming in Java
43
Numeric input
Data is input as strings - just as with
command-line input. If numeric input is needed,
explicit conversion is required with
Integer.parseInt() or Double.parseDouble()
44
Procedural Programming in Java
44
A useful method
45
Procedural Programming in Java
45
Reading text files
Note - File not found excep. Should
be handled. Any number of files may
be open at once. Can use a constant
string or variable to name file.
Should close file at end of program.
46
Procedural Programming in Java
46
Writing text files
Note - Text output to file uses same
commands - print println as screen
output. Must call flush() and close() to
ensure data is written to file.
47
Procedural Programming in Java
47
Arrays in Java
Arrays are collections of similar items - e.g.
collections of ints or collections of doubles
etc. An array is associated with a
single variable name - The variable
declaration does not create the array, this must
be done using the keyword new, and at
this point the size of the array is set
Both steps can be done at the same time if the
array size is known at that point in the
program. Array elements start at 0 and
values can be referenced by using an
integer expression in square brackets e.g. 2
x - 5
48
Procedural Programming in Java
48
Bubble sort - Pseudo code
Pseudo-code is a powerful way of expressing
program structure during the design process.
Pseudo-code - Is a way of expressing the
design of the program in simple English
at different levels of detail as the design
develops. Should be concise and well
structured. Should be implementation language
neutral - using a minimum of basic keywords to
show structure - e.g. if, then, else, while, for,
do Should show structure of code
clearly. Can be expressed at any level of
detail. A design will normally go through
several levels of detail in pseudo-code before
being translated into the target language.
49
Procedural Programming in Java
49
Bubble sort - Pseudo code
The following example develops a design for a
Bubble-sort program. In order to sort an array
of int values into ascending (or
descending) order, one approach is to scan the
array, comparing adjacent values and if they are
the wrong way round, swap them. This scanning is
repeated until no more swaps occur at which point
the array is sorted into order. The following
data illustrates a single scan through the data
- 15 2 9 3 1 2
15 9 3 1
2 9 15 3 1
2 9 3
15 1
2 9 3 1 15 Note that the
large value at the beginning bubbles up to the
top, but the small value at the top only descends
one place
50
Procedural Programming in Java
50
Bubble sort - Pseudo code
The pseudo-code for this could start like this
- data an array
of integers insert values into data from the
keyboard convert data into ascending
order display sorted data Concentrating on the
sort process in step 2, the next level might be
- data an array of integers do for
all adjacent pairs of elements in data
if values in wrong order then
swap them end
if end for
while swaps have occurred
51
Procedural Programming in Java
51
Bubble sort - Pseudo code
Developing the design for the first and third
steps we get - data an array of integers
value integer temporary store to
hold keyboard input do
step1 insert data
prompt for and get value if value gt 0
then insert value into data end
if while value gt 0 do
step 2 sort data
for all adjacent pairs of elements in data
if values in wrong order then
swap them
end if end for
while swaps have occurred for all values in
data step 3 display data
display data element end for
52
Procedural Programming in Java
52
Bubble Sort - Java Code
53
Procedural Programming in Java
53
Bubble sort - Using methods
This program is starting to get long and could
benefit from subdivision into separate methods as
follows -
54
Procedural Programming in Java
54
Bubble sort - Using methods
If methods are to be used, the pseudo code should
also be broken down into separate segements in a
similar way. If this is done, the pseudo-code
should indicate the parameters being supplied and
the return value used as well as a name for each
method.
55
Procedural Programming in Java
55
Progress test
public class Mean public static void
main(String args) throws IOException
int data getData() calcMean(data)
//end main public int getData()
BufferedReader in new BufferedReader(new
InputStreamReader(System.in)) int data
int100 int value, count 0 do

System.out.print(Enter value (-1 to
end)) value Integer.parseInt(in.rea
dLine()) if (value gt 0)
datacount value while (value gt
0) int results new int count
for (i 0 i lt count i) resultsi
datai return results //end
getData public void calcMean(int data)
int sum for (int i 0 i lt count
i) sum datai System.out.println(su
m/count) return true //end
calcMean //end class Mean
56
Programming in Java - Classes as Objects
56
So, far we have used classes simply as containers
for methods. Classes can however be used to
represent Singleton objects. A class can have
its own attributes which maintain state
information and a set of methods which bring
about changes of state.
Example of PostBox Note - static
attributes representing state static
methods changing state
57
Programming in Java - Classes as Objects
57
The PostBox class can be used to represent a
single PostBox object in an application as
follows -
58
Programming in Java - Classes as Objects
58
As another example, take the Vehicle class -
59
Programming in Java - Classes as Objects
59
And an application which uses it - Note
- There can only be one (singleton)
vehicle object in the system The
static qualifier on methods and attributes
indicates they refer to the class (i.e.
attributes of the class object and methods which
modify or access those attributes)
60
Programming in Java - Classes as Object Factories
60
public class Vehicle String registration
int mileage 0 //end class Vehicle
public class UseVehicle public static void
main(String args) Vehicle car1,
car2 //declare references to vehicle instances
car1 new Vehicle() //create an
instance of vehicle car2 new
Vehicle() //create another instance
car1.registration ABC123 //register car
car1.mileage 25
//take a short trip car2.mileage
1000 //car2 an independent
instance System.out.println(Car 1
mileage car1.mileage) car1.mileage
0 //winding back the
clock car1.registration PQR999
//putting on false plates //end
main //end class Vehicle
61
Programming in Java - Classes as Object Factories
61
Note here - Attributes have been
designated private. This prevents the
illegal operations in the previous
program. Methods are needed to both
access and modify these attributes.
Methods are not designated static as
they operate on instances of the class
and not on the class itself.
62
Programming in Java - Classes as Object Factories
62
The UseVehicle program now becomse -
63
Programming in Java - Classes as Object Factories
63
Here, the qualifier static has been removed.
This means that - A constructor method
is used to set registration on instance
creation. The addJourney method is
modified to prevent a negative
mileage. The class acts as a factory,
creating instances of class Vehicle.
The class acts as a blueprint
defining the features of vehicle
instances.
64
Programming in Java - OO Concepts
64
65
Programming in Java - OO Concepts
65
We have met some important OO concepts now
- The set of public methods defined in a class
is called the classes interface to its
clients. Any number of instances may
simultaneously exist and each has its own
private and independent state. Instances are
created by calling the constructor method, which
both creates and initializes the instance. A
default constructor is provided in a class
unless a user defines one (or more). Any
number of constructors may be defined so long as
they all have different numbers and/or types of
parameters. The same applies to other
identically named methods within a class. This is
called overloading.
66
Programming in Java - Inheritance
66
One of the powers of OO is to be able to be able
to create new classes of object by specialising
existing classes. This process is called
inheritance which in Java is limited by the
constraint that each class can only inherit (be
derived from) one parent class - single
inheritance. This results in a tree structure of
classes as illustrated below -
67
Programming in Java - Inheritance
67
Inheritance represents the is-a or is-a-kind-of
relationship between classes. In Java this is
single inheritance, so a DUKW which inherits from
a boat and a car cannot be directly
represented. The parent class is called the
super class and represents a generalisation of
the derived class (or sub class). The sub class
is a specialisation of the super class and
may have extra attributes and/or
methods. Inheritance is incremental, attributes
may be added but not taken away. Methods may be
added or modified. This later is called
overriding.
68
Programming in Java - Inheritance
68
Note - the attributes of Car instances
include the inherited ones - mileage
and registration similarly the methods
include - getReg, getMileage, addJourney
69
Programming in Java - Inheritance
69
We can similarly derive a Van class from the more
general Vehicle one thus -
70
Programming in Java - Inheritance
70
Taking another example, that of a Person class
and specialisations to Male and Female -
Female
Male
children getKids talk
bearded isBearded talk
71
Programming in Java - Inheritance
71
Note the call to the super-class version of
talk() in the overriden methods talk().
72
Programming in Java - Type compatability
72
A variable in Java may refer to instances of the
variables class, or instances of any
sub-class. In general, it is not known
what class of object a variable refers to. When
a sub-class overrides a method defined in the
super class, the method to be called is not known
until run-time. Such methods are bound at
run time - dynamic binding. This is referred to
as polymorphic referencing.
73
Programming in Java - Polymorphism
73
The rule about substitutability also applies to
actual parameters matching formal parameters
in method calls. Polymorphism refers to the
characteristic that when the same message is
sent to different objects, they respond to it
in different, but equivalent ways. This
behaviour is important when the recipient of a
message is not known.
74
Programming in Java - Arrays of Objects
74
Arrays of objects are created by - first,
declaring an array reference variable.
then, allocating space for an array of
references. finally, objects can be created
and their references assigned to elements
of the array. All unassigned references
will have the value null.
75
Programming in Java - Abstract classes
75
In our garage problem, we dont want to have
Vehicle instances, only Car and Van
instances. The Vehicle class is there to
factor out the common methods and attributes in
the other two classes. It also serves to define
the set of methods (messages) which can be sent
to Vehicles (protocol). As Vehicles should not
exist, we can make the class Abstract and Java
will refuse to instantiate objects of the class.
76
Programming in Java - Abstract classes
76
In the Garage implementation there is a problem
- The fleet is a fleet of vehicles, hence
cannot send elements of the array the following
messages - getSeats()
getCapacity() as these are not defined for
class Vehicle. The abstract class must
declare, even if it does not define, all the
methods to be used in the sub-classes. i.e. it
defines the protocol to be implemented by
the concrete sub-classes.
77
Programming in Java - Abstract classes
77
Abstract classes provide a definition of the
protocol to be implemented by sub-classes. They
DO contain constructors, but these can only
be called via sub-class constructors. They can
have method implementations and
attributes. Abstract methods are inherited by
sub-classes and will make the sub-class abstract
if not overridden. Can use null methods rather
than abstract methods.
78
Programming in Java - Collection classes
78
Java2 provides a rich set of collection classes,
but for this course we look only at the more
meagre provisions of JDK 1.1 . In addition to
Arrays, Java 1.1 has Vectors and Hashtables. A
Vector is a dynamically expandable/contractable
collection of Objects - these are referencable
in a similar way to the elements of an array. A
Hashtable is a dynamically expandable collection
of key/value pairs. Both key and value are
Objects. This allows random access to values by
supplying the key (implemented by a hashing
algorithm defined in the class Object, but
overridable). As both collection classes
accommodate only Objects, ints, shorts,
doubles etc must first be wrapped using a
wrapper class. Vectors can easily be processed
sequentially, but to do this with Hashtables it
is necessary to employ an Enumeration object.
79
Programming in Java - Vectors
79
To add items to vector use the method
addElement() To access items, use the
method elementAt() - Vectors are indexed like
arrays. The item returned from a Vector is
assumed to be of class Object and has to be cast
to the correct type - called DownCasting The
number of elements in a Vector is given by the
method size() Processing is similar to
arrays although Enumerations can be used
80
Programming in Java - Wrapper classes
80
As Vectors and Hashtables can only contain
objects, to store simple data types, such as int,
long, double etc wrapper classes are
needed. There are separate wrapper classes for
all basic data types e.g. Byte, Short,
Long, Float, Character, Boolean. Each instance
of a wrapper class contains a single attribute of
the corresponding simple type.
81
Programming in Java - Hashtables
81
The previous version of Garage made it difficult
to access individual vehicles. Here, the
collection is keyed on registration
number. Traversing all items in a Hashtable
requires the use of an Enumeration
instance. Enumerations operate like a
file, starting at the first item and working
sequentially through until end-of-file. Must
obtain a new enumeration to repeat the process.
82
Programming in Java - The Zoo problem
82
A zoo contains a large number of different types
of animal. All animals respond to the message
talk() by announcing what they are, their
name and age. Each type of animal is represented
by a different sub-class of the abstract animal
super-class. The zoo itself provides methods to
add animals and responds to the message
feeding-time() by sending the message talk() to
all the animals. The main program makes use of a
menu class instance to provide the user with a
suitable menu selection - add animal, feeding
time, quit. Create an Animal, Zoo and Menu class
and a small selection of animal sub-classes such
as Lion, Tiger Elephant etc. Create a separate
Application class just containing a main method.
83
Programming in Java - Interfaces
83
The set of public methods defined in a class are
referred to as the public interface to that
class. This represents the set of messages to
which instances respond - also called its
protocol. There exists in Java a component
called an interface which consists only of method
declarations - i.e. contains no attributes or
method implementations. This is distinct from
abstract classes which can have both attributes,
method implementations and constructors.
84
Programming in Java - Interfaces
84
An example of an interface is the Enumeration
interface just used in Vectors and Hashtables.
This has a declaration as follows -
Enumerations usually represent capabilities such
as - Serialisable Runnable Observer Cloneabl
e Objects which implement them will belong to
some other class.
85
Programming in Java - Interfaces
85
An interface represents a contract which an
implementing class enters into - to provide the
set of methods defined. e.g. if we have
an interface Storeable -
Objects requiring to have this capability must
implement the interface and provide the
corresponding methods -
86
Programming in Java - Interfaces
86
Given a collection of instances of maybe a
variety of different classes, all of which have
implemented the interface Storeable, we can make
use of this knowledge by treating them as
instances of the type Storeable - The
array of Storeable could contain any
mixture of objects so long as their
classes have implemented the interface.
Classes can implement any number of
interfaces.
87
Programming in Java - Interfaces
87
Classes can implement any number of
interfaces. Interfaces can be viewed as a
subset of the classes interface Allows client
code to have restricted and different views
of the objects protocol. Instances of classes
implementing an interface can be treated as
though they were instances of the interface type.
88
Programming in Java - Exception handling
88
Exceptions are run-time errors which occur under
exceptional circumstances - i.e. should not
normally happen. In Java an exception is an
instance of an Exception class which is thrown by
the offending code. Exceptions, if not handled
by the program will cause the program to
crash. Exceptions are handled by catching them
and dealing with the problem. Exceptions are
propogated from a method to the caller
back through the chain of callee to caller. If
propogated out of main, they are always handled
by the run time system. (virtual machine).
89
Programming in Java - Exception handling
89
Here is an example of an exception handler which
we will meet again - The sleep() method
in the Thread class delays the program
for the specified number of
milliseconds. If interrupted, an exception
occurs. The try block signifies that we
wish to handle the exception. If an
exception occurs, the corresponding catch method
is executed and the exception cancelled.
Processing then continues with the next
statement. If no exception occurs, the
catch method is passed over. If the
exception is not handled, it is propogated to the
caller of methodA.
90
Programming in Java - Exception handling
90
Exceptions are of different types and form a
class heirarchy, just as other classes do.
Any number of catch methods may follow a
try block. When an exception
occurs, these are scanned in order, to find
a matching parameter. If one is
found, the exception is cancelled
and the handler code executed. All
other catch methods are ignored.
91
Programming in Java - Exception handling
91
Exceptions are instances just like other class
instances and can have attributes and methods.
This allows us to interrogate an exception object
to find out what happened. The exception
class is a sub-class of Throwable,
which provides the method printStackTrace()
etc. The finally block following a try
block is always executed. Users may
create their own exceptions which they
can throw and handle in same way as
predefined ones.
92
Programming in Java - Exception handling
92
User-defined exceptions
93
Programming in Java - Exception handling
93
Exception classes fall into two groups -
sub-classes of RunTimeException and others. In
the case of others - A method which could
give handle the
exception rise to an exception either
locally. by
throwing it or calling a method which
might, This
does not apply to must declare the fact in
a
RunTimeExceptions. throws clause, or
94
Programming in Java - Exception handling
94
95
Programming in Java - Petri-Net problem
95
Petri-nets are diagrams used to simulate the
behaviour of concurrent systems. Their main
purpose is to identify the possibility of
deadlock. The diagram consists of nodes called
places (where either a queue of resources waits
to be allocated or a process is carried
out. Places are connected to nodes called
transitions by directed arcs in such a way that
all paths through the network are a strict
alternation of places and transitions. The arcs
leading to a transition are called inputs to the
transition (from input places) and the arcs
leading away from a transition are called outputs
from a transition. Places are occupied by a
number of tokens representing units of resource.
A Transition is said to be fireable if all input
places contain a token.
96
Programming in Java - Petri-Net problem
96
When a transition fires it removes tokens from
its input places and sends them to its output
places. At any one time, a number of Transitions
may be fireable. One is selcted at random and
fired. This process continues until we are
satisfied that deadlock will not occur or until
no transitions are fireable. (condition for
deadlock) One minor modification allows an arc
to represent several tokens (called a
weighting). This input requires there to be
sufficient numbers of tokens in the corresponding
input place. Or if an output arc specifies how
many token are deposited in the output
place. The simulation proceeds by randomly
selecting fireable transitions and hence moving
the tokens around the network.
97
Programming in Java - Petri-Net problem
97
T1
Queue of input jobs
4
2
1
P1
P1
P2
5
1
T2
T1
Idle cpus
1
1
3
Job processing
P3
P4
P2
P3
1
3
T3
T2
1
3
P4
P5
Queue of output jobs
T4
Computer job scheduling
Part of assembly line
98
Programming in Java - Petri-Net problem
98
Required - Design and implement a system which
will allow for the following - creation of a
transition creation of a place connecting a
transition to an input place with specified
weight connecting a transition to an output
place with specified weight insertion of tokens
into a place attempting to fire a nominated
transition running the simulation for a
specified number of firings At each stage, the
state of the petri-net is displayed - this is
represented by a vector of token counts in
places. E.g.(2, 0, 1, 3) and (4,1,0,3,0)
in examples. It must also be possible to display
the structure of the net and its connections in
a tabular form.
99
Programming in Java - Threads
99
Java Threads provide concurrent execution.
Instances of sub-classes of the Thread class have
their own thread of execution.
The sub-class defines the processing required in
the run method.
The Thread class defines methods start() - to
start the run method
suspend() - to interrupt it resume() - to
continue it stop() - to terminate it finally
100
Programming in Java - Threads
100
Sometimes, the class whose instances need to run
concurrently need to inherit from some other
class - often Frame. Another way of
creating concurrent threads must then be used -
101
Programming in Java - Threads - IPC
101
Threads use a shared object - a Buffer -
to communicate. The global object is passed in
the constructor and Producer Consumer are long
running independent threads.
102
Programming in Java - Threads - IPC
102
As the get and put operations involve changes to
count and this is non-atomic, the state of the
buffer may become inconsistent These operations
should operate under mutual exclusion.
103
Programming in Java - Semaphores
103
Regions of code in both the Producer and the
Consumer which modify the shared data are called
critical sections. Only one thread is allowed to
be in a critical section at any one time. This
condition is called mutual- exclusion. Achieved
by aquiring a lock on the critical region with
the synchronized statement. Gives rise to the
danger of deadlock if two separate shared objects
are involved.
104
Programming in Java - Monitors
104
Critical regions can proliferate and are
difficult to keep track of Better solution is to
use a Monitor A Monitor is an object which
has synchronized methods. Only one thread is
allowed to be executing a synchronized method at
one time. This guarantees mutual exclusion of
conflicting operations. The suspended threads
are held in a queue waiting to access the
synchronized methods. Non synchronized methods
can still be called freely at any time.
105
Programming in Java - Condition Queues
105
One problem with the previous buffer
implementation is - what happens when we try to
get from an empty buffer or put to a full one.
If a thread enters a get method and
discovers the buffer empty it must release
the lock on the buffer. It does this
with the wait statement. This
suspends the thread and it will only be
re-awoken by another thread issuing a
notify. Two separate condition
queues must be provided for.
Write a Comment
User Comments (0)
About PowerShow.com