Introduction To Java Programming Language
Introduction To Java Programming Language
the Java
Programming Language
Abstract
The primary aim of the notes are to provide an introduction to the Java programing lan-
guage. It is assumed that you know one programming language moderately well. There is a
brief coverage of most of the features of the language, and the emphasis is on breadth be-
fore depth.
The material in these notes evolves as Java evolves.
© Ian D Chivers. Permission to copy all or part of this work is granted, provided that the
copies are not made or distributed for resale (except a nominal copy fee may be charged),
and provided that the Author, Copyright, & No Warranty sections are retained verbatim and
are displayed conspicuously. If anyone needs other permissions that aren't covered by the
above, please contact the author.
Table of Contents
1 Overview...............................................................................................................16
1.1 Aims............................................................................................................................16
1.2 Assumptions ...............................................................................................................16
1.3 Course Material and Recommended Sources ............................................................16
1.4 Java Versions – Bits of History .................................................................................17
1.4.1 1.0.x ..................................................................................................................................17
1.4.2 1.1.x ..................................................................................................................................17
1.4.3 1.2.x – aka Java 2.............................................................................................................17
1.5 Development platforms ..............................................................................................17
1.6 Development kits and Standards................................................................................18
1.7 Miscellanea .................................................................................................................18
1.8 Course Timetable........................................................................................................19
1.9 Coda............................................................................................................................19
1.10 Bibliography ...............................................................................................................19
2 An Introduction to Programming Languages and Object Oriented Pro-
gramming ...................................................................................................................24
2.1 Fortran 66, 1966 .........................................................................................................24
2.2 Pascal, 1975, ANSI & BSI 1982, ISO 1983, Extended Pascal 1991?......................24
2.3 Fortran 77, 1978 .........................................................................................................25
2.4 C, K&R 1978, Standard 1989. ...................................................................................25
2.5 Modula 2, 1982, Standard 1996? ...............................................................................25
2.6 Ada, ISO 8652: 1987 .................................................................................................25
2.7 C++, 1986, Standard November 1997 .......................................................................25
2.8 Oberon 2, Late 1980's, early 1990's...........................................................................26
2.9 Fortran 90, 1991. ........................................................................................................26
2.10 Eiffel, 1988 .................................................................................................................26
2.11 Ada, ISO 8652: 1995 .................................................................................................26
2.12 Java .............................................................................................................................27
2.13 Visual Basic................................................................................................................27
2.14 Language Comparison................................................................................................27
2.15 Language Features......................................................................................................29
2.15.1 Independent Compilation .................................................................................................29
2.15.2 Separate Compilation .......................................................................................................29
2.15.3 Concrete Data Types ........................................................................................................29
2.15.4 Abstract Data Types .........................................................................................................29
2.15.5 Dynamic arrays.................................................................................................................29
2.15.6 Numeric and General Polymorphism...............................................................................29
2.15.7 Modules ...........................................................................................................................30
2.15.8 Pointers and References ...................................................................................................30
2.15.9 Procedure Variables .........................................................................................................30
2.15.10 Inheritance ........................................................................................................................30
2.15.11 Dynamic Binding .............................................................................................................30
2.15.12 Operator Overloading.......................................................................................................30
2.15.13 Threads/Multitasking........................................................................................................30
2.15.14 Exception Handling..........................................................................................................31
2.16 Some Important Milestones in Program Language Development ............................31
2.16.1 Structured Programming ..................................................................................................31
2.16.2 Stepwise Refinement........................................................................................................31
2.16.3 Data Structuring, Concrete vs Abstract Data Types........................................................31
2.16.4 Information Hiding – Modules ........................................................................................31
2.17 Terminology of Object Oriented Programming.........................................................31
2.18 Parallel Developments................................................................................................31
2.18.1 Parallel Fortran – Fortran 95, Fortran 2000, SMP, MPI, HPF .......................................32
2.18.2 Parallel C++......................................................................................................................32
2.19 Object Oriented Programming ...................................................................................32
2.20 Object Oriented Languages ........................................................................................33
2.20.1 Simula – 1967 ..................................................................................................................33
2.20.2 Smalltalk – 1978 ..............................................................................................................33
2.20.3 C++ ...................................................................................................................................33
2.20.4 Eiffel .................................................................................................................................33
4 Contents
22.5.2.5 Timestamp................................................................................................................270
22.5.2.6 Types........................................................................................................................270
22.5.3 Exception Summary .......................................................................................................270
22.5.3.1 BatchUpdateException – JDBC 2.0 .......................................................................270
22.5.3.2 DataTruncation.........................................................................................................270
22.5.3.3 SQLException..........................................................................................................270
22.5.3.4 SQLWarning ............................................................................................................270
22.6 Package javax.sql ....................................................................................................270
22.6.1 Interface Summary .........................................................................................................270
22.6.1.1 ConnectionEventListener.........................................................................................270
22.6.1.2 ConnectionPoolDataSource .....................................................................................270
22.6.1.3 DataSource ...............................................................................................................270
22.6.1.4 PooledConnection ....................................................................................................270
22.6.1.5 RowSet .....................................................................................................................270
22.6.1.6 RowSetInternal.........................................................................................................270
22.6.1.7 RowSetListener........................................................................................................270
22.6.1.8 RowSetMetaData .....................................................................................................270
22.6.1.9 RowSetReader..........................................................................................................271
22.6.1.10 RowSetWriter...........................................................................................................271
22.6.1.11 XAConnection .........................................................................................................271
22.6.1.12 XADataSource .........................................................................................................271
22.6.2 Class Summary...............................................................................................................271
22.6.2.1 ConnectionEvent......................................................................................................271
22.6.2.2 RowSetEvent............................................................................................................271
22.7 Examples...................................................................................................................271
22.8 Summary...................................................................................................................271
22.9 Bibliography .............................................................................................................271
23 Servlets................................................................................................................274
23.1 Getting started ..........................................................................................................274
23.1.1 Notes...............................................................................................................................278
23.1.1.1 Jar files.....................................................................................................................278
23.1.1.2 Start the server .........................................................................................................278
23.1.1.3 Compiled class files.................................................................................................279
23.1.1.4 Incorrect example link .............................................................................................279
23.1.1.5 Complete source code..............................................................................................279
23.1.1.6 Calling Servlets From a Browser ...........................................................................279
23.1.1.7 Calling Servlets from an HTML page.....................................................................280
23.2 Package java.servlet .................................................................................................280
23.2.1 Interfaces ........................................................................................................................280
23.2.2 Classes ............................................................................................................................280
23.2.3 Exceptions .....................................................................................................................280
23.3 Package java.servlet.http ..........................................................................................280
23.3.1 Interfaces ......................................................................................................................280
23.3.2 Classes ..........................................................................................................................281
23.4 Package java.servlet.jsp............................................................................................281
23.4.1 Interfaces ......................................................................................................................281
23.4.2 Classes .........................................................................................................................281
23.4.3 Exceptions ...................................................................................................................281
23.5 Package java.servlet.jsp.tagtext................................................................................281
23.5.1 Interfaces ......................................................................................................................281
23.5.2 Classes .........................................................................................................................281
23.6 Bibliography .............................................................................................................281
24 JavaServer Pages ...............................................................................................284
24.1 Bibliography .............................................................................................................284
24.1.1 JSP ..................................................................................................................................284
24.1.2 HTML.............................................................................................................................284
24.1.3 XML ...............................................................................................................................284
25 Package java.util................................................................................................286
25.1 Package java.util ......................................................................................................286
25.1.1 Interface Summary .........................................................................................................286
25.1.1.1 Collection .................................................................................................................286
25.1.1.2 Comparator...............................................................................................................286
25.1.1.3 Enumeration .............................................................................................................286
Contents 13
26.1.2.5 DragSourceContext..................................................................................................293
26.1.2.6 DragSourceDragEvent .............................................................................................293
26.1.2.7 DragSourceDropEvent .............................................................................................293
26.1.2.8 DragSourceEvent .....................................................................................................293
26.1.2.9 DropTarget ...............................................................................................................293
26.1.2.10 DropTarget.DropTargetAutoScroller.......................................................................293
26.1.2.11 DropTargetContext ..................................................................................................293
26.1.2.12 DropTargetDragEvent..............................................................................................293
26.1.2.13 DropTargetDropEvent .............................................................................................293
26.1.2.14 DropTargetEvent......................................................................................................293
26.1.2.15 MouseDragGestureRecognizer ................................................................................293
26.1.3 Exception Summary .......................................................................................................293
26.1.3.1 InvalidDnDOperationException ..............................................................................293
26.2 Bibliography .............................................................................................................294
27 IEEE Arithmetic................................................................................................296
27.1 History ......................................................................................................................296
27.2 IEEE 754 Specifications...........................................................................................297
27.2.1 Single precision floating point format. ..........................................................................298
27.2.2 Double precision floating point format..........................................................................299
27.2.3 Two classes of extended floating point formats............................................................300
27.2.4 Accuracy requirements ..................................................................................................300
27.2.5 Base conversion - i.e. when converting between decimal and binary floating point for-
mats and vice versa............................................................................................................................300
27.2.6 Exception handling.........................................................................................................300
27.2.7 Rounding directions. ......................................................................................................300
27.2.8 Rounding precisions. ......................................................................................................300
27.3 Resumé .....................................................................................................................300
27.4 ematics ......................................................................................................................301
27.5 Bibliography .............................................................................................................301
27.5.1 Web based sources .........................................................................................................302
27.5.2 Hardware Sources...........................................................................................................303
27.5.3 Operating Systems..........................................................................................................303
27.5.4 Java and IEEE 754 .........................................................................................................303
27.5.5 C and IEEE 754 .............................................................................................................303
28 Language Standardisation................................................................................306
28.1 Sun ............................................................................................................................306
1
Overview
'The first thing we do, let's kill all the language lawyers.'
Aims
The aims of the chapter are to provide a background to the organisation of the
course.
Chapter 1 Overview 16
1 Overview
1.1 Aims
The primary aim of the course is to provide a Java conversion course. Some of the exam-
ples are taken from the Fortran 95 and C++ courses. These examples are available on the
college web server enabling you to compare the syntax of the three languages.
The rest of the examples look at what Java has to offer in its own right. In particular there
is a coverage of both Java programs and Java applets. Java programs are usually interpreted
using the Java interpreter provided with the development kit you use, whilst Java applets
run in a web browser. We will look into the differences in more depth later.
The emphasis is on breadth rather than depth.
1.2 Assumptions
It is assumed that the reader:–
has a working knowledge of programming with one of Fortran 77, Fortran 90,
Fortran 95, Pascal, Modula 2, C or C++;
knows about the benefits of structured programming;
knows about the data structuring facilities in one of the above languages;
has some knowledge of object oriented programming;
The size of these may put you off downloading over a telephone line. Around 9-10 Mb in
March 2000.
1.7 Miscellanea
We will be using a Sun unix system to learn Java. You will have to learn about:–
X-Windows access to the system using Vista Exceed;
the file manager;
terminal window access and the unix operating system;
the editor
html;
netscape and other browsers;
Coverage of these is provided in separate notes and within the body of the notes
1.9 Coda
Be prepared to devote some time to learning Java. You can't gain an understanding of 50
years of program language development and an object oriented language like Java without
some effort on your part. Modifying existing programs is a good place to start, but you
have to write your own from scratch to really learn a language. Think about how you learn
French, German, etc. Practice makes perfect. Be patient, Rome wasn't built in a day.
1.10 Bibliography
Deitel H.M., Deitel P.J., Java: How to Program, Prentice Hall.
1st Edition comments. This is a very well written complete coverage of the Java lan-
guage. If you had to get just one large text then this is one to consider. 1050 pages
in all.
3rd Edition comments. I bought this edition in February 2000 and it has been up-
dated considerably. It now covers Java 2 and Swing. The CD has JDK1.2.1 on it as
well as Netbeans Developer 2.2.1 and Inprise (nee Borland) JBuilder 3 (University
Edition). It also has coverage of JDBC, servlets, remote method invocation, and the
attempt to provide an equivalent to the STL in Java. At around £30 it is very good
value. Also contains lots of links to Java resources available on the Web.
The following is a list of some of the chapters:
2. Java Applications
3. Java Applets
4. Control structures – 1
5. Control structures 2
6. Methods
7. Arrays
8. Object based programming
9. Object oriented programming
10. Straings and characters
11. Graphics and Java2D
12. Basic GUI components
13. Advanced Gui
14. Exception handling
15. Multihtreading
16. Multimedia, animation, audio, video
17. Files and streams
18. JDBC
19. Servlets
20. RMI
21. Networking
22. Data structures
23. Utilities
24. Collections
25. JavaBeans
Eckstein R., Loy M., Wood D., Java Swing, O R'Reilly.
There are a number of books on Swing and this one looks to be one of the better
ones with a coverage of most of the features I was interested in. The following are
the chapters:
1 Introducing Swing
2 Jump starting a Swing application
3 Swing component basics
4 Labels and Icons
5 Buttons
6 Bounded range components
7 Lists and Combo boxes
8 Swing containers
9 Internal frames
10 Swing dialogs
11 Speciality panes and layout managers
12 Chooser dialogs
13 Borders
14 Menus and toolbars
15 Tables
16 Advanced table examples
17 Trees
18 Undo
19 Text
20 Document models and events
21 Styled documents and Jtextpane
22 Carets, highlighters and keymaps
23 text views
24 editorkits and text actions
25 Programming with accessibility
26 Look and feel
27 Swing utilities
28 Swing under the hood
Nilsson D.R., Jakab P.M., Developing JavaBeans Using VisualAge for Java, Wiley.
I have had a look at JavaBeans and decided that a graphical front end would proba-
bly be a good idea. This meant looking at the issue from proprietary software. As
IBM make their version available for download I chose a book that was specifically
about VisualAge for Java. Comes with 1.1.5 on a CD. Release 2 is available for
download.
Winder R., Roberts G., Developing Java Software, Wiley.
If you don't have a formal background in programming, algorithms and data struc-
tures, object oriented programming then I would suggest that you have a look at this
book.
Hunt J., Java and Object Orientation, Springer.
If you want an introduction to object oriented programming take a look at this one.
JDK 1.2.2 On-line documentation.
This is available on the college web server. Just follow the links. You can also
download and install to your own machine. This is the source of technical informa-
tion on Java.
Arnold K., Gosling J., The Java Programming language, Addison Wesley.
Written by two of the Java team. I normally try to get hold of a book by people who
have been behind the design of a programming language when trying to learn it.
This one is very disappointing.
Gosling, Yellin and the Java Team, The Java API, Volume 1, Core Packages, Addison Wes-
ley.
Paper definition of the application programming interface. Also available on-line but
obviously more difficult to use. Covers the core of the language. Out of date as soon
as I bought it! Not recommended. Persevere and use the on-line material instead.
Gosling, Yellin and the Java Team, The Java API, Volume 2, Window Toolkit and Applets,
Addison Wesley.
The second api text. Not recommended. Use the on-line material instead.
Flanagan, Java in a Nutshell, O'Reilly & Associates.
For people familiar with the Nutshell series this book is what one would expect. It
offers an introduction to Java, programming with the Java api, a language reference
and api quick reference. If you had to buy one book then this is one to consider.
email: [email protected] © Ian D Chivers
Chapter 1 Overview 22
Aims
The primary aim of this chapter is to look at some of the languages used in the sci-
ences. There is a look at the developments from a historical view point; a compari-
son of their features and a look at future developments.
Chapter 2 An Introduction to Programming Languages 24
and Object Oriented Programming
2.2 Pascal, 1975, ANSI & BSI 1982, ISO 1983, Extended Pascal 1991?
Very successful attempt at a teaching language. Note that it precedes both C and Fortran
77. Pascal still is the most widely taught programming language in computer science de-
partments, as the introductory programming language. The following summarises the survey
done by Dick Reid taken from a number of editions:–
Language 20th 18th 15th 13th
Pascal 140 144 151 157
C++ 101 100 87 34
Ada 82 82 74 73
C 58 56 51 39
Scheme 50 49 51 50
Modula 32 32 32 35
Java 15 - - -
Modula-2 14 15 15 13
Fortran 9 9 9 8
SML 8 7 6 6
Turing 4 4 5 6
Miranda 4 4 4 3
Smalltalk 4 4 4 1
Eiffel 3 3 3 3
Oberon 3 3 2 2
ISETL 2 2 2 2
ML 2 2 2 1
Modula-3 2 2 2 2
ObjPascal 2 2 2 1
Ada95 2 - - -
Haskel 2 1 1 1
Beta 1 1 1 1
Oberon-2 1 1 1 -
Orwell 1 1 1 1
Prolog 1 1 1 1
© Ian D Chivers email: [email protected]
25 An Introduction to Programming Languages Chapter 2
and Object Oriented Programming
Simula 1 1 1 1
Blue 1 - - -
The first edition was May 1990. New editions come out about every six months. He doesn't
keep past editions. I've put up the complete survey, which includes the institutions, at:–
http://www.kcl.ac.uk/kis/support/cc/fortran/dickreid20.txt
What is interesting is the following:–
http://www.kcl.ac.uk/kis/support/cc/fortran/sdickreid20.txt
which is a sorted list by language. Where is your institution?
Annex G, Numerics
Annex H, Safety and Security
2.12 Java
Bill Joy (of Sun fame) had by the late 1980's decided that C++ was too complicated and
that an object oriented environment based upon C++ would be of use. At round about the
same time James Gosling (mister emacs) was starting to get frustrated with the implementa-
tion of an SGML editor in C++. Oak was the outcome of Gosling's frustration.
Sun over the next few years ended up developing Oak for a variety of projects. It wasn't un-
til Sun developed their own web browser, Hotjava that Java as a language hit the streets.
And as the saying goes the rest is history.
Java is a relatively simple object oriented language. Whilst it has its origins in C++ it has
dispensed with most of the dangerous features. It is OO throughout. Everything is a class.
It is interpreted and the intermediate byte code will run on any machine that has a Java vir-
tual machine for it. This is portability at the object code level, unlike portability at the
source code level – which is what we expect with most conventional languages.
It has built in garbage collection – no dispose!
It has no pointers – everything is passed by reference!
It is multithreaded, which makes it a delight for many applications.
It has a extensive windows toolkit, the so called AWT that was in the original release of the
language and Swing that came in later. It achieves much of what Visual Basic offers but
within the framework of a far more powerful language. Development environments are be-
coming widely available to aid in this task.
Finally it is fun!
Major drawback is the rapid development of the language and the large number of different
versions. Further compounded by the different virtual machines available.
Dates
Fortran: The dates are the dates of the standards.
Pascal: Preliminary version 1968. Major development and first operational compiler 1970.
1973 publication of first revised report. User Manual and Report 1975.
Modula: Defined experimentally 1975. Lilith research project 1977. First implementation of
Modula 2 1979. Technical report March 1980. First distributed compiler March 1981. Pro-
gramming in Modula 2 1982.
Oberon 2: 1988, N. Wirth. The Programming Language Oberon, Software Practice and Ex-
perience, 1991, Mossenbeck and Wirth, The Programming Language Oberon 2. 1991,
Reisser , The Oberon System, User Guide and Programmer's Manual. 1993, Mossenbeck,
Object Oriented Programming in Oberon 2.
C: 1969, M Richards: BCPL A Tool for Compiler Writing and Systems Programming. 1970,
Ken Thompson, B. 1978, K and R. The C Programming Language,. 1989 ANSI C Stan-
dard.
C++: C with classes, 1979-1983 From C with Classes to C++, 1982-1985 Release 2.0:
1985-1988 Stroustrup, The C++ Programming Language, 1st edition, 1986 Stroustrup, The
C++ Programming Language, 2nd edition, 1991. Standard 1997.
Ada: 1980 original definition. Standard 1987. Latest standard is 1995.
Java: Exact date not well defined. Hopefully the standardisation effort will make life easier!
tween one type and another. The explicit type casting required in some languages means
that they are not widely used for numeric programming.
At the next level the ability to call in built functions with numeric data of one or more
types. This has been in Fortran from a very early stage.
Finally the ability to create one's own functions that accept numeric data of a variety of nu-
meric types.
Languages that support OOP have to offer the last kind of polymorphism.
General Polymorphism
OO programming languages have to offer this functionality.
2.15.7 Modules
The primary purpose of modules is to provide the ability to group related functions and pro-
cedures. This is a powerful program decomposition tool. They normally have a well con-
trolled mechanism for making visible what the external, calling routine needs to have access
to.
Terminology varies with programming languages, and so does the exact functionality that
these different languages support.
Classes and packages are two terms also used.
2.15.8 Pointers and References
Pointers in a programming language extend the range of problems that can be solved con-
siderably. Multi-dimensional structures are easily programmed using pointers, e.g. linked
lists, queues, trees, quad-trees, oct-trees etc.
The major problem is that the user is provided with very little help if they are programmed
incorrectly. It is assumed that you know what you are doing.
In Java all objects are accessed via an object reference. When you see an object variable in
a Java program you actually see a reference to an object. We will look into the concept of
references in much greater detail throughout the course.
2.15.9 Procedure Variables
An elegant way of extending the expressive power of a language. Quite old.
2.15.10 Inheritance
The first of the two major step towards OO programming. Allows the user to extend an ex-
isting type without having to know what is going on.
2.15.11 Dynamic Binding
The second of the two major features of OO programming. Provided in a limited sense via
procedure variables in older languages.
2.15.12 Operator Overloading
Syntactic sugar in many ways and over valued. Very useful to people with numeric prob-
lems. Given that C++ has 47 operators it poses problems of readability and comprehensibil-
ity with most other areas. The restrictions that C++ has in this area will be looked at later.
2.15.13 Threads/Multitasking
Multitasking and/or threads are needed in a programming language when solving problems
in the areas of real-time systems, equipment interfacing, embedded systems and parallel
programming.
2.18.1 Parallel Fortran – Fortran 95, Fortran 2000, SMP, MPI, HPF
To quote from the HPF Language Specification, version 1.1, November 1994 The High
Performance Fortran Forum (HPFF) was founded as a coalition of industrial and aca-
demic groups working to suggest a set of standard extensions to Fortran to provide the nec-
essary information. Its intent was to develop extensions to Fortran that provide support for
high performance programming on a wide variety of machines, including massively parallel
SIMD and MIMD systems and vector processors. From its very beginning HPFF included
most vendors delivering parallel machines, a number of government laboratories and many
university research groups. Public input was encouraged to the greatest possible extent.
A number of suppliers now provide HPF Fortran extensions and these are generally based
on Fortran 90, rather than Fortran 77.
Fortran 95 and 2000 offer support for parallelisation.
SMP and MPI are two other developments in this area.
2.18.2 Parallel C++
Similar developments are in the pipeline for C++.
features of that language and add a very small number of features. The outcome was
Oberon. The language was defined in 1986.
The object code size of the outer core of the Oberon system is 200K, and comprises
a kernel
a dynamic loader and garbage collector
a file system
drivers for disk, diskette, asynchronous and synchronous communication, printer
and a bit mapped display;
local network services;
support for texts and fonts;
a window subsystem;
a text editor;
the Oberon compiler;
Educational versions of the system are available from the ETH ftp server. I'd recommend
8Mb of memory and an 80486 with 1024*756 display. I've tried at home on a 20 MHz
80386 with 5 Mb of memory – a bit slow... Well worth a look at.
Programming in Oberon, Reiser and Wirth, is a good introductory text and combined with
OOP in Oberon 2, Mossenbeck, you have sufficient information to get started.
There is a lot of documentation that comes with the system and this can be printed.
The system integrates very well with both Windows on the PC and Apple macs. Versions
for other platforms are available.
If your are familiar with Pascal or Modula 2 then I'd recommend Oberon very highly to see
what OOP has to offer. Very low cost in time, effort and money.
2.20.6 Ada 95
Whilst I do not have access yet to an Ada 95 compiler from what I've read it looks a very
good language. The standard is available from a number of ftp servers, and there is also a
look at the changes from the original version to 95 available on the web. A text I'd recom-
mend is Programming in Ada 95, Barnes. This is well written. Ada 95 is the first language
that has been standardised with OOP in mind.
If you want a job in the defence industries, or see yourself working with real time embed-
ded systems then this is certainly a language to consider looking at.
2.20.7 Java
Java is a recent OO language. It is unusual in that it is the product of one company, Sun,
rather than the subject to formal language standardisation like the majority of the other lan-
guages covered in this chapter. It is hoped that it will pass out of Sun's hands in the near fu-
ture into the mainstream of language standardisation. Freely available if you have internet
access. IBM have taken it on board in a big way and so have Microsoft. They both realise
the potential earning capacity of Java and the internet.
Due to long file names and multithreading requirements needs operating systems like Win-
dows 95 and above.
genericity
design by contract
exception handling
supporting mechanisms
inheritance
multiple inheritance
inheritance techniques
typing
global obects and constants
Programming is an engineering activity and has evolved considerably since the first pro-
gramming languages of the 1950's. The changes between the first and second editions re-
flect the developments that have taken place over nearly 10 years. This book is essential
reading if you are seriously interested in objected oriented programming.
2.22.2 Rumbaugh et al
This book concentrates on OO modelling, rather than using a particular programming lan-
guage for OO programming. If you have a background in the relational database area then
much of the coverage should be quite familiar. They present a methodology for object ori-
ented development – the Object Modelling Technique or OMT. They identify four stages:–
analysis: build a model of the real world situation;
system design: make the high level decisions about the overall architecture;
object design: build a design model (based on the analysis model) with imple-
mentation details;
implementation: translate into an implementation using a particular programming
language, database, or hardware implementation;
and three kinds of models to describe the system:–
the object model: describes the static structure of the objects and their relation-
ships;
the dynamic model: describes the aspects of the system that change with time;
the functional model: describes the data value transformations within the system;
and the three models are orthogonal, with cross links.
This book is a must for large scale systems.
2.22.3 Practical Steps
The two major practical steps are:–
identify the classes; within this discriminate between:–
an is a relationship, e.g. where one class is a sub-type of
another;
Consider the concept of a point. It has two attributes,
an x and y position. So we could write point(x,y). Now
consider the concept of a pixel – a point with the
return(0)
}
We can now add another shape, e.g. circle, and still have things work without recompiling
the old code. We just compile the new move and draw procedures and link them in. The
method resolution is handled by dynamic binding. We will look into this in greater depth
later in the course.
One major step forward is in reusable software components. This can be seen as an exten-
sions to the object oriented approach to programming.
Consider building an application that required a spelling checker. The idea is to buy one of
the shelf and slot it straight in to our program. This is gradually becoming a reality.
Sun and Microsoft both made developments in this area and we will look at each in turn.
2.24.3.1 COM, OLE, ActiveX
First let us define each of the above in turn:–
COM – Component Object Model
OLE – Object Linking and Embedding
ActiveX – Now called Active Technologies
Let is look briefly at each in turn.
ActiveX is a set of technologies that enables software components to interact with one an-
other in a networked environment, regardless of the language in which they were created.
ActiveX is build on the Component Object Model.
OLE or OLE Automatation makes it possible for one application to manipulate objects im-
plemented in another application or to expose objects so that they can be manipulated.
A simple example of this would be embedding a spreadsheet of graph from Excel in a
Word document. Double clicking on the spreadsheets drops you into Excel. There are some
problems with this when working with a document on a number of computer systems with
different versions of the applications concerned.
The Component Object Model (COM) is a platform independent, distributed, object
orientded, system for creating binary software documents that can interact. COM is the
foundation technology for OLE and ActiveX.
2.24.3.2 JavaBeans
JavaBeans is the Java language software component offering. JavaBeans extends the Java
language write once run everywhere capability to resuable component development.
There is considerable interest in JavaBeans because of the platform neutrality of the devel-
oped code. Sun also provide mechanisms to migrate ActiveX/OLE/COM to JavaBeans.
Sun and Microsoft and battling this one out and there is little love lost between them.
Watch this space as they say!
2.25 Coda
There is a lot that John Backus has to be proud of. He achieved a lot with Fortran. As we
shall see Fortran is still the language of first choice for the majority of numeric based prob-
lem solving. There is a lot of very well written code in Fortran, and we find both commer-
cial and public domain numeric libraries available for most platforms.
Wirth has a lot to be proud of too with the Algol family of languages – Algol, Algol W,
Pascal, Modula, Modula 2, Oberon, Oberon 2. The sad thing that is that whilst abandoning
the previous language enabled successor languages to be well designed and compact, there
was a lot of effort required in moving production code from older languages to their succes-
sors. Knowledge of one of the more recent languages (Modula 2 or Oberon) in this family
is a worthwhile investment.
C and C++ have a considerable amount of code written in them. C++ represents a very ma-
jor advance over C, correcting some of the program correctness problems that arise in C
from array subscript checking, pointer manipulation, type checking and optimisation prob-
email: [email protected] © Ian D Chivers
Chapter 2 An Introduction to Programming Languages 40
and Object Oriented Programming
lems with pointer aliasing and array handling. For many applications they offer quite signif-
icant advantages over other languages. Graphical based systems are invariably written in
C++. Object oriented programming is often done in C++. The maintenance problems C
poses are considerable. The steep learning curve that C++ has poses problems for succes-
sive generations of would be C++ programmers.
Look at the Computational Science Education paper for an comparison of C, Fortran 77,
Fortran 90 and C++. This is on the college web server.
Whither Java? Java seems to be a language that will survive. How widely used it will be-
come depends obviously on the success of the internet and local intranets.
Whither Visual Basic? VB will survive. Many people need to be able to develop easy to use
programs and systems. Windows programs offer the possibility of solving this problem.
No one language is appropriate for solving every problem. Many factors come into play in
real life. Learning a variety of languages is a good idea. Learning Fortran 90, C++, Java
and Visual Basic provides you with a range of very useful skills for work in the academic,
scientific, engineering and commercial worlds.
I've included references to a couple of other languages that you might like to look at, and
these are Icon, Snobol, Prolog and SQL. Icon and Snobol are very good string processing
languages. SQL is the database language, and Prolog is a logic based language.
2.26 Bibliography
Adobe Systems Incorporated, Postscript Language: Tutorial and Cookbook, Addison Wes-
ley.
Adobe Systems Incorporated, Postscript Language: Reference Manual, Addison Wesley.
Adobe System Incorporated, Postscript Language: Program Design, Addison Wesley.
•The three books provide a comprehensive coverage of the facilities and capabili-
ties of Postscript.
ACM SIG PLAN, History of Programming Languages Conference – HOPL-II, ACM Press.
• One of the best sources of information on programming language developments,
from an historical perspective. The is coverage of Ada, Algol 68, C, C++, CLU,
Concurrent Pascal, Formac, Forth, Icon, Lisp, Pascal, Prolog, Smalltalk and Sim-
ulation Languages by the people involved in the original design and or imple-
mentation. Very highly recommended. This is the second in the HOPL series,
and the first was edited by Wexelblat. Details are given later.
Adams, Brainerd, Martin, Smith, Wagener, Fortran 90 Handbook: Complete ANSI/ISO Ref-
erence, McGraw Hill.
• A complete coverage of the language. As with the Metcalf and Reid book some
of the authors were on the X3J3 committee. Expensive, but very thorough.
Annals of the History of Computing, Special Issue: Fortran's 25 Anniversary, ACM publi-
cation.
• Very interesting comments, some anecdotal, about the early work on Fortran.
Arnold K., Gosling J., The Java Programming Language, Addison Wesley.
• Written by the people who designed and implemented the language. A definitive
source on the language. A bit expensive at just under thirty uk pounds.
guages which I have adopted and developed over a number of years, namely that
the primary purpose of a programming language is to help the programmer in
the practice of his art.
Jenson K., Wirth N., Pascal: User Manual and Report, Springer Verlag.
• The original definition of the Pascal language. Understandably dated when one
looks at more recent expositions on programming in Pascal.
Kemeny J.G., Kurtz T.E., Basic Programming, Wiley.
• The original book on Basic by its designers.
Kernighan B. W., Ritchie D. M., The C Programming Language, Prentice Hall: Englewood
Cliffs, New Jersey.
• The original work on the C language, and thus essential for serious work with C.
Kowalski R., Logic Programming in the Fifth Generation, The Knowledge Engineering Re-
view, The BCS Specialist Group on Expert Systems.
• A short paper providing a good background to Prolog and logic programming,
with an extensive bibliography.
Knuth D. E., The TeXbook, Addison Wesley.
• Knuth writes with an tremendous enthusiasm and perhaps this is understandable
as he did design TeX. Has to be read from cover to cover for a full understand-
ing of the capability of TeX.
Lemay L., Perkins, Teach Yourself Java in 21 Days, Sams net.
• Most gentle of the books I've found. Includes a CD with the Sun JDK.
Lyons J., Chomsky, Fontana/Collins, 1982.
• A good introduction to the work of Chomsky, with the added benefit that
Chomsky himself read and commented on it for Lyons. Very readable.
Malpas J., Prolog: A Relational Language and its Applications, Prentice-Hall.
• A good introduction to Prolog for people with some programming background.
Good bibliography. Looks at a variety of versions of Prolog.
Marcus C., Prolog Programming: Applications for Database Systems, Expert Systems and
Natural Language Systems, Addison Wesley.
• Coverage of the use of Prolog in the above areas. As with the previous book
aimed mainly at programmers, and hence not suitable as an introduction to
Prolog as only two chapters are devoted to introducing Prolog.
Metcalf M. and Reid J., Fortran 90 Explained, Oxford Science Publications, OUP.
• A clear compact coverage of the main features of Fortran 8x. Reid was secretary
of the X3J3 committee.
Meyer B., Object Oriented Software Construction, Prentice Hall.
• I'm just got the second edition. The first edition is dated 1988. Whilst obviously
Eiffel based well worth a read. Also looks at other languages. This comparision
is not as good as it could be.
Wiener R., Software Development Using Eiffel: There Can be Life After C++, Prentice
Hall.
• Very well written. I'd really recommend getting hold of this book if you are go-
ing to seriously program in C++ using oo techniques. He teaches both academic
and commercial Eiffel and C++ courses. He knows his stuff!
Winder R., Roberts G., Developing Java software, Wiley.
• Waiting to get a copy.
Wirth N., An Assessment of the Programming Language Pascal, IEEE Transactions on
Software Engineering, June 1975, 192-198.
Wirth N., Program Development by Stepwise Refinement, Communications of the ACM,
April 1971.
• Clear and simple exposition of the ideas of stepwise refinement.
Wirth N., History and Goals of Modula 2, Byte, August 1984, 145-152.
• Straight from the horse's mouth!
Wirth N., On the Design of Programming Languages, Proc. IFIP Congress 74, 386-393,
North Holland, Amsterdam.
Wirth N., The Programming Language Pascal, Acta Informatica 1, 35-63, 1971.
Wirth N., Modula: a language for modular multi- programming, Software Practice and Ex-
perience, 7, 3-35, 1977.
Wirth N., Programming in Modula 2, Springer Verlag.
• The original definition of the language. Essential reading for anyone considering
programming in Modula 2 on a long term basis.
Wirth N. Type Extensions, ACM Trans. on Prog. Languages and Systems, 10, 2 (April
1988), 2004-214
Wirth N. From Modula 2 to Oberon, Software – Practice and Experience, 18,7 (July 1988),
661-670
Wirth N., Gutknecht J., Project Oberon: The Design of an Operating System and Compiler,
Addison Wesley.
• Fascinating background to the development of Oberon. Highly recommended for
anyone involved in large scale program development, not only in the areas of
programming languages and operating systems, but more generally.
2.27 Problems
What programming languages are available on the system you work with?
'Plenty of practice' he went on repeating, all the time that Alice was getting him on
his feet again. 'plenty of practice.'
The White Knight, Through the Looking Glass and What Alice Found There, Lewis
Carroll.
Aims
3 An Introduction to Java
In this chapter we will look at three simple program examples. The first looks at a simple
hello world example, the second a simple text i/o and the third looks at simple numeric i/o.
We will also look at variants of these programs that occur with Java depending on whether
we want to write a Java program or a Java applet that runs within a web browser. We will
also look at the flavours of doing this that exist within Java due to the evolution of the lan-
guage.
We will also look at some of the syntax of Java programs.
Within a class we have one or more procedures and data. In Java terminology these are
methods and fields.
The { character signifies the start of the class.
The public static void main(String[] args) statement signifies that this is
a Java program. We will look at turning the above into an applet in the next example.
The c0301 class contains one method – main. This method returns a value of void. There is
the concept of functions and procedures in other languages with functions like sine return-
ing a value, but within the C/C++/Java family of languages we just have functions and
when they behave as a procedure or subroutine in another language they are void, and re-
turn a void data type.
This method is static. We will look in more depth a full coverage of static throughout the
course. For the time being all that is necessary to know is that if we are writing Java pro-
grams that the main method has to be static.
This method has the public attribute. This means that the method is visible whereever the
class is used.
The main method takes one argument or parameter, args and this is of type String[].
This enables the program to access data typed at the command line. We will look at arrays
of type String in much greater depth throughout the course.
We then have the { character signifying the start of the main method. There is one state-
ment in this method and that is System.out.println(" Hello world"). Let us
look at this statement in more depth. With object oriented languages there are the twin con-
cepts of objects and methods. What we are doing is invoking the println method on the
System class's out object.
With Java there is the concept of the core language and additional functionality is provided
by a number of built in classes. Much work has been done with Java to provide a lot of
functionality with these additional in built classes. It is essential to develop a good working
knowledge of what has already been provide. There is little point reinventing the wheel.
This is achieved in C and C++ using the #include statement.
Text or strings are delimited in Java with " marks.
; is the statement seperator in Java.
The } character signifies the end of the program.
There are a number of issues that are important whilst preparing java programs:–
the file name of the java program or applet must be the same as the class name
if using more than one platform then stick to an operating system that supports
long file names. This means that using Windows 3.x is not recommended.
java is case sensitive – I go against the normal style in java texts and stick to
lower case. I also use short names.
compile you java program using
javac c0301.java
run your programs using the java interpreter
java c0301.class
import java.awt.*;
but in this example we have not bothered overriding them, rather we have relied on default
behaviour.
Within our applet we have one method:–
public void paint(Graphics g)
and the method is public and void. The paint method takes one parameter and this is an ob-
ject g of type Graphics, which is one of the data types provided.
Within this method we have one statement:–
g.drawString(" Hello world",10,20);
and this applies the drawString method to the object g. The arguments to drawString are:–
" Hello world" – the string we want to appear on the screen
10 – the x position in pixels
20 – the y position in pixels
The } character signifies the end of the applet.
The outcome of all of this is that we now have an applet that we can run within a web
browser, e.g. netscape. This is not the end of the story however. We also need an html file
that can be loaded into the browser. HyperText Markup Language (HTML) is a markup lan-
guage and is based on SGML, which is an ISO standard. Within HTML terms a document
comprises two parts, the text and the markup. Markup languages are not new and TeX and
Runoff are two widely used markup languages. HTML is widely used and is the basis for
the World Wide Web (WWW) distributed information system. The web was originally de-
veloped at the European Particle Physics Laboratory (CERN) in Geneva to enable
high-energy physics researchers to work collaboratively on online documentation; it soon
became apparent that the system could be useful to a broader section of the population, and
the software became publicly available in 1991.
Here is the html file associated with this simple applet.
<html>
<head>
<title Hello World ></title>
</head>
<body>
<applet code=c0301a.class width=300 height=100></applet>
</body>
</html>
This simple html file uses a number of tags
<html> – an instruction to the web browser that this is an html document;
<head> – the heading
<title> – the title of the document which appears somewhere within the browser.
Also appears in a booklist.
<body> – the main body of the document
<applet> – used to signify a java applet
More infomation can be found on html on the College web server. There are links to some
very good coverages of html. You need to have a good working knowledge of html if you
are interested in Java applets. They key tag in the above is the applet tag. Let us look at this
in more depth:–
class c0302
{
public static void main(String[] args)
{
try
{
InputStream i=System.in;
DataInputStream in=new DataInputStream(i);
String Line;
System.out.println(" Type in a line of text ");
Line=in.readLine();
System.out.println(Line);
}
catch(IOException e)
{ System.out.println(" Exceptions raised: " + e); }
}
}
In this example we are interested in doing i/o. In the previous program and applet we only
did output. We first import from java.io to make available in shortened name form the vari-
ous facilities we need.
The next thing is the name of the class – c0302. Remember java is case sensitive and the
file name must match the class name.
We then have the standard statement for a java program:–
class c030301
{
public static void main(String[] args)
{
try
{
InputStream i=System.in;
DataInputStream in=new DataInputStream(i);
String Line;
float f=1.0f;
Float F=new Float(f);
System.out.println(" Type in a number ");
Line=in.readLine();
F=Float.valueOf(Line);
f=F.floatValue();
System.out.println(f);
}
catch(IOException e)
{ System.out.println(" Exceptions raised: " + e); }
}
}
Let us look at statement in turn.
class c030301
This is the name of our class. Remember that the file name used at the operating system
side must be the same.
public static void main(String[] args)
This signifies that this is a Java program. This is the standard Java program statement.
try
We are doing i/o so we must use try and catch to trap errors.
InputStream i=System.in;
I is a variable or object of type InputStream and it has an inital value of System.in.
DataInputStream in=new DataInputStream(i);
in is an object of type DataInputStream and it is created using new DataInputStream(i).
String Line;
Line is of type String.
float f=1.0f;
f is a numeric variable of type float. It is given an initial value of 1.0 – note the f extension
on the initial value. All numeric variables are of type double by default in Java.
Float F=new Float(f);
F is an object of type Float. There is the concept in Java of fundamental data types and ob-
jects. For each fundamental data type there is a corresponding object. so float and Float are
two very different concepts. This object is given an inital value by the new Float(f) state-
ment.
System.out.println(" Type in a number ");
This prints a text prompt on the screen.
Line=in.readLine();
This reads in the text that the user types into Line. All interaction is done using String ob-
jects.
F=Float.valueOf(Line);
This statement extracts the numeric value from the text typed in. Note that line is of type
String and hence is an object and we are extracting an object of type Float from this text
string.
f=F.floatValue();
This converts from a Float object to the build in float data type.
System.out.println(f);
This statement echos the numeric value back to the user.
catch(IOException e)
In the event of an i/o error control passes to this statement.
{ System.out.println(" Exceptions raised: " + e); }
In the event of an error the above message appears on the screen.
As you have all programmed using other languages the above appears very long winded.
Something we take for granted – numeric i/o – has become seemingly unreasonably com-
plex.
This is the syntax of Java. This is what you have to adapt to if you want to become profi-
cient in Java. Learning a second natural language is difficult at first.
3.14 Summary
Don't be put off by the syntax of Java. It doesn't take long to get on top of that syntax. You
wouldn't expect natural languages to have identical syntax and semantics, so why expect it
from programming languages.
3.15 Bibliography
I've broken down this into three areas. It is essential to get hold of additional sources in the
first two areas, and very useful in the third.
3.15.1 Java
As with most programming langauges it is useful to make the following distinctions:–
language tutorial and examples
language reference
language algorithms
The aims of the notes are to provide a brief coverage of the first and second areas. There
are little or no sources at this time of algorithms in Java.
Look at the web pages for more details of on-line sources. There are a lot of these. There
are a lot of good complete example programs.
3.15.2 HTML
Use the pointers on the college web pages. Most of these are free – you only have to pay
for the printing.
3.16 Problems
1. Type in the examples in this chapter. You will invariably make typing mistakes. Look at
the error messages that the compiler give you. The compiler gives error messages from their
view point. Make an attempt to understand what this means.
2. What happens with the first example with characters outside of the ASCII character set?
Does the screen representation of these characters match the printed representation? Why do
you think that is?
3. With the example what happens to so called white space, i.e spaces, tabs, and carriage re-
turns?
4. With the numeric example experiment with the number format, i.e. use integers, reals,
exponential format. What happens?
5. Write a program that will read in your name and address and print them out in reverse
order.
Samuel Johnson.
Aims
}
}
Let us look at this program in some detail.
class c0401
Class name.
public static void main(String[] args)
Standard program header.
byte i_b = 1;
Variable declaration and initialisation.
short i_s = 1;
Variable declaration and initialisation.
int i= 1;
Variable declaration and initialisation.
long l_l = 1;
Variable declaration and initialisation.
System.out.print(i_b);System.out.print(" ");
Standard mechanism to print to the screen. The print method can only take one argument.
There are several print methods – one for each built in type. This makes i/o seem a little
verbose compared to more conventional programming languages.
System.out.print(i_s);System.out.print(" ");
Print short.
System.out.print(i);System.out.print(" ");
Print int.
System.out.print(i_l);System.out.println();
Print long.
for (int count=1;count<33;++count)
Java and C++ syntax of a for loop. We are allowed to declare and initialise variables with a
for statement. In this case we introduce a new variable count and initialise to 1. The ; is a
statment terminator. count < 33 means repeat the loop whilst count is less than 33. ++count
means increment count by 1 each time round the loop.
i_b = (byte)(i_b * 2)
In this example we are forced to cast the expression i_b*2 from its default type of int back
to byte. This is because an integer literal (a number) has a default type of int. Hence the 2
forces the expression i_b*2 to be promoted to be of type int. This is the Java syntax for
casting.
i_s = (short)(i_s * 2)
In this example we are forced to cast the expression i_s*2 from int to short.
i = i * 2
Familiar arithmetic expression and assignment.
i_l = i_l * 2
Familiar arithmetic expression and assignment. In this case 2 is promoted to type long by
Java automatically.
System.out.print(i_b);System.out.print(" ");
System.out.print(i_s);System.out.print(" ");
System.out.print(i);System.out.print(" ");
System.out.print(i_l);System.out.println();
Print out the values.
The for loop will terminate when count reaches 32.
class c0403
{
public static void main(String[] args)
{
int i=2+3*4;
System.out.println(i);
}
}
The program prints out 14.
4.8.2 Operators, Precedence and Associativity.
The following table summarises the rules concerning precedence and associativity. All oper-
ators associate left to right except for those in the third and eighteenth position in the prece-
dence hierarchy, i.e. the unary and assignment operators.
Operator Summary
. member selection object.member
[] subscripting [expr]
() function call expr (expr_list)
++ post increment expr ++
— post decrement expr —
++ pre increment ++ expr
— pre decrement — expr
~ complement ~ expr
! not ! expr
- unary minus - expr
+ unary plus + expr
new new new object
() cast (type) expr
* multiply expr * expr
/ divide expr / expt
% modulo or remainder expr % expr
+ plus expr + expr
- minus expr - expr
<< shift left expr << expr
>> shift right, sign extend expr >> expr
>>> shift right, zero fill expr >>> expr
< less than expr < expr
<= less than or equal expr <= expr
> greater than expr > expr
>= greater than or equal expr >= expr
instanceof instanceof object instanceof object
== equal expr == expr
!= not equal expr != expr
System.out.println(i);
System.out.println(j);
System.out.println(k);
System.out.println(l);
}
}
What do you think will be the output of this program? Do we need four ways of achieving
the same thing in a programming language?
This example is taken from the Fortran 90 text. It is a direct translation.
class c0407
{
static final float light_year = (float)(9.46*10E12) ;
{
float light_minute;
float distance;
float elapse ;
int minute ;
int second ;
light_minute = light_year/(float)(365.25 * 24.0 * 60.0);
distance = (float)(150.0 * 10E6) ;
elapse = distance / light_minute ;
minute = (int)elapse ;
second = (int)(( elapse - minute ) * (float)60) ;
System.out.print(" Light takes ");
System.out.print(minute);
System.out.print(" minutes");
System.out.print(" ");
System.out.print(second);
System.out.println(" seconds");
}
}
Let us look at each line in turn.
class c0407
Standard class definiton.
static final float light_year = (float)(9.46*10E12) ;
This is the way that you define light_year to be a constant or parameter. The two additional
keywords are static and final.
The initial value looks a little strange. Remember that real numbers are double by default in
Java. We thus have to cast the expression (9.46*10E12) to a float. Note that we have to use
brackets around the numeric expression as we are interested in casting the result of the
whole expression.
public static void main(String[] args)
Standard start of program.
float light_minute;
float distance;
float elapse ;
int minute ;
int second ;
Standard variable declarations.
light_minute = light_year / (float)( 365.25 * 24.0 * 60.0 );
Assign value to light_minute. Part of the expression looks a little odd at first. We are doing
the complete expression as double and then casting the result to float.
distance = (float)(150.0 * 10E6) ;
Calculate distance – again cast from double to float.
elapse = distance / light_minute ;
Simple assignment.
minute = (int)elapse ;
Assignment with cast.
second = (int)(( elapse - minute ) * (float)60) ;
Assignment with cast. Notice the additional brackets to force the cast of the whole expres-
sion.
System.out.print(" Light takes ");
System.out.print(minute);
System.out.print(" minutes");
System.out.print(" ");
System.out.print(second);
System.out.println(" seconds");
Print out the answer.
The example looks a little unpleasant do to the requirment to cast from the various default
types. Let us now look at a slight variant using double throughout.
class c0408
{
static final double light_year = 9.46*10E12 ;
{
double light_minute , distance , elapse ;
int minute , second ;
light_minute = light_year / ( 365.25 * 24.0 * 60.0 ) ;
distance = 150.0 * 10E6 ;
elapse = distance / light_minute ;
minute = (int)elapse ;
second = (int)(( elapse - minute ) * 60) ;
System.out.print(" Light takes ");
System.out.print(minute);
System.out.print(" minutes");
System.out.print(" ");
System.out.print(second);
System.out.println(" seconds");
}
}
Better – now look at the last variant.
class c0409
{
static final float light_year = 9.46f*10E12f ;
{
float light_minute;
float distance;
float elapse ;
int minute ;
int second ;
light_minute = light_year/(365.25f * 24.0f * 60.0f) ;
distance = 150.0f * 10E6f ;
elapse = distance / light_minute ;
minute = (int)elapse ;
second = (int)(( elapse - minute ) * 60f) ;
System.out.print(" Light takes ");
System.out.print(minute);
System.out.print(" minutes");
System.out.print(" ");
System.out.print(second);
System.out.println(" seconds");
}
}
So the recommendation would seem to be to do all real arithmetic as double, rather than
have to cast all the time or append all variables with f. If your program is heavy on numeric
computation would you be using Java anyway?
4.10 Char
Characters are Unicode based in Java. Given the large number of natural languages in the
world and the requirements of the publishing world several companies got togthor and
formed Unicode Inc, a non-profit making consortium to draw up a standard for international
character sets. ISO was tackling the same probelm and the outcome was the Unicode Stan-
dard.
As Unicode is 16 bit based it can handle 65,536 distinct characters, which is enough for
most if not all languages in use today plus a number of older or arcane languages, e.g.
Egyptian hieroglyphs.
Note that not all computer systems can necessarily handle the display of the full Unicode
character set.
The bibliography contains some pointers to sources of information regarding Unicode. I've
also printed out the following:–
ASCII character set – 7 bit
ISO Latin 1 – 8 bit
4.11 Boolean
This is the last primitive data type supported in Java. Values are eithor true or false.
}
}
4.13 Summary
There are the following primitive data types in Java:–
boolean – true or false
char – 16 bit Unicode character
byte – 8 bit signed integer
short – 16 bit signed integer
int – 32 bit signed integer
long – 64 bit signed integer
float – 32 bit real: IEEE 754-1985
double – 64 bit real: IEEE 754-1985
Integer constants in expressions are of type int. Casting is required when doing integer
arithmetic using the other integer types.
Real constants are of type double. Casting is required when doing real arithmetic using float
types.
Java draws heavily on C and C++ for its operators and syntax.. If you have some back-
ground in these languages then this obviously helps. However there are no pointers in Java,
or explicit delete mechanisms to free memory. Java has a garbage collector.
Strings and arrays are not fundamental data types, they are objects and as such are covered
in separate chapters.
Constants are provided using the static final attributes.
There is a lot of material in this chapter. Don't panic. As the course progresses more and
more of it will stick.
4.14.2.2 Byte
The Byte class is the standard wrapper for byte values.
4.14.2.3 Character
The Character class wraps a value of the primitive type char in an object.
4.14.2.4 Character.Subset
Instances of this class represent particular subsets of the Unicode character set.
4.14.2.5 Character.UnicodeBlock
A family of character subsets representing the character blocks defined by the Unicode 2.0
specification.
4.14.2.6 Class
Instances of the class Class represent classes and interfaces in a running Java application.
4.14.2.7 ClassLoader
The class ClassLoader is an abstract class.
4.14.2.8 Compiler
The Compiler class is provided to support Java-to-native-code compilers and related ser-
vices.
4.14.2.9 Double
The Double class wraps a value of the primitive type double in an object.
4.14.2.10 Float
The Float class wraps a value of primitive type float in an object.
4.14.2.11 InheritableThreadLocal
This class extends ThreadLocal to provide inheritance of values from parent Thread to child
Thread: when a child thread is created, the child receives initial values for all
InheritableThreadLocals for which the parent has values.
4.14.2.12 Integer
The Integer class wraps a value of the primitive type int in an object.
4.14.2.13 Long
The Long class wraps a value of the primitive type long in an object.
4.14.2.14 Math
The class Math contains methods for performing basic numeric operations such as the ele-
mentary exponential, logarithm, square root, and trigonometric functions.
You make the fields and methods available by adding
import java.lang.Math.*
at the start of you program, and qualify the functions by preceding the function name with
Math. The following example illustrates the above with a simple trigonometric function.
class sine_example
{
public static void main(String[] args)
{
int angle_d=30;
float angle_r;
angle_r=((float)angle_d)*((float)Math.PI)/(float)180;
System.out.println(Math.sin(angle_r));
}
}
Run the program. What should be the value for the sine of 30 degrees?
Note that I've also left out the import. I recommend adding it as it clearly indicates what
parts of the class library you are using.
Fields
static double E The double value that is closer than any other to e, the base of
the natural logarithms.
static double PI The double value that is closer than any other to pi, the ratio of
the circumference of a circle to its diameter.
Methods
static double abs(double a) Returns the absolute value of a double value.
static float abs(float a) Returns the absolute value of a float value.
static int abs(int a) Returns the absolute value of an int value.
static long abs(long a) Returns the absolute value of a long value.
static double acos(double a) Returns the arc cosine of an angle, in the range of
0.0 through pi.
static double asin(double a) Returns the arc sine of an angle, in the range of -pi/2
through pi/2.
static double atan(double a) Returns the arc tangent of an angle, in the range of
-pi/2 through pi/2.
static double atan2(double a, double b) Converts rectangular coordinates (b, a) to
polar (r, theta).
static double ceil(double a) Returns the smallest (closest to negative infinity)
double value that is not less than the argument and is equal to a mathematical in-
teger.
static double cos(double a) Returns the trigonometric cosine of an angle.
static double exp(double a) Returns the exponential number e (i.e., 2.718...)
raised to the power of a double value.
static double floor(double a) Returns the largest (closest to positive infinity) dou-
ble value that is not greater than the argument and is equal to a mathematical in-
teger.
static double IEEEremainder(double f1, double f2) Computes the remainder op-
eration on two arguments as prescribed by the IEEE 754 standard.
static double log(double a) Returns the natural logarithm (base e) of a double
value.
static double max(double a, double b) Returns the greater of two double values.
static float max(float a, float b) Returns the greater of two float values.
static int max(int a, int b) Returns the greater of two int values.
static long max(long a, long b) Returns the greater of two long values.
static double min(double a, double b) Returns the smaller of two double values.
static float min(float a, float b) Returns the smaller of two float values.
static int min(int a, int b) Returns the smaller of two int values.
static long min(long a, long b) Returns the smaller of two long values.
static double pow(double a, double b) Returns of value of the first argument
raised to the power of the second argument.
static double random() Returns a random number greater than or equal to 0.0 and
less than 1.0.
static double rint(double a) returns the closest integer to the argument.
static long round(double a) Returns the closest long to the argument.
static int round(float a) Returns the closest int to the argument.
static double sin(double a) Returns the trigonometric sine of an angle.
static double sqrt(double a) Returns the square root of a double value.
static double tan(double a) Returns the trigonometric tangent of an angle.
static double toDegrees(double angrad) Converts an angle measured in radians to
the equivalent angle measured in degrees.
static double toRadians(double angdeg) Converts an angle measured in degrees
to the equivalent angle measured in radians.
4.14.2.15 Number
The abstract class Number is the superclass of classes Byte, Double, Float, Integer, Long,
and Short.
4.14.2.16 Object
Class Object is the root of the class hierarchy.
4.14.2.17 Package
Package objects contain version information about the implementation and specification of
a Java package.
4.14.2.18 Process
The Runtime.exec methods create a native process and return an instance of a subclass of
Process that can be used to control the process and obtain information about it.
4.14.2.19 Runtime
Every Java application has a single instance of class Runtime that allows the application to
interface with the environment in which the application is running.
4.14.2.20 RuntimePermission
This class is for runtime permissions.
4.14.2.21 SecurityManager
The security manager is a class that allows applications to implement a security policy.
4.14.2.22 Short
The Short class is the standard wrapper for short values.
4.14.2.23 String
The String class represents character strings.
4.14.2.24 StringBuffer
A string buffer implements a mutable sequence of characters.
4.14.2.25 System
The System class contains several useful class fields and methods.
4.14.2.26 Thread
A thread is a thread of execution in a program.
4.14.2.27 ThreadGroup
A thread group represents a set of threads.
4.14.2.28 ThreadLocal
This class provides ThreadLocal variables.
4.14.2.29 Throwable
The Throwable class is the superclass of all errors and exceptions in the Java language.
4.14.2.30 Void
The Void class is an uninstantiable placeholder class to hold a reference to the Class object
representing the primitive Java type void.
You must look at the on-line documentation for more details of what are in these classes.
4.15 Bibliography
IEEE 754-1985
The standard is the definitive statement. Other sources include Suns Numerical Computa-
tion Guide. Similar publications will exist for other platforms.
What Every Computer Scientist Should know About Floating Point Arithmetic
This paper first appeared in the March 1991 issue of Computing Surveys, ACM Inc. It can
also be found (after some rumaging around) on Sun systems. I recommend the paper very
highly.
4.16 Problems
1. Try typing in and running the examples given in this chapter. Remember that you need to
gain familiarity with the Java rules. You need to make mistakes and see what goes wrong.
2. Write a program that will read in your name and address and porint them out. Now mod-
ify the program to read in your age also. Print out your name, age and address.
3. One of the easiest ways to write a program is to modify an existing one. The example
given earlier, dealing with the time taken for light to travel from the sun to the earth could
form the basis of several other programs.
many communications satellites follow a geosynchronous orbit, some 35,870 Km
above the earth's surface. What is the time lag in using such a satellite for a tele-
phone conversation?
the moon is about 384,400 Km from the earth (on average). what implications
does this have for control experiments on the moon? what is the time lag?
the following table gives the distance in MKm from the sun to the planets in the
solar system:
mercury 57.9 venus 108.2
earth 149.6 mars 227.9
jupiter 778.3 saturn 1427.0
Aims
5 Strings
This chapter looks at strings in Java. Where characters are a built in primitive type strings
are fully blown objects. This means that there are some very important differences between
the way we think of strings in older programming languages and Java.
5.2 java.lang.String
Whilst Strings are objects they can be created in three ways:–
by enclosing the text in " marks.
by using + and += on two strings to create a new string
explcitly using new – as with objects
The following program illustrates all three.
class c0501
{
public static void main(String[] args)
{
int i1,i2,i3,i4;
String s1=" This is a string";
String s2=" and this is another";
String s3;
String s4=new String();
i1=s1.length();
i2=s2.length();
i4=s4.length();
System.out.println(i1);
System.out.println(i2);
System.out.println(i4);
s3=s1+s2;
i3=s3.length();
System.out.println(i3);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
}
}
Let us look at each line in turn.
String s1=" This is a string";
String s2=" and this is another";
class c0504
{
public static void main(String[] args)
{
String s0,s1,s2,s3,s4,s5;
char c='1';
int i=1;
long l=1;
float f=1;
double d=1;
s1=String.valueOf(c);
s2=String.valueOf(i);
s3=String.valueOf(l);
s4=String.valueOf(f);
s5=String.valueOf(d);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
s0=s1+s2+s3+s4+s5;
System.out.println(s0);
}
}
The first line is very important. This makes available all of the methods within java.lang to
the following program. We can then use shortened forms of the method names within the
following program. The String class is within java.lang.
This example highlights the differences between the base types and String objects. In each
case we use the value 1. It has a different meaning in each of the contexts.
5.2.1.3 String Example 3 – as above but no import statement
class c0505
{
public static void main(String[] args)
{
String s0,s1,s2,s3,s4,s5;
char c='1';
int i=1;
long l=1;
float f=1;
double d=1;
s1=java.lang.String.valueOf(c);
s2=java.lang.String.valueOf(i);
s3=java.lang.String.valueOf(l);
s4=java.lang.String.valueOf(f);
s5=java.lang.String.valueOf(d);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
s0=s1+s2+s3+s4+s5;
System.out.println(s0);
}
}
Note that in this example we have not used the import statement and have had to fully state
the method name, i.e. java.lang.String.valueof().
5.3 java.lang.StringBuffer
This class also represents a string of characters, but now the contents may be modified. This
means that:–
String toString()
Note again that we have many functions with the same name and different signatures.
There are two new concepts raised here. The first is the concept of synchronised and the
second of throwing an exception. Let us look at each in turn.
Something that you may never have thought much about is multiprocessing. With most
computer systems there will be several processes running. Type
ps -ef
the next time you are logged onto a unix system to see what proceeses are running.
If you have ever used a pc or a mac you will probably have logged into a computer system
whilst at the same time using netscape or doing some printing. Again there are several pro-
cesses running.
Java supports the concepts of threads. This means that you as the writer of a Java program
can create a program that has several threads running. This is useful when retrieving images
from another site, whilst at the same time still interacting with the user.
It will therefore be necessary to make certain methods run in a way where they have sole
access to an object. You don't want several threads modifying the same StringBuffer object
for example.
So we declare a method synchronized to force locking of any objects that they have access
to – in reality objects that they change.
The second concept is that of error handling. Most of you will be familiar with programs
you have written that terminate when you type in unexpected values. Situations like this are
handled in Java by the ability to throw an exception. The error is then handled by an excep-
tion handler. In the example above insert methods may make the StringBuffer object too
large. In this case an exception is raised and control will pass to the error handler.
We will look at a couple of example programs to clarify the above.
5.3.1.1 StringBuffer Example 1 – throwing an exception and catching
import java.lang.*;
class c0507
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer(" this is the base
string");
StringBuffer s2=new StringBuffer(" insert this");
System.out.println(s1);
System.out.println(s2);
try
{
s1.insert(1,s2);
System.out.println(s1);
s1.insert(10,s2);
System.out.println(s1);
s1.insert(20,s2);
System.out.println(s1);
s1.insert(99999,s2);
System.out.println(s2);
}
catch (StringIndexOutOfBoundsException e)
{
System.out.println(" String too large");
}
}
}
Let us look in more details at some of the statements in this program.
StringBuffer s1=new StringBuffer(" this is the base string");
StringBuffer s2=new StringBuffer(" insert this");
These two statements define and create the two StringBuffer objects with initial values.
There are only three constructors defined for the StringBuffer class compared to seven for
the String class.
The creation of String and String Buffer objects within Java is quite different, e.g.
Creation Mechanism String StringBuffer
" Text in quotes " Yes No
+ and += Yes No
explicit new Yes Yes
This means that code that we write for handling objects of these types is syntactically quite
different.
We next print out the two StringBuffer objects.
try
{
s1.insert(1,s2);
System.out.println(s1);
s1.insert(10,s2);
System.out.println(s1);
s1.insert(20,s2);
System.out.println(s1);
s1.insert(99999,s2);
System.out.println(s2);
}
catch (StringIndexOutOfBoundsException e)
{
System.out.println(" String index too large");
}
We next have the try {...} catch block. In the event of an error control will pass to the catch
statement, and the statements following will be executed. In this case in the event of an
StringIndexOutOfBounds error the message String index too large will appear.
Within the try catch block we have code which inserts one string within another and then
prints out the value of the new string.Notice the object oriented way of doing this where we
have the binding of StringBuffer object (in each case s1) with the insert action.
The the StringBuffer object s1 will grow successfully in size until we try providing a start-
ing point for the insertion that is outside of the current size of s1.
This program highlights quite clearly the different way of thinking required when we ap-
proach things from an object oriented viewpoint.
5.3.1.2 StringBuffer Example 2 – throwing an exception and splat
import java.lang.*;
class c0508
{
public static void main(String[] args)
{
StringBuffer s1=new
StringBuffer(" this is the base string");
StringBuffer s2=new StringBuffer(" insert this");
System.out.println(s1);
System.out.println(s2);
s1.insert(1,s2);
System.out.println(s1);
s1.insert(10,s2);
System.out.println(s1);
s1.insert(20,s2);
System.out.println(s1);
s1.insert(999999,s2);
}
}
This example is very similar to the previous but now we don't have the enclosing try catch
block. Try running both of the programs to see what happens.
We will come back to the concept of exception handling in much greater depth throughtout
the course.
5.4 References
You should be aware by now of the difference between the built in basic Java data types
(byte, short, int, long, etc) and objects. When we work with i/o for example we have the
following conversion taking place when we need to get read in a floating point number:–
String -> Float ->float
A String an object and whenever we use a String variable we are actually using a reference
to the corresponding object. Object references are null when they don't actually refer to any-
thing. For people with a knowledge of pointers this will be quite familiar.
This has some interesting implications for the == operator. Try running the following pro-
gram.
import java.lang.*;
class c0
{
public static void main(String[] args)
{
String s1,s2;
s1="Hello";
s2="Hello";
if (s1==s2) System.out.println(" 1");
s1=s2;
if (s1==s2) System.out.println(" 2");
if (s1 == "Hello") System.out.println(" 3");
}
}
What do you think the output will be?
5.5 Unicode
Java is of course Unicode based. Some knowledge of Unicode is required for successfully
using Java with characters and strings.
The following provides some information regarding the languages supported under
Unicode.
Arabic – ISO-8859-6
Catalan – ISO-8859-1
Chinese (Simplified) – GB2312
Chinese (traditional) BIG5
Danish – ISO-8859-1
Dutch – ISO-8859-1
English – ISO-8859-1
Esperanto – ISO-8859-3
Finnish – ISO-8859-1
French – ISO-8859-1
Georgian– UTF-8
German – ISO-8859-1
Hebrew – ISO-8859-1
Hungarian – ISO-8859-2
Irish Gaelic – ISO-8859-1
Italian – ISO-8859-1
Japanese – SHIFT_JIS
Korean – EUC_KR
Norwegian (Bokmal) – ISO-8859-1
Norwegian (Nynorsk) – ISO-8859-1
Occitan – ISO-8859-1
Portuguese (Brazil) – ISO-8859-1
Portuguese (Portugal) – ISO-8859-1
Romanian – ISO-8859-2
Russian – ISO-8859-5
Slovenian – ISO-8859-2
Spanish – ISO-8859-1
Swedish – ISO-8859-1
Yiddish – UTF-8
Other languages that I know are supported within Unicode include Gujariti, Telugu,
Kannada, Mayalam, Thai, Lao
5.6 Summary
So far we've only looked at characters and Strings and StringBuffers. As Java is unicode
based we are dealing with 16 bit characters, and each element of a string is 16 bit.
We can also look at character manipulation in a number of other ways, that may be more
appropriate to the problem in hand. Thus we can have:–
arrays of characters
conversion to byte from both char and String and StringBuffer
conversion from byte to String and StringBuffer
arrays of bytes
and you should chose the representation that is most suited to your application.
5.7 Problems
1. Firstly try the examples out in this chapter.
2. Modify the StringBuffer example to repeatedly increase the size of the string. At what
point does the program fail, i.e. how big is the string at the time it can't be inceased in size
any more.
3. Write a Java program to print out π, i.e. print out the character pi to the screen, not 3.14
etc.
Aims
6 Arrays In Java
In this chapter we will look at the basic features of Java that support arrays.
The first thing to know is that arrays start at 0, i.e. an array dimensioned to 12 has indices
from 0 through 11.
The second thing to know is that arrays are objects.
Consider the following example:–
6.1 Example 1
For people who have attended the Fortran 90 and/or C++ courses the examples will look
very familiar!
class c0601
{
public static void main(String[] args)
{
float sum=(float)0.0,average=(float)0.0 ;
float[] rainfall={1,2,3,4,5,6,7,8,9,10,11,12} ;
int month ;
System.out.println(" Rainfall values are ");
for (month=0;month < 12 ; ++month)
System.out.println( rainfall[month]);
for (month=0;month < 12 ;++month)
sum = sum + rainfall[month];
average = sum/12;
System.out.print(" Average is ");
System.out.println( average);
}
}
Let us look more closely at some of the statements in this program.
float sum=(float)0.0,average=(float)0.0 ;
This statement declares the variables sum and average to be of type float and it gives them
initial values of 0.0 Remember that real constants are of type double by default, and as Java
is strongly type we must cast to float.
float[] rainfall={1,2,3,4,5,6,7,8,9,10,11,12} ;
This declares the array rainfall to be of type float – rainfall is an array of float. We then as-
sign initial values for the elements of the array. The values 1 through 12 have been chosen
to make it easy to see whether the calculations give the correct results. The size of the array
is worked out from the number of elements between the {} brackets.
for (month=0;month < 12 ; ++month)
System.out.println( rainfall[month]);
This is a simple for loop in Java. It prints out each element of the array on a new line.
The next thing of interest is the array indexing. This goes from 0 through 11. A little odd at
first, but don't panic.
We are used to arrays starting at 1 – naturally, this is the first element. Zero didn't exist in
mathematics for quite some time. However BASIC is a programming language that offers
arrays starting at 0 and 1 as an option in most implementations.
Lets look now at the for loop in Java. The general sytax is:–
isation, printing out of the values and the actual calculation of the sum. Note that the array
index goes from 0 through 11, not 1 through 12.
We also make use of a new another feature of arrays in Java – their length attribute.
for (month=0;month < rainfall.length ; ++month)
So in this case we can terminate the loop when we have reached the length of the array.
This is a simple example of the treatment of arrays as objects.
6.7 Summary
There are some problems with arrays in raw Java, and the main one is the machine oriented
array dimensioning, rather than physical world array dimensioning, e.g. stepping from
0–360 instead of -180–+180. The major advance over C++ is the built in subscript check-
ing, something which can only be achieved in C++ through operator overloading.
6.8 Problems
1. Type in and run some of the examples in this chapter. Modify the program to go outside
of the array bound. What run time messages do you get?
2. Write a program to assign the following data values into a 3*3 array.
1 2 3
4 5 6
7 8 9
Produce totals for each row and column. It should produce output as shown below:
1 2 3 6
4 5 6 15
7 8 9 24
12 15 18
After successfully doing this modify the program to produce averages for each row and col-
umn as well.
3. The data below has been taken from a group of first year undergraduates. It is their
heights and weights.
1.85 85
1.80 76
1.85 85
1.70 90
1.75 69
1.67 83
1.55 64
1.63 57
1.79 65
1.78 76
Your body mass index is given by your height (in metres) squared divided by your weight
in kilos. Calulate the BMI for each person.. Use arrays to hold the height and weight infor-
mation.
Grades of obesity according to Garrow as follows:
Grade 0 (desirable) 20 - 24.9
Grade 1 (overweight) 25-29.9
Grade 2 (obese) 30-40
Grad 3 (morbidly obese) >40
Ideal BMI range,
Men, Range 20.1 to 25 kg/m2
Women, Range 18.7 to 23.8 kg/m2
If you know your own height and weight modify the above to calculate your own BMI.
Aims
7 Control Structures
There are a reasonable range of control structures in Java. We need to review a number of
other concepts before looking at them in depth.
7.2 Expression
An expression is made up of one or more operations. They in turn are a mixture of
operands and operators. The evaluation of an expression typically means that one or more
operations are carried out and a value is returned.
7.3 Boolean
Remember that within standard Java boolean exists as a built in type, with values of true
and false.
7.5.1 Example 1
if ( i < 0 )
System.out.println(" Result not defined for negative val-
ues");
else
System.out.println(" Calculating for positive i ");
One or other of the cout statements will be executed. Note the semi-colons. If you are fa-
miliar with Pascal or Ada this will catch you out.
7.5.2 Example 2
if ( i < 0 )
System.out.println(" Entering negative region");
else if ( i == 0 )
System.out.println(" crossover reached ");
else
System.out.println(" Positive region entered ");
Note the semi-colons. Again will catch the Pascal/Modula 2 programmer out.
class c0704
{
public static void main(String[] args)
{
int i=0;
Integer I=new Integer(i);
String Line;
try
{
InputStream ip=System.in;
DataInputStream inp=new DataInputStream(ip);
System.out.println(" Type in an integer value ") ;
Line=inp.readLine();
I=Integer.valueOf(Line);
i=I.intValue();
switch (i)
{
case 1 : System.out.println(" one entered " );
break;
case 2 : System.out.println(" two entered " );
break;
case 3 : System.out.println(" three entered " );
break;
default: System.out.println(" number other than 1,
2 or 3 entered");
break;
}
}
catch(IOException e)
{
System.out.println(" Exceptions raised " + e);
}
}
}
Note the use of the break statement to exit from the switch statement, otherwise execution
simply drops through!
Equivalent to the case statement in other languages.
class c0705
{
public static void main(String[] args)
{
int counter=0;
int mark=99;
Integer Mark=new Integer(mark);
int[] a={1,2,3,4,5,6,7,8,9,10,0};
String Line;
try
{
InputStream i=System.in;
DataInputStream I=new DataInputStream(i);
System.out.println(" Type in value to look for") ;
Line=I.readLine();
Mark=Integer.valueOf(Line);
mark=Mark.intValue();
a[a.length-1]=mark;
while (mark != a[counter]) ++counter;
if (counter == a.length-1)
System.out.println(" Number not found");
else
{
System.out.println(" Number found at position");
System.out.println(counter);
}
}
catch(IOException e)
{
System.out.println(" Exceptions raised " + e);
}
}
}
We will look at the use of a sentinel in a later example.
class c0706
{
public static void main(String[] args)
{
float tol=(float)1.0E-6;
float term=(float)1.0,x=(float)0.0,etox=(float)1.0;
int nterm=0;
Float X=new Float(x);
String Line;
try
{
InputStream i=System.in;
DataInputStream I=new DataInputStream(i);
System.out.println(" Type in a number") ;
Line=I.readLine();
X=Float.valueOf(Line);
x=X.floatValue();
do
{
nterm+=1;
term = (x/nterm) * term;
etox+=term;
}
while (term > tol);
}
catch(IOException e)
{
System.out.println(" Exceptions raised " + e);
}
System.out.println(etox);
}
}
Statements may be labelled and we can use the break statement to jump to an appropriate
point in the code.
There is no goto statement in Java.
The following is a complete program that illustrates the use of all three statements. Type
the program in and run it to see what happens.
class c0710
{
public static void main(String[] args)
{
int j=0;
goto2:
for (;;)
{
goto1:
for (;;)
{
j=j+1;
System.out.print(j);
if (j>10)
break goto2;
if ((j>=5) & (j<=7))
break goto1;
else
{
System.out.println(" in the else clause");
continue;
}
}
}
System.out.println(" When will we get here");
}
}
Study the program to see if you can predict what the output will be. Now type the program
in and compile and run it. Were you correct?
7.11 Summary
Java has a decent set of control structures. They provide us with most of the functionality
we require.
7.12 Problems
1. Write a program to print out the 12 times table. Output should be roughly of the form
1 * 12 = 12
2 * 12 = 24
2. Write a program that produces a conversion table from litres to pints and vice versa. One
litre is approximately 1 3/4 pints. The output should comprise three columns. The middle
column should be an integer and the columns to the left and right should be the correspond-
ing pints and litre values. This enables the middle column to be scanned quickly and the
corresponding equivalent in litres or pints read easily.
3. Rewrite the program for the period of a pendulum. The new program should print out the
length of the pendulum and period for lengths of the pendulum from 0 to 100 cm in steps of
0.5 cm.
The physical world has many examples where processes require some threshold to be over-
come before they begin operation: critical mass in nuclear reactions, a given slope to be ex-
ceeded before friction is overcome, and so on. Unfortunately, most of these sorts of calcula-
tions become rather complex and not really appropriate here. The following problem tries to
restrict the range of calculation, whilst illustrating the possibilities of decision making.
4. If a cubic equation is expressed as:
z3 + a2z2 + a1z + a0 = 0
and we let:
q=a1/3-(a2*a2)/9
and:
r=(a1*a2-3a0)/6-(a2*a2*a2)/27
we can determine the nature of the roots as follows:
q3 + r2 > 0; one real root and a pair of complex;
q3 + r2 = 0; all roots real, and at least two equal;
q3 + r2 < 0; all roots real;
Incorporate this into a suitable program, to determine the nature of the roots of a cubic from
suitable input.
5. The form of breaking waves on beaches is a continuum, but for convenience we com-
monly recognise three major types: surging, plunging and spilling. These may be classified
empirically by reference to the wave period, T (seconds), the breaker wave height, Hb
(metres), and the beach slope, m. These three variables are combined into a single parame-
ter, B, where
B = Hb/(gmT2)
g is the gravitational constant (981 cm sec–2). If B is less than .003, the breakers are surg-
ing; if B is greater than 0.068, they are spilling, and between these values, plunging break-
ers are observed.
(i) On the east coast of New Zealand, the normal pattern of waves is swell waves, with
wave heights of 1 to 2 metres, and wave periods of 10 to 15 seconds. During storms, the
wave period is generally shorter, say 6 to 8 seconds, and the wave heights higher, 3 to 5
metres. The beach slope may be taken as about 0.1. What changes occur in breaker charac-
teristics as a storm builds up?
(ii) Similarly, many beaches have a concave profile. The lower beach generally has a very
low slope, say less than 1 degree (m=0.018), but towards the high tide mark, the slope in-
creases dramatically, to say 10 degrees or more (m=0.18). What changes in wave type will
be observed as the tide comes in?
6. Personal taxation is usually structured in the following way:–
no taxation on the first m0 units of income;
taxation at t1% on the next m1 units;
taxation at t2% on the next m2 units;
taxation at t3% on anything above.
For some reason, this is termed progressive taxation. Write a generalised program to deter-
mine net income after tax deductions. Write out the gross income, the deductions and the
net income. You will have to make some realistic estimates of the tax thresholds mi and the
taxation levels ti. You could use this sort of model to find out how sensitive revenue from
taxation was in relation to cosmetic changes in thresholds and tax rates.
8. The specific heat capacity of water is 2009 J kg–1 K–1; the specific latent heat of fusion
(ice/water) is 335 kJ kg–1, and the specific latent heat of vaporization (water/steam) is 2500
kJ kg–1. Assume that the specific heat capacity of ice and steam are identical to that of wa-
ter. Write a program which will read in two temperatures, and will calculate the energy re-
quired to raise (or lower) ice, water or steam at the first temperature, to ice, water or steam
at the second. Take the freezing point of water as 273 K, and its boiling point as 373 K. For
those happier with Celsius, 0o C is 273 K, while 100o c is 373 K. One calorie is 4.1868 J,
and for the truly atavistic, 1 BTU is 1055 J (approximately).
7.13 Bibliography
Dahl O. J., Dijkstra E. W., Hoare C. A. R., Structured Programming, Academic Press,
1972.
This is the original text, and a must. The quote at the start of the chapter by
Dijkstra summarises beautifully our limitations when programming and the disci-
pline we must have to successfully master programming.
Knuth D. E., Structured Programming with GOTO Statements, in Current Trends in Pro-
gramming Methodology, Volume 1, Prentice Hall.
The chapter by Knuth provides a very succinct coverage of the arguments for the
adoption of structured programming, and dispells many of the myths concerning
the use of the GOTO statement. Highly recommended.
Winston Churchill.
Aims
8 Exceptions
Errors always occur at run time in programs that do anything useful. The facilities for han-
dling errors have gradually improved in programming languages. The concept of raising an
exception and then passing control to an error handler is one that is now seen in a number
of programming languages including C++, Ada 95 and Java.
Let us look at some common errors and solutions:–
invalid input: ask the user to retype the data values
file not found: ask the user to retype the file name
numeric overflow: terminate the program with a warning;
numeric underflow: terminate the program with a warning;
array out of bounds: terminate the program with an error message;
and you will all be familiar with one or more of these common errors.
One of the major problems in languages that do not support the concept of raising an ex-
ception and passing control to an error handler is that the logic of something really quite
simple can be lost completely because of the additional coding complexity.
So we have to chose between:–
correctness by trapping all possible errors at one extreme with code that is very
difficult to understand;
and
probable erroneous output because we have only trapped a small number of er-
rors with code that is relatively easy to understand.
Exceptions enable us to move towards overall program correctness without writing code
that is unintelligible.-
Let us look at examples in a couple of programming languages of reading user input.
Fortran 90 for example has the concept of implicit gotos via the END= and ERR= options
and also the concept of IOSTAT returing a value to let you know something has gone
wrong.
Pascal and Modula 2 have the concept of EOLN and EOF.
The following are coding examples that read all input from a user until they type CTRL Z –
end of file. The first is in Pascal, the second in Fortran 90, and the third in C++. The exam-
ples also highlight the quite different ways that languages have in their handling of end of
line and end of file.
Current:=Root;
WHILE NOT EOF DO
BEGIN
NEW([email protected]);
Current:[email protected]);
READ([email protected])
END;
[email protected]:=NIL;
Current:=Root;
WHILE Current NIL DO
BEGIN
WRITE([email protected]);
Current:[email protected]
END;
END.
/*
Update pointers to add new value at end of list. The "if"
statement could be omitted by making the first character en-
tered a "special" case - as in Example 10.1.4 - but
generallity is a good idea!
*/
if (first == NULL) /* If this is the first character
*/
ptr = first;
while (ptr != NULL)
{
cout << ptr-c;
ptr = ptr->next;
}
cout << endl;
return 0;
}
8.4 Discussion
It is apparent that the essential code is hidden to greater or lessor extent in the requirements
to handle special conditions. The Pascal code is probably the cleanest. The beauty of excep-
tion handling is that the essential logic of the code is left alone and enclosed within a try
statement. Let us look at one of the earlier examples to see how simple and straightforward
this is in Java.
import java.io.*;
class c0302
{
public static void main(String[] args)
{
try
{
InputStream i=System.in;
DataInputStream in=new DataInputStream(i);
String Line;
System.out.println(" Type in a line of text ");
Line=in.readLine();
System.out.println(Line);
}
catch(IOException e)
{System.out.println(" Exceptions raised: " + e); }
}
}
If there is an error getting a line of input from the user within the body of the try block con-
trol will pass to the catch statement and in this case an informative message is issued about
the error. The readLine() method can throw an IOException. We will come back to look at
the above example after we have covered i/o in more depth.
The general syntax is:–
try
{
}
catch (Exception_1 e)
{
}
catch(Exception_2 e)
{
}
...
finally
{
}
8.4.1 try
The try block can have zero or more catch clauses. An abnormal exit is one of:–
break
continue
return
exception propagation
8.4.2 catch
These are the exception handlers. They actually carry out thw work of handling the excep-
tion that was raised in the try block. The argument of the catch must be of type Throwable
(or subclass). We will look into this in more depth in the complete file copy program in this
chapter.
8.4.3 finally
This part is executed:–
after normal termination of the try block;
after an exception handled in a catch clause;
after an exception that has no catch clause;
after a break, continue or return statement;
We will look into this in more depth in the complete file copy program in this chapter.
try
{
// First make sure the specified source file
// exists, is a file, and is readable.
if (!source_file.exists() || !source_file.isFile())
throw new FileCopyException(
"FileCopy: no such source file: " +
source_name);
if (!source_file.canRead())
throw new FileCopyException(
"FileCopy: source file " +
"is unreadable: "
+ source_name);
if (destination_file.exists())
{
if (destination_file.isFile())
{
DataInputStream in = new
DataInputStream(System.in);
String response;
if (!destination_file.canWrite())
throw new FileCopyException(
"FileCopy: destination " +
"file is unwriteable: " + dest_name);
System.out.print("File ");
System.out.print(dest_name);
System.out.print(" already exists. Overwrite?
(Y/N): ");
System.out.flush();
response = in.readLine();
if (!response.equals("Y")
&& !response.equals("y"))
throw new FileCopyException(
"FileCopy: copy cancelled.");
}
else
throw new FileCopyException(
"FileCopy: destination "
+ "is not a file: "
+ dest_name);
}
else
{
File parentdir = parent(destination_file);
if (!parentdir.exists())
throw new FileCopyException(
"FileCopy: destination "
+ "directory doesn't exist: " + dest_name);
if (!parentdir.canWrite())
throw new FileCopyException(
"FileCopy: destination "
+ "directory is unwriteable: " + dest_name);
}
finally
{
if (source != null)
try { source.close(); } catch (IOException e) { ; }
if (destination != null)
try { destination.close(); } catch (IOException e) {
; }
}
}
you are in a class hierarchy. We will come back to this in more depth when we look for-
mally at class extension in a later chapter.
8.10 Summary
There are a number of examples that cover this area in more depth later in the course, as it
is best to see exception handling done in a realistic context to appreciate the power and ex-
pressiveness that the concepts provide.
8.11 Problems
1. Try writing a Java version of the linked list examples in this chapter. There are a number
of catches here.
2. Try running the example program in this chapter. I've put it up on the Web server. Base
url is:–
http://www.kcl.ac.uk/support/cc/fortran/home.html
This method can easily be incorporated into any program that requires it very easily.
From a programmer's point of view the user is a peripheral that types when you is-
sue a read request.
Peter Williams.
Aims
The aims of this chapter are to look at the mechanisms in Java for i/o. As Java is
fully object oriented the way Java does i/o will appear strange at first. There is a
coverage of streams and their use for both input and output.
Chapter 9 i/o 120
9 i/o
There is a complete package for i/o called java.io. This contains paired streams. A stream is
an ordered sequence of data. A stream has either a source or a destination.
There is no way at the moment within Java of getting formatted output. This means that
you cannot:–
define a minimum width on output
define a maximum width on output
define precision for floating point output
Thus it is impossible at present to achieve neat tabular output.
A subset is listed below.
InputStream OutputStream
ByteArrayInputStream ByteArrayOutputStream
PipedInputStream PipedOutputStream
FilterInputStream FilterOutputStream
DataInputStream DataOutputStream
FileInputStream FileOutputStream
RandomAccessFile
DataInput DataOutput
DataInputStream DataOutputStream
The complete hierarchy is given below. This highlights many of the very important con-
cepts involved in object oriented programming.
Object
File
FileDescriptor
InputStream
ByteArrayInputStream
FileInputStream
FilterInputStream
BufferedInputStream
DataInputStream
LineNumberInputStream
PushBackInputStream
PipedInputStream
SequenceInputStream
StringBufferInputStream
RandomAccessFile
DataInput
DataInputStream
DataOutput
DataOutputStream
OutputStream
ByteArrayOutputStream
FileOutputStream
BufferedOutputStream
DataOutputStream
PrintStream
FilterOutputStream
PipedInputStream
StreamTokenizer
I recommend looking at the on-line documentation that comes with the Java 1.1 jdk. Use
netscape to browse it. All of the information required is there. We will only look at a subset
of the above in the notes.
Note that Java does not support file i/o from an applet when running on another system, i.e.
if we were loading a Java applet from system A and running it on system B, then it would
not have access to B's file system. This would comprimise the security of Java.
A Java program will have access to the underlying file system.
To aid here Java supports UTF-8, which is a multibyte coding scheme. The standard ASCII
characters only occupy 1 byte. Thus for text which is essentially ASCII we have a much
more compact data representation.
and anyone who has done an operating system course or real time programming would be
familiar with the ideas.
Note that does not mean that the section of code cannot be timesliced. We have a lock set
and access cannot be made to whatever the lock has been applied until it has completed.
If you would like more information see the bibliography at the end of the chapter on
threads.
9.7 Example 1
The following is a C++ program to extract all of the ASCII characters from a Microsoft
Word file.
#include <iostream.h>
int main()
{
unsigned char c;
unsigned int i=0;
while (cin.get(c))
{
i=++i;
if ( c < 32 || c > 127)
c = ' ';
cout << c;
if ( i > 60 && c == ' ')
{
cout << endl;
i=0;
}
}
return(0);
}
The following is a modification to the file copy program that does the same.
// This example is a simple modification of the earlier
// example on file copying.
//
// It has been rewritten to extract all of the ascii
// characters from a Microsoft Word document.
//
import java.io.*;
try {
// First make sure the specified source file
// exists, is a file, and is readable.
if (!source_file.exists() || !source_file.isFile())
throw new convertException("convert: no such source
file: " +
source_name);
if (!source_file.canRead())
throw new convertException("convert: source file "
+
"is unreadable: " + source_name);
if (!destination_file.canWrite())
throw new convertException("convert: des-
tination " +
"file is unwriteable: "
+ dest_name);
}
}
// No matter what happens, always close any streams
we've opened.
finally {
if (source != null)
try { source.close(); } catch (IOException e) { ; }
if (destination != null)
try { destination.close(); } catch (IOException e)
{ ; }
}
}
char c;
Variable to hold the character to be written.
int byte_read;
Read returns integers.
while(true)
{
byte_read = source.read();
if (byte_read == -1) break;
Read returns -1 at end of file.
i++;
Increment the character count.
if ( byte_read < 32 || byte_read > 127 )
byte_read=32 ;
Convert non-printing characters to blank.
if ( i>60 && byte_read==32 )
{
c=(char)carriage_return;
destination.write(c);
c=(char)line_feed;
destination.write(c);
i=0;
}
Split the output line at the first blank character after position 60.
c=(char)byte_read;
destination.write(c);
Convert to character and write out.
The program can be run with the following command line:
java convert before.doc after.txt
9.8 Problems
1. Write a program that writes a file that contains the numbers 1 through 10 as integer val-
ues. Examine this file with an editor. What do you notice?
2. Now write a program to read in these values and print them out to the screen.
3. Repeat problem one but now use single precision reals.
4. Repeat 2 with the file containing real numbers.
5. Chapter 17 in the third edition of the Deitel book has some i/o examples. Have a look at
those to see how to create a sequential file and read it back in.
Aims
The aim of this chapter is to introduce the concepts and ideas involved in using
threads in Java.:–
extends Thread;
implements Runnable;
sleep;
static variables;
synchronized;
priority;
init(), start(), stop(), paint(), update(), repaint(), yield();
Chapter 10 Threads 130
10 Threads
The computer systems that you use runs many processes. It is not uncommon to:–
be listening to a cd;
downloading a file using ftp;
printing a file;
reading your mail;
at the same time.
If you are using a unix system try:–
ps -ef
If you use Windows try
[CTRL] [ESC]
to bring up a list of tasks.
Some programming languages offer support for writing programs that can multitask. Mod-
ula 2 offers coroutines, Ada has tasks, and Java has threads.
This will enable us to write Java programs that run each of the following as a separate
thread:–
download data from a remote system
play sound
interact with a user
carry out calculations
display the output from these calculations as the calculations run
thread02(int t)
{delay=t;}
The first thing of interest is the addition of a class variable delay. Whenever we create an
object of this class we will also create a variable called delay.
thread02(int t)
{delay=t;}
We now supply our own constructor for an object of type thread02. The constructor tales
one argument and will be used to provide a value for the class variable delay.
thread02 t1=new thread02(50);
thread02 t2=new thread02(100);
We now create two thread objects and provide initial values for delay. The time is in milli-
seconds.
Sys-
tem.out.println(Thread.currentThread().getName());
sleep(delay);
The run method gets the name of the cuurently executing thread and then calls the
sleepmethod with the corresponding value for delay.
thread04(int t)
{
delay=t;
}
10.9 Problems
The important thing with these examples is to see them actually running. See if you can
predict what the output will be.
The next thing is to try all of the examples out on another platform. Do you think that you
will get the same results.
Compare the actual output for each of the examples on the various systems that you have
access to.
Chapter 15 of the Deitel book has a coverage of multithreading. They have a number of ex-
amples including one implementing a circular buffer.
10.10Bibliography
The two main types of sources are texts on operating systems and programming langauges
that support real time programming. Ada 95 and Modula 2 offer support in this area.
Barnes J., Programming in Ada 95, Addsion Wesley.
• The chapter on tasking provides a description of the way that Ada handles
multitasking.
Christian K., A Guide to Modula 2, Springer Verlag.
• The chapter on coroutines is worth looking at.
Deitel H. M., An Introduction to Operating Systems, Addison Wesley.
• There are several chapters that look at the whole area of multi-processing, asyn-
chronous and snychronous processes. Easy read. Very comprehensive bibliogra-
phy.
The following faq is excellent.
http://www.best.com/~bos/threads-faq/
Searching Amazon will reveal a fascinating spread of books on threads. Try it!
Aims
The aim of this chapter is to introduce the concepts and ideas involved in using the
facilities offered in Java for graphical output. The coverage looks at what was avail-
able in the original 1.0.x JDK and the facilities in later releases. There is a coverage
of:
Basic graphics concepts:
vector vs raster graphics, pixels, bit maps – gif vs jpg, fonts, coordinate
space, user space, screen resolution, colour and colour models, scan-
ning, integer arithmetic, real arithmetic, flicker, double buffering, se-
lective erasure, device contexts, clipping, rendering.
java.awt
java.awt.Graphics
java.awt.Graphics2D
The imaging models supported by the Java 2D API:
The original producer consumer model
The immediate model introduced in the Java 2 JDK
The pipeline model in the Java Advanced Imaging API.
Chapter 11 Introduction to Graphics Programming 138
11.2 Pixels
With each x-y point we have the additional feature of a gray scale value or colour value.
If one needs faithful printed colour then one should use software that offers pantone colour
support. You would typically print out test sheets with the name/number of each colour and
then use that to provide the on-screen colour. This may not match very closely the printed
colour.
11.6 Scanning
Take care when scanning. Take a 5*7 inch colour photo with 300 dpi resolution.
5*300 * 7*300 = 35*9 * 10,000 = 3,150,000
11.8 Fonts
There is a limited choice of fonts with the early versions of the JDK and but we can use
them with a range of settings. Things have changed considerably with later versions of the
JDK.
11.10Device context
A concepts that is very useful in the graphics and windows programming area is that of a
device context. All drawing can be done to a device context and this might be virtual or
physical, e.g. the screen or a printer. In Java we use the Graphics object as our device con-
text. You have seen this throughout the examples already. We will look at this area in more
depth in this chapter.
11.11Clipping
Clipping refers to the way in which a graphics object is displayed on the current area. Some
of the object will be outside the clip region and will not be displayed. See Foley et al for a
coverage of this subject.
11.12Rendering
Rendering is the production of the actual output on a graphics device.
11.14History
Things are more complicated than they need be in this area, due to the way that Java has
evolved. As you know we have had three major release of the Java jdk.
jdk 1.0.x
jdk 1.1.x
jdk 1.2.x
and Sun have announced jdk 1.3 on February 15th.
There have also been several release of Swing. As problems are discovered with the current
versions Sun try and fix the problems. This makes working out the best way of doing some-
thing quite difficult in the graphics and windows programming area.
If you look at the books and examples that exist you will see several ways of achieving
what appears to be the same end result.
This chapter starts by looking at ways of doing things using the original jdk 1.0.x style.
This (hopefully) will show some of the problems that exist with the original release and
why Sun had to make changes.
ball=new Thread(this);
ball.start();
}
}
{
x+=deltax;
y+=deltay;
if ( (x>=xl) | (x<=0) ) deltax=-deltax;
if ( (y>=yl) | (y<=0) ) deltay=-deltay;
repaint();
try
{
Thread.sleep(1);
}
catch (InterruptedException e)
{
}
}
}
bgg.setColor(Color.blue);
bgg.fillOval((int)x,(int)y,20,20);
g.drawImage(bgi,0,0,this);
oldx=x;
oldy=y;
}
for(;;)
{
x+=deltax;
y+=deltay;
if ( (x>=xl) | (x<=0) ) deltax=-deltax;
if ( (y>=yl) | (y<=0) ) deltay=-deltay;
repaint();
try
{
Thread.sleep(1);
}
catch (InterruptedException e)
{
}
}
}
}
Compiling with JDK 1.2.2 and -deprecation generates warning about size and stop. Running
the applet on Gum using the appletviewer is very slow. Running on a P166 with 64 Mb of
memory is faster, but there are still problems with trails of where the ball has been. Run-
ning off the college web server with Netscape on the pc has the same trail behaviour.
Thread ball;
Image bgi;
Graphics bgg;
bgg.setColor(Color.blue);
bgg.fillOval(x,y,20,20);
g.drawImage(bgi,0,0,this);
oldx=x;
oldy=y;
}
public void update(Graphics g)
{
paint(g);
}
Image janeimg;
int xpos=10;
// 25%
g.drawImage(janeimg,xpos,10,iwidth/4,iheight/4,this);
// 50%
xpos += (iwidth/4)+10;
g.drawImage(janeimg,xpos,10,iwidth/2,iheight/2,this);
// 100%
xpos += (iwidth/2)+10;
g.drawImage(janeimg,xpos,10,this);
import java.awt.Graphics;
import java.awt.Image;
for (xpos=10;xpos<400;xpos+=50)
{
g.drawImage(img,xpos,ypos,this);
ypos += +50;
try {Thread.sleep(100);}
catch(InterruptedException e) {}
}
}
}
11.22.5 Polygons
There are two ways of doing this:–
using arrays
using the polygon class
The following two examples show both methods.
import java.awt.*;
import java.awt.*;
BOLD
ITALIC
BOLDITALIC
The following example prints out some text in some of the above fonts in each of the four
variations.
import java.awt.*;
public class c1170 extends java.applet.Applet
{
String s;
11.23AWT 1.0.x
The package java.awt contains all of the classes for creating user interfaces and for painting
graphics and images. A user interface object such as a button or a scrollbar is called, in
AWT terminology, a component. Some components fire events when a user interacts with
the components. The AWTEvent class and its subclasses are used to represent the events
that AWT components can fire. A container is a component that can contain components
and other containers. A container can also have a layout manager that controls the visual
placement of components in the container. The AWT package contains several layout man-
ager classes and an interface for building your own layout manager.
11.23.2Class Summary
AlphaComposite
This AlphaComposite class implements the basic alpha compositing rules for
combining source and destination pixels to achieve blending and transparency ef-
fects with graphics and images.
AWTEvent
The root event class for all AWT events.
AWTEventMulticaster
A class which implements efficient and thread-safe multi-cast event dispatching
for the AWT events defined in the java.awt.event package.
AWTPermission
This class is for AWT permissions.
BasicStroke
The BasicStroke class defines a basic set of rendering attributes for the outlines
of graphics primitives.
BorderLayout
A border layout lays out a container, arranging and resizing its components to fit
in five regions: north, south, east, west, and center.
Button
This class creates a labeled button.
Canvas
A Canvas component represents a blank rectangular area of the screen onto
which the application can draw or from which the application can trap input
events from the user.
CardLayout
A CardLayout object is a layout manager for a container.
Checkbox
A check box is a graphical component that can be in either an "on" (true) or
"off" (false) state.
CheckboxGroup
The CheckboxGroup class is used to group together a set of Checkbox buttons.
CheckboxMenuItem
This class represents a check box that can be included in a menu.
Choice
The Choice class presents a pop-up menu of choices.
Color
A class to encapsulate colors in the default sRGB color space or colors in arbi-
trary color spaces identified by a ColorSpace.
Component
A component is an object having a graphical representation that can be displayed
on the screen and that can interact with the user.
ComponentOrientation
The ComponentOrientation class encapsulates the language-sensitive orientation
that is to be used to order the elements of a component or of text.
Container
A generic Abstract Window Toolkit(AWT) container object is a component that
can contain other AWT components.
Cursor
A class to encapsulate the bitmap representation of the mouse cursor.
Dialog
A Dialog is a top-level window with a title and a border that is typically used to
take some form of input from the user.
Dimension
The Dimension class encapsulates the width and height of a component (in inte-
ger precision) in a single object.
Event
Event is a platform-independent class that encapsulates events from the plat-
form's Graphical User Interface in the Java 1.0 event model.
EventQueue
EventQueue is a platform-independent class that queues events, both from the
underlying peer classes and from trusted application classes.
FileDialog
The FileDialog class displays a dialog window from which the user can select a
file.
FlowLayout
A flow layout arranges components in a left-to-right flow, much like lines of text
in a paragraph.
Font
The Font class represents fonts.
FontMetrics
The FontMetrics class defines a font metrics object, which encapsulates informa-
tion about the rendering of a particular font on a particular screen.
Frame
A Frame is a top-level window with a title and a border.
GradientPaint
The GradientPaint class provides a way to fill a Shape with a linear color gradi-
ent pattern.
Graphics
The Graphics class is the abstract base class for all graphics contexts that allow
an application to draw onto components that are realized on various devices, as
well as onto off-screen images.
Graphics2D
This Graphics2D class extends the Graphics class to provide more sophisticated
control over geometry, coordinate transformations, color management, and text
layout.
GraphicsConfigTemplate
The GraphicsConfigTemplate class is used to obtain a valid
GraphicsConfiguration.
GraphicsConfiguration
The GraphicsConfiguration class describes the characteristics of a graphics desti-
nation such as a printer or monitor.
GraphicsDevice
The GraphicsDevice class describes the graphics devices that might be available
in a particular graphics environment.
GraphicsEnvironment
The GraphicsEnvironment class describes the collection of GraphicsDevice ob-
jects and Font objects available to a Java(tm) application on a particular plat-
form.
GridBagConstraints
The GridBagConstraints class specifies constraints for components that are laid
out using the GridBagLayout class.
GridBagLayout
The GridBagLayout class is a flexible layout manager that aligns components
vertically and horizontally, without requiring that the components be of the same
size.
GridLayout
The GridLayout class is a layout manager that lays out a container's components
in a rectangular grid.
Image
The abstract class Image is the superclass of all classes that represent graphical
images.
Insets
An Insets object is a representation of the borders of a container.
Label
A Label object is a component for placing text in a container.
List
The List component presents the user with a scrolling list of text items.
MediaTracker
The MediaTracker class is a utility class to track the status of a number of media
objects.
Menu
A Menu object is a pull-down menu component that is deployed from a menu
bar.
MenuBar
The MenuBar class encapsulates the platform's concept of a menu bar bound to a
frame.
MenuComponent
The abstract class MenuComponent is the superclass of all menu-related compo-
nents.
MenuItem
All items in a menu must belong to the class MenuItem, or one of its subclasses.
MenuShortcut
A class which represents a keyboard accelerator for a MenuItem.
Panel
Panel is the simplest container class.
Point
A point representing a location in (x, y) coordinate space, specified in integer
precision.
Polygon
The Polygon class encapsulates a description of a closed, two-dimensional re-
gion within a coordinate space.
PopupMenu
A class that implements a menu which can be dynamically popped up at a speci-
fied position within a component.
PrintJob
An abstract class which initiates and executes a print job.
Rectangle
A Rectangle specifies an area in a coordinate space that is enclosed by the Rect-
angle object's top-left point (x, y) in the coordinate space, its width, and its
height.
RenderingHints
The RenderingHints class contains rendering hints that can be used by the
Graphics2D class, and classes that implement BufferedImageOp and Raster.
RenderingHints.Key
Defines the base type of all keys used to control various aspects of the rendering
and imaging pipelines.
Scrollbar
The Scrollbar class embodies a scroll bar, a familiar user-interface object.
ScrollPane
A container class which implements automatic horizontal and/or vertical scroll-
ing for a single child component.
SystemColor
A class to encapsulate symbolic colors representing the color of GUI objects on
a system.
TextArea
A TextArea object is a multi-line region that displays text.
TextComponent
The TextComponent class is the superclass of any component that allows the ed-
iting of some text.
TextField
A TextField object is a text component that allows for the editing of a single line
of text.
TexturePaint
The TexturePaint class provides a way to fill a Shape with a texture that is speci-
fied as a BufferedImage.
Toolkit
This class is the abstract superclass of all actual implementations of the Abstract
Window Toolkit.
Window
A Window object is a top-level window with no borders and no menubar.
Exception Summary
11.23.3
AWTException
Signals that an Absract Window Toolkit exception has occurred.
IllegalComponentStateException
Signals that an AWT component is not in an appropriate state for the requested
operation.
11.23.4Error Summary
AWTError
Thrown when a serious Abstract Window Toolkit error has occurred.
The original AWT has some problems associated with it, and you can see now why it was
necessary to develop a better windowing development system. We will look at Swing in a
later chapter. We will next look at some of the developments that have taken place with the
original AWT.
11.23.5 java.awt.Graphics
The Graphics class is the abstract base class for all graphics contexts that allow an applica-
tion to draw onto components that are realized on devices. You need to know about what is
in this package as the other more recent packages will inherit from this package. A Graph-
ics object has state information needed for the basic rendering operations that Java supports.
This state information includes the following properties:
The Component object on which to draw.
A translation origin for rendering and clipping coordinates.
The current clip.
The current color.
The current font.
The current logical pixel operation function (XOR or Paint).
For example, through the Graphics class you can draw rectangles, ovals, and polygons.
Graphics2D enhances the concept of geometric rendering by providing a mechanism for
rendering virtually any geometric shape. Similarly, with the Java 2D API you can draw
styled lines of any width and fill geometric shapes with virtually any texture.
11.29.2 Rendering Model
The basic graphics rendering model has not changed with the addition of the Java 2D APIs.
To render a graphic, you set up the graphics context and invoke a rendering method on the
Graphics object.
The Java 2D API class Graphics2D extends Graphics to support more graphics attributes
and provide new rendering methods.
The Java 2D API automatically compensates for differences in rendering devices and pro-
vides a uniform rendering model across different types of devices. At the application level,
the rendering process is the same whether the target rendering device is a display or a
printer.
11.29.3 Backward Compatibility and Platform Independence
The Java 2DTM API maintains backward compatibility with JDK 1.1 software. It is also
architected so that applications can maintain platform-independence.
To ensure backward compatibility, the functionality of existing JDK graphics and imaging
classes and interfaces was maintained. Existing features were not removed and no package
designations were changed for existing classes. The Java 2D API enhances the functionality
of the AWT by implementing new methods in existing classes, extending existing classes,
and adding new classes and interfaces that don't affect the legacy APIs.
The Java 2D API functionality is delivered through an expanded graphics context,
Graphics2D. To provide this extended graphics context while maintaining backward com-
patibility, Graphics2D extends the Graphic s class from the JDK 1.1 release.
The usage model of the graphics context remains unchanged. The AWT passes a graphics
context to an AWT Component through the following methods:
paint
paintAll
update
print
printAll
getGraphics
A JDK 1.1 applet interprets the graphics context that's passed in as an instance of Graphics.
To gain access to the new features implemented in Graphics2D, a Java 2D API-compatible
applet casts the graphics context to a Graphics2D object:
public void Paint (Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
...
...
g2.setTransform (t);
}
Note that we still invoke paint with Graphics and switch to Graphics2D with an explicit
cast.
To enable the development of platform-independent applications, the Java 2D API makes
no assumptions about the resolution, color space, or color model of the target rendering de-
vice. Nor does the Java 2D API assume any particular image file format.
Truly platform-independent fonts are possible only when the fonts are built-in (provided as
part of the JDK software), or when they are mathematically or programmatically generated.
The Java 2D API does not currently support built-in or mathematically generated fonts, but
it does enable the programmatic definition of entire fonts through their glyph set. Each
glyph can in turn be defined by a Shape that consists of line segments and curves. Many
fonts of particular styles and sizes can be deriv ed from a single glyph set.
11.29.4 Setting Up the Graphics2D Context
To configure the Graphics2D context for rendering, you use the Graphics2D set methods to
specify attributes such as the RenderingHints, Stroke, Paint, clipping path, Composite, and
Transform.
11.29.5 Rendering Graphics Primitives
Graphics2D provides rendering methods for Shapes, Text, and Images:
draw—strokes a Shape's path using the Stroke and Paint objects in the
Graphics2D context.
fill—fills a Shape using the Paint in the Graphics2D context.
drawString—renders the specified text string using the Paint in the Graphics2D
context.
drawImage—renders the specified image.
To stroke and fill a shape, you must call both the draw and fill methods.
Graphics2D also supports the draw and fill methods from previous versions of the JDK
software, such as drawOval and fillRect.
11.29.6 Managing and Manipulating Rasters
A BufferedImage object uses a Raster to manage its rectangular array of pixel data. The
Raster class defines fields for the image's coordinate system—width, height, and origin. A
Raster object itself uses two objects to manage the pixel data, a DataBuffer and a
SampleModel. The DataBuffer is the object that stores pixel data for the raster, and the
SampleModel provides the interpretation of pixel data from the DataBuffer.
11.29.7 Geometries
The Java 2DTM API provides several classes that define common geometric objects, such
as points, lines, curves, and rectangles. These new geometry classes are part of the
java.awt.geom package. For backward compatibility, the geometry classes tha t existed in
previous versions of the JDK software, such as Rectangle, Point, and Polygon, remain in
the java.awt package.
The Java 2D API geometries such as GeneralPath, Arc2D, and Rectangle2D implement the
Shape interface defined in java.awt. Shape provides a common protocol for describing and
inspecting geometric path objects. A new interface, PathIterator, defines methods for re-
trieving elements from a geometry.
This API supports accessing image data in a variety of storage formats and manipulating
image data through several types of filtering operations.
11.29.10 Color
Color imaging is one of the fundamental components of any graphics system, and it is often
a source of great complexity in the imaging model. The Java 2D API provides support for
high-quality color output that is easy to use and allows advanced clients to make sophisti-
cated use of color.
The key color management classes in the Java 2D API are ColorSpace, Color, ColorModel:
A ColorSpace represents a system for measuring colors, typically using three separate nu-
merical values or components. The ColorSpace class contains methods for converting be-
tween the color space and two standard color spaces, CI EXYZ and RGB.
We will now look at redoing some of the earlier examples to use the newer, preferred meth-
ods.
y+=deltay;
if ( (x>=xl) | (x<=0) ) deltax=-deltax;
if ( (y>=yl) | (y<=0) ) deltay=-deltay;
repaint();
try
{
Thread.sleep(1);
}
catch (InterruptedException e)
{
}
}
}
11.30.1 Initialisation
public void init()
Called by the browser or applet viewer to inform this applet that it has been loaded into the
system. It is always called before the first time that the start method is called.
A subclass of Applet should override this method if it has initialization to perform. For ex-
ample, an applet with threads would use the init method to create the threads and the de-
stroy method to kill them. The implementation of this method provided by the Applet class
does nothing.
11.30.2 JFrame
public class JFrame extends Frame
implements WindowConstants, Accessible, RootPaneContainer
An extended version of java.awt.Frame that adds support for interposing input and painting
behavior in front of the frame's children (see glassPane), support for special children that
are managed by a LayeredPane (see rootPane) and for Swing MenuBars.
The JFrame class is slightly incompatible with java.awt.Frame. JFrame contains a
JRootPane as it's only child. The contentPane should be the parent of any children of the
JFrame.
11.30.3 addWindowListener
public void addWindowListener(WindowListener l)
Adds the specified window listener to receive window events from this window. If l is null,
no exception is thrown and no action is performed.
11.30.4 Class WindowAdapter
public abstract class WindowAdapter extends Object implements WindowListener
An abstract adapter class for receiving window events. The methods in this class are empty.
This class exists as convenience for creating listener objects.
Extend this class to create a WindowEvent listener and override the methods for the events
of interest. (If you implement the WindowrListener interface, you have to define all of the
methods in it. This abstract class defines null methods for them all, so you can only have to
define methods for events you care about.)
Create a listener object using the extended class and then register it with a Window using
the window's addWindowListener method. When the window's status changes by virtue of
being opened, closed, activated or deactivated, iconified or deiconified, the relevant method
in the listener object is invoked, and the WindowEvent is passed to it.
Experiment with the sleep time.
We will look into the above in more detail in later chapters.
{
double x,y,deltax,deltay,oldx,oldy;
double xl=300;
double yl=300;
Thread ball;
BufferedImage bgi;
Graphics bgg;
bgg.setColor(Color.white);
bgg.fillOval((int)oldx,(int)oldy,20,20);
bgg.setColor(Color.blue);
bgg.fillOval((int)x,(int)y,20,20);
g2d.drawImage(bgi,0,0,this);
oldx=x;
oldy=y;
}
}
The differences are:
The init method creates a BufferedImage from an Image. An explicit cast is re-
quired.
The paint method uses Graphics2D variables, and again we have an explicit cast.
A main method has been added, which is identical with that used in 11.30.
Experiment with the sleep time.
}
});
}
}
Differences include:
We are now working with buffered images
paint creates a Graphics2D context from a Graphics context.
We pick up the size
We call dispalyimage with the current Graphics2d context and size
displayimage creates a buffered image and graphics 2d context based on the size
from the calling routine.
We get the height and width of the jpg file associated image.
Draw the image
Force the display with g2d.drawImage
The main method is identical to the last two examples in this section.
11.34Summary
There is a lot to this subject. I have only provided a very brief coverage. It is essential to
get a background to the field of computer graphics if you are going to use Java for graphi-
cal output.
11.35Problems
Try the examples out in this chapter.
I would also have a look at the examples that come with the Sun JDK. These came with an
early AWT based version.
ArcTest
BarChart
Blink
BouncingHeads
CardTest
DitherTest
DrawTest
Fractal
GraphLayout
GraphicsTest
ImageMap
ImageTest
JumpingBox
MoleculeViewer
NervousText
ScrollingImages
SimpleGraph
SpreadSheet
TicTacToe
TumblingDuke
UnderConstruction
WireFrame
They can all be found on the College web server in the demo directory, under the Java
home page.
The following is the source of the bouncing heads example. Taking this as a basis modify
the program to replace the images with your own. Look at the images with Netscape and
look at the size information that Netscape provides. The width and height variables contain
details of the expected sizes.
/*
* %W% %E%
*
* Copyright (c) 1994-1995 Sun Microsystems, Inc. All Rights
Reserved.
*
* Permission to use, copy, modify, and distribute this
software
import java.util.Hashtable;
import java.applet.*;
import java.io.*;
import java.awt.*;
import java.net.*;
/**
class BounceImage {
static float inelasticity = .96f;
static float Ax = 0.0f;
static float Ay = 0.0002f;
static float Ar = 0.9f;
public float x = 0;
public float y = 0;
public int width;
public int height;
public float Vx = 0.1f;
public float Vy = 0.05f;
public int index;
public float Vr = 0.005f + (float)Math.random() *
0.001f;
public float findex = 0f;
BounceItem parent;
static boolean imagesReadIn = false;
if (parent.bounceimages[i] == null) {
i = 0;
}
g.drawImage(parent.bounceimages[i], (int)x, (int)y,
null);
}
findex += Vr * deltaT;
if (collision_x || collision_y) {
Vr *= Ar;
}
}
}
boolean time_to_die;
AudioClip music;
AudioClip sounds[];
Image bounceimages[];
public BounceItem() {
}
try {
if (images == null) {
System.out.println("Making images ...");
makeImages(4);
}
if (music != null) {
music.loop();
}
lasttime = System.currentTimeMillis();
while (!time_to_die) {
int i;
long now = System.currentTimeMillis();
long deltaT = now - lasttime;
boolean active = false;
Dimension d = size();
img.step(deltaT);
if (img.Vy > .05 || -img.Vy > .05 ||
img.y + img.width < d.height - 10) {
active = true;
}
}
if (!active && images.length != 0) {
for (i = 0; i < images.length; i++) {
BounceImage img = images[i];
img.Vx = (float)Math.random() /
4.0f - 0.125f;
img.Vy = -(float)Math.random() /
4.0f - 0.2f;
img.Vr = 0.05f - (float)Math.ran-
dom() * 0.1f;
}
if (sounds[3] != null) {
sounds[3].play();
}
}
repaint();
lasttime = now;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
return;
}
}
} finally {
if (music != null) {
music.stop();
}
}
11.36Bibliography
One of the best books I've found is:
Foley, van Dam, Feiner, Hughes, Computer Graphics: Principles and Practice, Addison
Wesley.
• There is a good coverage of most of the things that you need to know. Not
cheap, about 35-40 uk pounds the last time I looked.
The other source of information is of course the on-line JDK documentation. This is a mix-
ture of actual inforation that actually is installed on the College web server or your own pc,
with links to the Sun site.
The documentation tells you what is on-line and what is on the Sun web server. A modem
is therefore very useful when working at home.
Sun also make available a lot of examples on their web site. I normally bookmark some of
the key components to make it easier to use with Netscape.
Lewis Carroll, Through the Looking Glass and What Alice found there.
Aims
The aims are to introduce some of facilities provided within the Abstract Windows
Toolkit for Windows programming. The examples are based on the early 1.0.x jdk.
There is a coverage of:–
buttons
labels
buttons and lables
scrollbars
checkboxes
checkboxgroups
list items
text fields
passwords
text fields on multiple lines
layout managers
flowlayout
gridlayout
gridbag layout with constraints
Chapter 12 AWT Based Windows Programming 190
12.1 Button
import java.awt.*;
public class c1110 extends java.applet.Applet
{
public void init()
{
Font f=new Font("Arial",Font.PLAIN,20);
setFont(f);
add(new Button(" QPR"));
add(new Button(" Arsenal"));
add(new Button(" Spurs"));
}
}
12.2 Label
import java.awt.*;
public class c1111 extends java.applet.Apple
{
public void init()
{
Font f=new Font("Arial",Font.PLAIN,20);
setFont(f);
add(new Label(" QPR"));
add(new Label(" Arsenal"));
add(new Label(" Spurs"));
}
}
12.4 Scrollbar
import java.awt.*;
public class c1113 extends java.applet.Applet
{
public void init()
{
add(new Scrollbar());
add(new Scrollbar(Scrollbar.HORIZONTAL));
}
}
12.6 Checkbox
import java.awt.*;
public class c1115 extends java.applet.Applet
{
public void init()
{
Font f=new Font("Arial",Font.PLAIN,20);
setFont(f);
add(new Checkbox(" QPR",null,true));
add(new Checkbox(" Arsenal"));
add(new Checkbox(" Spurs"));
}
}
12.8 List
import java.awt.*;
public class c1117 extends java.applet.Applet
{
public void init()
{
// Font f=new Font("Arial",Font.PLAIN,20);
// setFont(f);
List l=new List(3,false);
l.addItem(" Qpr");
l.addItem(" Arsenal");
l.addItem(" Spurs");
l.addItem(" Chelsea");
l.addItem(" Crystal Palace");
add(l);
}
}
12.9 TextField
import java.awt.*;
public class c1118 extends java.applet.Applet
{
public void init()
{
add(new TextField(" Who are you favourite London
team?",50));
add(new Label(" Who is your favourite player"));
add(new TextField(20));
}
}
12.10Passwords
import java.awt.*;
public class c1119 extends java.applet.Applet
{
public void init()
{
add(new Label(" Type in your password"));
TextField t=new TextField(20);
t.setEchoCharacter('*');
add(t);
}
}
12.11TextArea
import java.awt.*;
public class c1120 extends java.applet.Applet
{
public void init()
{
String s=" This is some text that is going\n" +
" to spread over several lines\n" +
" and use the control characters for \n" +
" end of line - as in c and c++";
add(new TextArea(s,10,10));
}
}
12.12Layout
There are a number of layout managers in Java. We look at each in turn and privide simple
examples.
The following methods apply to all 5 layout classes:–
add(String,component) add the component
remove(component) remove the component
layoutContainer() reshape the components in the container to
meet the requirements of the BorderLayout ob-
ject
minimumLayoutSize(container) return the minimum dimensions needed to lay-
out the components
preferredLayoutSize(container) return the preferred dimensions needed to lay-
out the components
12.12.1 Panels
The first thing to look at is the concept of dividing the screen up into panels. We can then
use the various layout managers within these panels.
12.12.2 FlowLayout
This is the simplest layout manager. The objects are displayed from left to right in the order
they are added to the screen.
import java.awt.*;
public class c1130 extends java.applet.Applet
{
public void init()
{
}
12.12.5 GridBagLayout
import java.awt.*;
public class c1133 extends java.applet.Applet
{
12.14Problems
Try the examples out in this chapter.
Aims
The aims of this chapter are to introduce some of the ideas involved in the use of
events in Java. This is an area where there have been major changes since the origi-
nal Java 1.0.x JDK.
Chapter 13 Events 198
13 Events
Java supports windows programming and therefore has to offer facilities for handling
events. This is another area where Java differs from conventional procedural programming.
In the first part of this chapter we will look at event handling based on the early 1.0.x jdk.
t1=new TextArea(5,10);
t1.setText(s);
t2=new TextArea(5,20);
b=new Button(" copy text -> ");
setLayout(new FlowLayout(FlowLayout.LEFT,5,5));
add(t1);
add(b);
add(t2);
return false;
}
}
13.1.4Example 2 – Simple mouse tracking
import java.applet.Applet;
import java.awt.*;
firsttime=true;
}
firsttime=false;
repaint();
return true;
}
}
g.setFont(f);
if (!first)
{
g.drawString(letter,50,50);
}
}
letter=String.valueOf((char)key);
first=false;
repaint();
return true;
}
return true;
}
}
CellEditorListener
CellEditorListener defines the interface for an object that listens to changes in a
CellEditor
ChangeListener
Defines an object which listens for ChangeEvents.
DocumentEvent
Interface for document change notifications.
DocumentEvent.ElementChange
Describes changes made to a specific element.
DocumentListener
Interface for an observer to register to receive notifications of changes to a text
document.
HyperlinkListener
HyperlinkListener
InternalFrameListener
The listener interface for receiving internal frame events.
ListDataListener
ListDataListener
ListSelectionListener
The listener that's notified when a lists selection value changes.
MenuDragMouseListener
Defines a menu mouse-drag listener.
MenuKeyListener
MenuKeyListener
MenuListener
Defines a listener for menu events.
MouseInputListener
A listener implementing all the methods in both the MouseListener and
MouseMotionListener interfaces.
PopupMenuListener
A popup menu listener
TableColumnModelListener
TableColumnModelListener defines the interface for an object that listens to
changes in a TableColumnModel.
TableModelListener
TableModelListener defines the interface for an object that listens to changes in
a TableModel.
TreeExpansionListener
The listener that's notified when a tree expands or collapses a node.
TreeModelListener
13.3 ActionListener
The listener interface for receiving action events. The class that is interested in processing
an action event implements this interface, and the object created with that class is registered
with a component, using the component's addActionListener method. When the action event
occurs, that object's actionPerformed method is invoked.
13.4 ActionEvent
A semantic event which indicates that a component-defined action occured. This high-level
event is generated by a component (such as a Button) when the component-specific action
occurs (such as being pressed). The event is passed to every every ActionListener object
that registered to receive such events using the component's addActionListener method.
The object that implements the ActionListener interface gets this ActionEvent when the
event occurs. The listener is therefore spared the details of processing individual mouse
movements and mouse clicks, and can instead process a "meaningful" (semantic) event like
"button pressed".
13.5 Example 1
This is taken from the Java Swing book. It is in several files.
/*
* CCPHandler.java
* A Cut, Copy, and Paste event handler. Nothing too
* fancy, just define
* some constants that can be used to set
* the actionCommands on buttons.
*/
import java.awt.event.*;
* * Metal
* * Windows
* * Motif
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public LnFListener(Frame f) {
frame = f;
}
if (e.getActionCommand().equals("Metal")) {
lnfName = "javax.swing.plaf.metal.MetalLookAndFeel";
} else if (e.getActionCommand().equals("Motif")) {
lnfName = "com.sun.java.swing.plaf.mo-
tif.MotifLookAndFeel";
} else {
lnfName = "com.sun.java.swing.plaf.win-
dows.WindowsLookAndFeel";
}
try {
UIManager.setLookAndFeel(lnfName);
SwingUtilities.updateComponentTreeUI(frame);
}
catch (UnsupportedLookAndFeelException ex1) {
System.err.println("Unsupported LookAndFeel: " +
lnfName);
}
catch (ClassNotFoundException ex2) {
System.err.println("LookAndFeel class not found: " +
lnfName);
}
catch (InstantiationException ex3) {
System.err.println("Could not load LookAndFeel: " +
lnfName);
}
catch (IllegalAccessException ex4) {
System.err.println("Cannot use LookAndFeel: " +
lnfName);
}
}
}
This is the third file.
/*
* ToolbarFrame4.java
* The Swing-ified button example.
* The buttons in this toolbar all carry
* images but no text.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public ToolbarFrame4() {
super("Toolbar Example (Swing no text)");
setSize(450, 250);
addWindowListener(new BasicWindowMonitor());
add(toolbar, BorderLayout.NORTH);
13.6 Example 2
This is taken from the Deitel book.
// Fig. 6.9: Craps.java
// Craps
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
switch ( sumOfDice ) {
case 7: case 11: // win on first roll
gameStatus = WON;
point.setText( "" ); // clear point text
field
break;
case 2: case 3: case 12: // lose on first roll
gameStatus = LOST;
point.setText( "" ); // clear point text
field
break;
default: // remember point
gameStatus = CONTINUE;
myPoint = sumOfDice;
point.setText( Integer.toString( myPoint )
);
firstRoll = false;
break;
}
}
else {
sumOfDice = rollDice();
if ( gameStatus == CONTINUE )
showStatus( "Roll again." );
else {
if ( gameStatus == WON )
showStatus( "Player wins. " +
"Click Roll Dice to play again." );
else
showStatus( "Player loses. " +
"Click Roll Dice to play again." );
firstRoll = true;
}
}
return workSum;
}
}
/*************************************************************
*************
* (C) Copyright 1999 by Deitel & Associates, Inc. and
Prentice Hall. *
* All Rights Reserved.
*
*
*
* DISCLAIMER: The authors and publisher of this book have
used their *
* best efforts in preparing the book. These efforts include
the *
* development, research, and testing of the theories and
programs *
* to determine their effectiveness. The authors and pub-
lisher make *
* no warranty of any kind, expressed or implied, with re-
gard to these *
* programs or to the documentation contained in these
books. The authors *
* and publisher shall not be liable in any event for inci-
dental or *
**************************************************************
***********/
Things to note:
we now extend JApplet
we in turn implement ActionListener – compare this with the previous example.
set up some variables
set up the graphical components within init()
over ride actionPerformed() – this calls play()
play actually plays the game.
roll the dice – this updates the text atrea.
These examples show two of the different ways that we can program event handling using
actionListener. We will come back to this area in more depth in later chapters.
13.7 Summary
Event driven programming takes a while to get used to. We will look at how this all works
in later chapters.
13.8 Problems
Try the examples out to see what happens.
Aims
14 Swing
It should be obvious by now that graphics programming requires some effort. It was real-
ised that the AWT was not adequate, and if Java was to succeed in the graphics area then
this had to be addressed. The AWT were tied to the local platform. The Java Foundation
Classes or JFC were created to ease the design and implementation of the user interface.
These include things that people take for granted with windows based software, e.g. menus,
dialog boxes etc. There is a coverage of each of them in this chapter. We will first look at
the history of the JFC and Swing.
14.1 History
The original JDK release that these examples were based on was 1.0.2. As you have seen
during the course some of the examples generate warning messages when compiled. This is
due to the evolution that is taking place with Java.
One of the major drawbacks of the early releases was the platform specific behaviour of
many program. Hardly write once and run anywhere.
JDK 1.1 fixed some of the problems. The new event model was a massive step forward, but
the AWT was still platform specific. Now we had an event subscriber model rather than a
chain based model. This eliminated a lot of the overhead of event propagation.
In April 1997 the JFC were announced. One of the new components were given the name
Swing. They JFC comprises:–
Swing
We will cover this in this chapter;
AWT
The basic gui;
Accessibility
This package is for people who find access using a keyboard, mouse and
screen a problem;
2D API
Package for painting, complex shapes, fonts etc;
Drag and Drop
This package allows users to implement a visual interface to their code.
Swing was based on both Netscape's Internet Foundation Classes and input from IBM's
Taligent division and Lighthouse Design.
Swing sits on top of AWT. Swing is written entirely in Java and has a consistent look and
feel across platforms.
14.8 Multithreading
You have already seen some of the problems that can occur with threads in an earlier chap-
ter. A swing component paints itself based on the state of the component. If the state
changes during the paint process what should happen? Incorrectly painting itself is obvi-
ously not acceptable. To handle this there is an event dispatch queue. This is a system
thread that handles the communication of evenets to other components.
14.9 Components
There a number of Swing components and they include:
Menus
Buttons
Dialog Boxes
List Boxes
Combo Boxes
Layout Managers
Tables
Trees
Undo
Look and Feel
We will look at each in turn and use the examples from the AWT chapter as our starting
point.
14.10Simple Examples
Given the sheer size of Swing we are only going to touch briefly on what can be done. In
this section we will simply rewrite the AWT examples to use Swing classes where possible
and simply compare the differences. What we will try in most cases is a minimal set of
changes to the original examples. Some will work, some won't.
We will look at the new ways of doing things later on in the chapter.
14.10.1 JButton
In this case we only have to make very minor changes. The first is the extra import line and
the simple replacement of Button with JButton.
import java.awt.*;
import javax.swing.*;
Compile and run this example. Compare with the AWT equivalent.
14.10.3 Button and Label
import java.awt.*;
import javax.swing.*;
14.10.6 CheckBox
import java.awt.*;
import javax.swing.*;
public class s1415 extends java.applet.Applet
{
public void init()
{
Font f=new Font("Arial",Font.PLAIN,20);
setFont(f);
add(new JCheckBox(" QPR",null,true));
add(new JCheckBox(" Arsenal"));
add(new JCheckBox(" Spurs"));
}
}
14.10.7 CheckBox with Grouping
import java.awt.*;
import javax.swing.*;
public class s1416 extends java.applet.Applet
{
public void init()
{
Font f=new Font("Arial",Font.PLAIN,20);
setFont(f);
JCheckBoxGroup g=new JCheckBoxGroup();
add(new JCheckBox(" QPR",g,false));
add(new JCheckBox(" Arsenal",g,false));
}
}
This example won't compile. Look at the on-line documentation and work out what we
need from Swing to replace what we have in the above AWT based example.
14.10.8 List
import java.awt.*;
import javax.swing.*;
public class s1417 extends java.applet.Applet
{
public void init()
{
// Font f=new Font("Arial",Font.PLAIN,20);
// setFont(f);
JList l=new JList(3,false);
l.addItem(" Qpr");
l.addItem(" Arsenal");
l.addItem(" Spurs");
l.addItem(" Chelsea");
l.addItem(" Crystal Palace");
add(l);
}
}
This compiles with 6 error messages. Do you think it will run? Try it what. What do you
think has happened?
14.10.9 TextField
import java.awt.*;
import javax.swing.*;
public class s1418 extends java.applet.Applet
{
public void init()
{
add(new JTextField(" Who are you favourite London
team?",50));
add(new JLabel(" Who is your favourite player"));
add(new JTextField(20));
}
}
14.10.10 Passwords
import java.awt.*;
import javax.swing.*;
public class s1419 extends java.applet.Applet
{
public void init()
{
add(new JLabel(" Type in your password"));
JTextField t=new JTextField(20);
t.setEchoCharacter('*');
add(t);
}
}
This example won't compile. Have a look at the on-line documentation and make the neces-
sary changes to make it work.
14.10.11 TextArea
import java.awt.*;
import javax.swing.*;
14.11Layout
14.11.1 Panels
A Panel is the simplest container class. A panel provides space in which an application can
attach any other component, including other panels.
14.11.2 FlowLayout
import java.awt.*;
import javax.swing.*;
public class s1430 extends java.applet.Applet
{
public void init()
{
14.11.3 GridLayout
Not available at this time.
14.11.4 Gridlayout with size
Not available at this time.
14.11.5 GridBagLayout
Not available at this time.
14.11.6 CardLayout
Not available at this time.
14.11.7 Simple Graph Plotting – AWT Based
This example shows how to plot a sine curve, and it does so using an AWT based ap-
proach.
import java.awt.*;
import java.lang.Math.*;
int angled;
double angler;
g.setColor(Color.blue);
for (angled=0;angled<361;++angled)
{
x = angled;
g.drawLine(x,y,x,y);
angler = angled*2*Math.PI/360;
}
}
}
Things to note include:
The origin at the top left causes a few problems.
We are forced to shift the y values down and in this exam-
ple I have chosen 180.
I have also scaled the values returned by the sine function.
We are forced to qualify both PI and the sine function with Math. This is a little
verbose.
14.11.8 Simple Graph Plotting – Swing Based
This is the same example but now we use the new Swing way of doing things.
import java.awt.*;
import javax.swing.JApplet;
import java.lang.Math.*;
{
int x=0;
int y=180;
int angled;
double angler;
g.setColor(Color.blue);
for (angled=0;angled<361;++angled)
{
x = angled;
g.drawLine(x,y,x,y);
angler = angled*2*Math.PI/360;
}
}
}
Things to note include:
This example will not run under Netscape 4.5 It generates a class not found error
for Javax.Swing.JApplet.
It will run under the Appletviewer that comes with the 1.2.2 JDK.
We are now using the enhanaced functionality provided by JApplet over the
original Applet. This is done using:
import javax.swing.JApplet;
We extend JApplet using:
public class c1184 extends javax.swing.JApplet
The rest of the code is identical.
14.12Inheritence Revisited
You have now seen the power of OO programming and the benefits it has to offer. We have
been able to accept the default behaviour of most of the classes we have used and rely on
the fact that a lot of complexity is hidden from us.
You have also seen that there is more than one way to acheive something within Java in a
lot of cases. Part of this is due to the fact that Sun released Java as an incomplete language
and it has evolved in response to the demands that people have made on it. Java is now be-
ing used in areas well beyond what it was originally capable of doing.
We are now going to look at two ways of doing things within Swing. The first will inherit
from JApplet. The second will inherit from JComponent
14.13JApplet
JApplet is well down the Java class hierarchy, and this is shown below.
14.15Examples
Chapters 12 and 13 of the Deitel book look at basic and advanced gui programming. I
would recommend looking at some of these examples to see the newer and better ways of
doing things.
The Eckstein book has a very comprehensive coverage. Over 1200 pages.
Sun provide a very comprehensive demonstration program that can be found on the College
web server. The url is:
http://www.kcl.ac.uk/kis/support/cit//fortran/java/jdk1.2.2/jfc/SwingSet/
I would recommend trying to run this. You will need to get all the source java files and
then compile them and run under the appletviewer. If you have the jdk installed on your
machine they are in the demo directory hanging off the root of the installation. There are
about 30 files, taking up 320Kb on my local hard disk.
14.16Problems
0. Try the programs out in this chapter, especially the SwingSet demo.
14.17Bibliography
The major sources I used during the development of these examples include:
The on-line jdk documentation.
This is essential. The information you need will be there
but digging it out may take a long time.
Deitel and Deitel, Java: How to Program, Prentice Hall, various versions.
Very good general coverage of the whole of the Java lan-
guage. The two chapters on graphical user interface pro-
gramming are enough to get you started.
Eckstein, Loy, Wood, Java Swing, O'Reilly
Really good coverage of Swing. Much deeper coverage
than the first.
Foley, van Dam, Feiner, Hughes, Computer Graphics, Addison Wesley
Java now offers very good functionality in the graphics
area. I'd get hold of a copy to fill in the missing gaps.
Descartes.
Aims
15 JavaBeans
When we look at programming with older langauges (Fortran 66 and Fortran 77, C, the
original Pascal) they support so called procedural programming. Fortran 90 adds object
based programming and C++ adds object oriented programming. Java is completely object
based. With the addition of Java Beans we have added one more programming paradigm –
reusabe software components. They enable us to construct solutions based on using building
blocks.
JavaBeans can be used to create applications or applets. They can be simple, such as a text
box or label, or they can be complex, such as a mail tool or a data inspector. Beans typi-
cally have a set of:
properties: are the attributes exposed by a bean
methods: are the actions that a bea makes available for use by other beans.
events. the events that the bean makes happen.
JavaBeans is a component architecture for the Java platform. ActiveX is Microsoft's offer-
ing.
The following is taken verbatim from the Sun blurb about JavaBeans. I couldn't resist!
THE CHOICE IS CLEAR: Write to the JavaBeansTM Component Architecture.
Throughout the industry, JavaBeans component architecture is the architecture of
choice. More than 1,000,000 developers around the world have already embraced
the JavaTM platform. And no wonder. The Java platform has opened up an entirely
new world of opportunities for building fully portable network-aware applications.
Yet many developers are not yet sure how best to take advantage of the capabilities
and benefits the Java platform delivers without sacrificing their existing investment
in legacy applications. The Answer is JavaBeans Component Architecture
JavaBeans component architecture is the platform-neutral architecture for the Java
application environment. It's the ideal choice for developing or assembling net-
work-aware solutions for heterogeneous hardware and operating system environ-
ments—within the enterprise or across the Internet. In fact, it's the only component
architecture you should consider if you're developing for the Java platform.
JavaBeans component architecture extends "Write Once, Run AnywhereTM" capa-
bility to reusable component evelopment. In fact, the JavaBeans architecture takes
interoperability a major step forward—your code runs on every OS and also within
any application environment. A beans developer secures a future in the emerging
network software market without losing customers that use proprietary platforms,
because JavaBeans components interoperate with ActiveX. JavaBeans architecture
connects via bridges into other component models such as ActiveX. Software com-
ponents that use JavaBeans APIs are thus portable to containers including Internet
Explorer, Visual Basic, Microsoft Word, Lotus Notes, and others.
The JavaBeans specification – which was completed ahead of schedule – defines a
set of standard component software APIs for the Java platform. The specification
was developed by Sun with a number of leading industry partners and was then re-
fined based on broad general input from developers, customers, and end-users dur-
ing a public review period.
Better than apple pie, mum, etc.
If you have used Visual Basic or Delphi you will be familiar with the way in which you can
develop a program using a visual interface. Look at the screen shot on the next page when
reading the following. With Visual Basic you drag and drop tools from the toolbar on the
left and drop them onto the form in the middle. You then alter the state of the object by us-
ing the propertires displayed on the right hand side. This process is similar in all visual de-
velopment environments, just the words and phrases change.
This is called visual development. You don't actually have to write any code – or so the
claims go.
JavaBeans in conjunction with java.awt.dnd opens up this possibility with Java.
To do this properly you obviously need a graphical work environment. We have been com-
piling from the unix or dos prompt so far.
I recommend getting hold of IBM Visual Age for Java and installing that. The entry level
version is free of charge.
I would also recommmend getting hold of the BeanBox Development Kit. This enables you
to test out your beans. The url is given later in this chapter.
Java Beans will obviously vary in functionality but will have one or more of the following
attributes:
Introspection: looking inside and finding out how a bean works.
Customization: how to alter the appearance and behavior of a bean.
Event handling: events they can handle and events they generate
Properties: beans can be programmed and customised
Persistence: saving state information, e.g. saving a word processing document.
15.3 Example 1
This example is a complete reworking of the earlier example of a moving graphics image.
Rather than use AWT I've moved over to the swing way of doing things. I have also used
the networking component to use a url to locate the image.
package jbean01;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
public bean01()
{
img = new ImageIcon();
URL url;
url = getClass().getResource("joan01.gif");
int xpos;
int ypos=10;
if ( img.getImageLoadStatus() == MediaTracker.COMPLETE)
{
for (xpos=10;xpos<=400;xpos+=50)
{
img.paintIcon(this,g,xpos,ypos);
ypos += +50;
try {Thread.sleep(50);}
catch(InterruptedException e) {}
}
}
}
app.getContentPane().add(joanbean , BorderLayout.CENTER);
app.addWindowListener
(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
app.setSize(400,400);
app.show();
}
}
Note that the first line of the program is a package statement. We put classes into a package
when working with beans. There is also an additional compilation option required, and this
would be in the above case:
javac -d . bean01.java
where . is the current directory. The development environment is set up to create a subdi-
rectory based on your package name. In this case you will end up with the compiled class
file in jbean01.
After successful compilation we then need to create the Java Archive File or .jar file. You
can put more than one bean into a jar file. We do this with the following command:
jar cfm bean01.jar manifest.tmp jbean01\*.*
and note again that everything will refers to this sub-directory.
The manifest file is required and I've followed the Sun naming convention, calling it mani-
fest.tmp. The manifest file from this example is given below:
Main-Class: jbean01.bean01
Name: bean01.class
Java-Bean: True
The next major difference occurs when defing our own class bean01. In this case we now
have an additioal element in the function header and this is Serializable. This means that the
state of the bean is remembered. Another term for this is persistence.
When developing this example I didn't rebuild the jar file after recompiling the Java source
and it ran as before.
You can examine the archive with:
jar tvf bean01.jar
We run the program with the following command:
java -jar bean01.jar
15.4 Summary
I've only briefly touched on what beans can do in this chapter. They really come into their
own when used in conjuction with a visual development environment.
We are currently trying to install Netbeans on Gum. I will notify people when we have
successully installed it and I'll provide details on how to use the environment.
You also have details of IBM Visual Age for Java and I would recommed installing that on
your pc and working through the pdf documentation. More details are in the chapter on
IBM Visual Age for Java.
http://java.sun.com/beans/training.html
links to both instructor led and on line training resources specifically for
JavaBeans component developers.
http://developer.java.sun.com/developer/onlineTraining/index.html
Links to Java Beans training material.
http://developer.java.sun.com/developer/onlineTraining/Beans/EJBTutorial/index.html
Enterprise JavaBeansTM Tutorial: Building Your First Stateless Session Bean
15.6 Problems
Try converting some of your existing Java programs to a bean. Be prepared to devote some
time to this!
Aims
The aims of this chapter are look at some of the development environments available, both
free and commercial.
Chapter 16 Overview of Development Environments 236
and they vary quite considerably from the very straighforward to extremely complex. The
Salford Fortran 90 and 95 compilers come with a simple environment called Plato. The
Compaq Fortran compiler works within Microsoft Developer Studio which is a very com-
plex environment that takes some time to get on top off. The following screen shots show
these.
These are normaly the most costly, but they do offer considerable benefits (eventually) in
terms of speed of development. Putting a visual interace onto a program is obviously going
to be much easier using visual development tools, rather than raw programming.
16.4 Problems
Aims
The aims of this chapter are to provide an overview of Sun's offerings in this area.
Chapter 17 Forte for Java 240
17.3 Documentation
Sun provide 3 documents that can be printed in the release I installed:
QuickStart – 36 pages
Tutorials – 38
UserGuide – 299
and these are all Adobe PDF format. I recommend printing them, and working through the
first two to help you familiarise yourself with the environment.
There is extensive on-line help. More difficult to work with though.
Lewis Carroll, Through the Looking Glass and What Alice Found There.
Aims
The aims of this chapter are to provide a brief coverage of Microsoft Visual J++.
Chapter 18 Microsoft Visual J++ 242
following the links to the Java documentation and work through that. The Cowell book is
another option.
Microsoft J++
Visual J++ Reference: Contains comprehensive reference information for the Vi-
sual J++ Code Model, extensibility, conditional compilation, reserved words, and
compiler errors.
Samples: Provides a rich collection of ready-to-run samples that illustrate key
technologies.
Located elsewhere in the MSDN Library, the following documentation sets can be found:
Java Package Manager
ActiveX Data Objects (ADO)
Remote Data Service (RDS)
Database Designer
Query Designer
VBScript
JScript
Active Server Pages (ASP) and server script
Microsoft Transaction Server
18.7 Bibliography
Cowell J., Essential Visual J++ 6.0 Fast, Springer.
Quick introduction. Walks you through the use of the development environment and
worth it for that alone. No coverage of Swing of course.
The aim of this chapter is to provide a brief introduction to IBM Visual Age for Java.
Chapter 19 IBM VisualAge for Java 248
alphaWorks moved into the IBM Almaden Research Center in January 1997, and relocated
once more to the IBM Center for Java Technology in Cupertino, CA.
19.2.4 Other Offerings
A beta version of VisualAge Professional Edition 3.0 is also available. Typically we are
looking at 80-100 Mb. I don't recommend downloading this at home over the telephone
line.
I have a copy of:–
Nilsson D.R., Jakab P.M., Developing JavaBeans Using VisualAge for Java, Wiley
and the CD has the following on it:–
VisualAge for Java Entry Edition 1.0
VisualAge for Java Patch Set 1
Sun Java Developers Toolkit 1.1.5
Sun Java Runtime Environment 1.1.5
Take care when buying a book with a CD to get hold of as recent a version as you can.
19.3 Documentation
IBM provide a lot of documentation in Adobe Acrobat Portable Document Format. Acrobat
readers are free over the web. The following url:–
http://www.kcl.ac.uk/www/adoacr.html
provides more information.
19.3.1 IDE Basics: Concepts and Tasks: 34 pages
How to use the integrated development environment. Print this guide if you can. Have a
quick browse to get a feel for some of the things you will need to know to develop a Java
applet.
19.3.2 Getting Started: 144 pages
General introduction to using the basic features of Visual Age for Java. Print this guide if
you can. I would work through the following chapters:
Chapter 2: The Basics
Chapter 3: Building your first applet
at least. I would also work through:–
Chapter 4: Adding State Checking to your Applet
Chapter 5: Enhancing the To-Do List Program
Chapter 6: What Else can you do with the Visual Composition Editor
Chapter 6 takes you through the use of working with Beans including:
manipulating beans
moving them around
changing their properties
connecting beans
There is also a coverage of working with relational using the select bean.
19.4 Installation
Follow the installation guidelines for which ever version you have.
19.5 Overview
If you are used to thinking in terms of a program being made up of one or more source files
and going through the following cycle:–
edit
compile
link – if no errors
run
then the first time you meet a development environment can be quite a shock. Both
Microsoft Visual Basic and Developer Studio take a while to get used to. Visual Basic also
introduces the concept of visual development where one can drap and drop visual compo-
nents. Well VisualAge for Java takes things one step further.
The workbench and components are object based, rather than file based. You need to think
in terms of
projects
packages
classes
interfaces
methods
and the hierarchy associated with these will provide a structure.
I am used to working with directories when programming and typically organise my work
into:
f90: fortran 90 code
f95: fortran 95 code
java: java code
cxx: c++ code
This no longer works very well when working with a development environment. You can
use the above but you have to add directories below the above to keep related work files.
This is true when working with:
Compaq/Dec Fortran 95 under Microsoft Visual Studio
Microsoft Visual C++ under Visual Studio
Microsoft Visual J++
IBM VisualAge for Java
Don't point one of the Java programming environments at your Java directory. It will try
reading everything in and compiling it!
1 Opening Screen
As you can see we have a similar layout to Visual Basic which we looked at in an earlier
chapter. The key things to note are:
the left hand side has the tools - in this case Beans
the middle is where we can lay things out.
there are a variety of toolbars, menus etc to enable us to work with the environ-
ment and develop our applet.
The composition editor provides with access to four sets of beans. These are:
swing
awt
other
available, and under available we have:
IBM Data Access Beans: Select and DB Navigator
Domino Java Class Library 4.6.1
Sun BDK Examples 1.0
IBM Domino Examples 2.0
Sun JDK Examples 1.1.6
Sun JFC Examples 1.0.2
IBM Java Examples 2.0
19.7 Summary
Follow the instructions in the two documents and be patient. It takes a while to get used to
working in this new way. The key feature is the way that everything is based around beans.
This is a major step forward when developing professional Java applets. The learning curve
is steep, but your productivity will increase.
The aims of this chapter are to provide a brief coverage of standardisation efforts, imple-
mentation differences and future developments.
Chapter 20 Multimedia 254
20 Multimedia
For more general capabilities you will need to download the Sun Java Media Framework.
Visit
http://java.sun.com/products/java-media/jmf/
There are verisons for Windows and Solaris.
The JavaTM Media Framework (JMF) is an application programming interface (API) for
incorporating time-based media into Java applications and applets. The JMF 1.0 API ( the
Java Media Player API) enabled programmers to develop Java programs that presented
time-based media. The JMF 2.0 API extends the framework to provide support for captur-
ing, storing, and broadcasting media data, using custom codecs, and manipulating media
data before it is rendered.
The JMF 2.0 API was developed by Sun Microsystems, Inc. and IBM. The JMF 1.0 API
was developed by Sun Microsystems, Inc., Silicon Graphics Inc., and Intel Corporation.
JMF 2.0 supports a wide array of media types, including
protocols: FILE, HTTP, FTP, RTP
audio: AIFF, AU, AVI, GSM, MIDI, MP2, MP3, QT, RMF, WAV
video: AVI, MPEG-1, QT
other: Flash 2, HotMedia
20.2 java.applet
20.2.1 Interface AudioClip: Since: JDK1.0
public interface AudioClip
The AudioClip interface is a simple abstraction for playing a sound clip. Multiple
AudioClip items can be playing at the same time, and the resulting sound is mixed together
to produce a composite.
20.2.2 Method Summary
void loop()
Starts playing this audio clip in a loop.
void play()
Starts playing this audio clip.
void stop()
Stops playing this audio clip.
20.2.3 Method Detail
play
public void play()
Starts playing this audio clip. Each time this method is called, the clip is re-
started from the beginning.
loop
public void loop()
currentSound =
chooseSound.getSelectedIndex() == 0 ?
sound1 : sound2;
}
}
);
c.add( chooseSound );
sound1 = getAudioClip(
getDocumentBase(), "welcome.wav" );
sound2 = getAudioClip(
getDocumentBase(), "hi.au" );
currentSound = sound1;
}
}
}
}
/*************************************************************
*************
* (C) Copyright 1999 by Deitel & Associates, Inc. and
Prentice Hall. *
* All Rights Reserved.
*
*
*
* DISCLAIMER: The authors and publisher of this book have
used their *
* best efforts in preparing the book. These efforts include
the *
* development, research, and testing of the theories and
programs *
* to determine their effectiveness. The authors and pub-
lisher make *
* no warranty of any kind, expressed or implied, with re-
gard to these *
* programs or to the documentation contained in these
books. The authors *
* and publisher shall not be liable in any event for inci-
dental or *
* consequential damages in connection with, or arising out
of, the *
* furnishing, performance, or use of these programs.
*
**************************************************************
***********/
Try it out. Obviously you will need a sound card and speakers to hear anything.
There are two sound file format files used in this example:
wav
au
If you have a pc try:
dir /s /p *.wav
from the root of your c drive to see what wav files you have.
Java 1.3 increases the support considerably in this area.
20.4 Problems
Try the example out on the pc. You obviously need a sound card and speakers. Have a look
at what sounds Microsoft provide. Can you get them to play?
21 Simple Networking
This chapter looks at using Java for networking.
URLDecoder: The class contains a utility method for converting from a MIME format
called "x-www-form-urlencoded" to a String
URLEncoder: The class contains a utility method for converting a String into a MIME for-
mat called "x-www-form-urlencoded" format.
URLStreamHandler: The abstract class URLStreamHandler is the common superclass for
all stream protocol handlers.
21.1.3 Exception Summary
BindException: Signals that an error occurred while attempting to bind a socket to a local
address and port.
ConnectException: Signals that an error occurred while attempting to connect a socket to a
remote address and port.
MalformedURLException: Thrown to indicate that a malformed URL has occurred.
NoRouteToHostException: Signals that an error occurred while attempting to connect a
socket to a remote address and port.
ProtocolException: Thrown to indicate that there is an error in the underlying protocol, such
as a TCP error.
SocketException: Thrown to indicate that there is an error in the underlying protocol, such
as a TCP error.
UnknownHostException: Thrown to indicate that the IP address of a host could not be de-
termined.
UnknownServiceException: Thrown to indicate that an unknown service exception has oc-
curred.
21.2 Examples
There are a couple of examples in this chapter.
21.2.1Manipulating urls
import java.awt.*;
import java.net.*;
import java.applet.Applet;
sites[0]=new Site("Home",
"http://www.kcl.ac.uk/kis/support/cc/fortran/");
sites[2]=new Site("C++",
"http://www.kcl.ac.uk/kis/support/cc/for-
tran/cpp/cpp.html");
sites[3]=new Site("Java",
"http://www.kcl.ac.uk/kis/support/cc/for-
tran/java/javahome.html");
if ( title.equals( arg.toString() ) ) {
gotoSite( location );
return true; // event handled
}
}
}
try {
location = new URL( siteLocation );
}
catch ( MalformedURLException e ) {
System.err.println( "Invalid URL: " + siteLocation
);
}
}
try
{
fileURL = new URL(
"http://www.kcl.ac.uk/kis/sup-
port/cc/staff/ian.html" );
}
catch ( MalformedURLException e )
{
showStatus( "Exception: " + e.toString() );
}
}
try
{
input = fileURL.openStream();
dataInput = new DataInputStream( input );
contents.setText( "Replace with your ego trip:\n"
);
dataInput.close();
}
catch ( IOException e )
{
showStatus( "Exception: " + e.toString() );
}
}
}
What do you notice about the output?
The original source file is on the college web server. Save the file and have a look at it in
an editor.
21.3 Problems
Try out the examples in this chapter. Try them out on Gum and your own pc. They are also
on the College web server. Run them from there using Netscape.
The aims of this chapter are to provide a brief coverage of web data access.
Chapter 22 Web Data Access 266
22.2 Java
Java obviously has to work in a similar fashion. So you need at least:
a database on a web accessible machine
a jdbc driver for that database
a web server process to handle the jdbc request
22.3.2 Microsoft
If you have Office then you may already have Access. This combined with Microsoft Vi-
sual J++ should be enough to get you started.
Another possibility would be SQL server, but this would imply NT as well. I am not sure of
the cost of SQL server for NT.
22.3.2.1 Some entries from the FAQ
Are there any ODBC drivers that do not work with the JDBC-ODBC Bridge?
Most ODBC 2.0 drivers should work with the Bridge. Since there is some varia-
tion in functionality between ODBC drivers, the functionality of the bridge may
be affected. The bridge works with popular PC databases, such as Microsoft Ac-
cess and FoxPro.
How can I use the JDBC API to access a desktop database like Microsoft Access over the
network?
Most desktop databases currently require a JDBC solution that uses ODBC un-
derneath. This is because the vendors of these database products haven't imple-
mented all-Java JDBC drivers. The best approach is to use a commercial JDBC
driver that supports ODBC and the database you want to use. See the JDBC
drivers page for a list of available JDBC drivers. The JDBC-ODBC bridge from
Sun's Java Software does not provide network access to desktop databases by it-
self. The JDBC-ODBC bridge loads ODBC as a local DLL, and typical ODBC
drivers for desktop databases like Access aren't networked. The JDBC-ODBC
bridge can be used together with the RMI-JDBC bridge , however, to access a
desktop database like Access over the net. This RMI-JDBC-ODBC solution is
free.
Does the JDBC-ODBC Bridge work with Microsoft J++?
No, J++ does not support the JDBC-ODBC bridge since it doesn't implement the
Java Native Interface (JNI). Any all-Java JDBC driver should work with J++,
however.
22.3.3IBM
DB2 would imply using OS/2 as your data source and Visual Age for Java.
22.5.2.4 Time
A thin wrapper around java.util.Date that allows JDBC to identify this as a SQL TIME
value.
22.5.2.5 Timestamp
This class is a thin wrapper around java.util.Date that allows JDBC to identify this as a
SQL TIMESTAMP value.
22.5.2.6 Types
The class that defines constants that are used to identify generic SQL types, called JDBC
types.
22.5.3 Exception Summary
22.5.3.1 BatchUpdateException – JDBC 2.0
22.5.3.2 DataTruncation
An exception that reports a DataTruncation warning (on reads) or throws a DataTruncation
exception (on writes) when JDBC unexpectedly truncates a data value.
22.5.3.3 SQLException
An exception that provides information on a database access error.
22.5.3.4 SQLWarning
An exception that provides information on database access warnings.
22.6.1.9 RowSetReader
An object implementing the RowSetReader interface may be registered with a RowSet ob-
ject that supports the reader/writer paradigm.
22.6.1.10 RowSetWriter
An object that implements the RowSetWriter interface may be registered with a RowSet ob-
ject that supports the reader/writer paradigm.
22.6.1.11 XAConnection
An XAConnection object provides support for distributed transactions.
22.6.1.12 XADataSource
A factory for XAConnection objects.
22.6.2 Class Summary
22.6.2.1 ConnectionEvent
The ConnectionEvent class provides information about the source of a connection related
event.
22.6.2.2 RowSetEvent
A RowSetEvent is generated when something important happens in the life of a rowset, like
when a column value changes.
22.7 Examples
Deitel provides three examples. You will need to register the Access database with the
ODCB manager which is in the control panel. They are in chapter 18. You will need to
download all of the files and try them out on a pc. Register them as a User Data Source
Name. Choose the Access driver.
Look carefully at the Deitel source. Yoy need to ensure that you register the database with
the same names as those used in the Java source.
You need a basic understanding of SQL and the relational model. I've provided references
at the end of this chapter.
I have Access installed and used this to look at the databases provided. This enables to see
much more about the databases concerned.
Note that
22.8 Summary
If you have Microsoft Visual J++ then you can try out jdbc using this.
If you are going to try out anything original then you will need Access to create your own
databases. Various versions of Microsoft Office include Access.
22.9 Bibliography
Cannen S., Otten G., SQL: The Standard Handbook, McGraw Hill
This is a very good reference text to the SQL standard.
Date C., An Introduction to Database Systems, Addison Wesley.
One of the most prolific writers about database systems.
Pratt P.J., A Guide to SQL, Boyd and Fraser.
Very good gentle introduction with clear examples.
Rbase Technologies Inc., Rbase 2000, Release 6.5, Rbase Technologies Inc.
23 Servlets
The basic idea of a servlet is that of a program that runs on a web server and provides a
service to other programs that make requests to it.
They are written in Java and have access to the Java API. This obviously includes the
JDBC API to access databases and Sun saw their initial use to provide secure web-based
access to data which is presented using HTML web pages, interactively viewing or modify-
ing that data using dynamic web page generation techniques.
Sun also see servlets as a popular choice for building interactive web applications.
Third-party Servlet containers are available for Apache Web Server, iPlanet Web Server
(formerly Netscape Enterprise Server), Microsoft IIS, and others. Servlet containers can also
be integrated with web-enabled application servers, such as BEA WebLogic Application
Server, IBM WebSphere, Netscape Application Server, and others.
./etc:
1696 Apr 27 1999 SimpleStartup.java
./examples:
./examples/WEB-INF:
./examples/WEB-INF/jsp:
./examples/WEB-INF/jsp/beans:
./examples/WEB-INF/jsp/beans/cal:
1630 Apr 21 1999 Entries.class
1088 Apr 27 1999 Entries.java
771 Apr 21 1999 Entry.class
586 Apr 27 1999 Entry.java
3112 Apr 21 1999 JspCalendar.class
2949 Apr 27 1999 JspCalendar.java
2018 Apr 21 1999 TableBean.class
1890 Apr 27 1999 TableBean.java
./examples/WEB-INF/jsp/beans/colors:
1858 Apr 21 1999 ColorGameBean.class
2788 Apr 27 1999 ColorGameBean.java
./examples/WEB-INF/jsp/beans/error:
463 Apr 21 1999 Smart.class
231 Apr 27 1999 Smart.java
./examples/WEB-INF/servlets:
3265 Apr 21 1999 CookieExample.class
3398 Apr 27 1999 CookieExample.java
1721 Apr 21 1999 HelloWorldExample.class
1714 Apr 27 1999 HelloWorldExample.java
1354 Apr 27 1999 LocalStrings.properties
2251 Apr 21 1999 RequestHeaderExample.class
2153 Apr 27 1999 RequestHeaderExample.java
2464 Apr 21 1999 RequestInfoExample.class
2814 Apr 27 1999 RequestInfoExample.java
2661 Apr 21 1999 RequestParamExample.class
2973 Apr 27 1999 RequestParamExample.java
3407 Apr 21 1999 SessionExample.class
3574 Apr 27 1999 SessionExample.java
./examples/images:
292 Apr 21 1999 code.gif
1242 Apr 21 1999 execute.gif
1231 Apr 21 1999 return.gif
./examples/servlets:
1895 Apr 21 1999 cookies.html
1854 Apr 21 1999 helloworld.html
./src:
./src/javax:
./src/javax/servlet:
12920 Apr 27 1999 GenericServlet.java
234 Apr 27 1999 LocalStrings.properties
4634 Apr 27 1999 RequestDispatcher.java
6846 Apr 27 1999 Servlet.java
3147 Apr 27 1999 ServletConfig.java
16714 Apr 27 1999 ServletContext.java
3957 Apr 27 1999 ServletException.java
3169 Apr 27 1999 ServletInputStream.java
8939 Apr 27 1999 ServletOutputStream.java
12239 Apr 27 1999 ServletRequest.java
6269 Apr 27 1999 ServletResponse.java
1813 Apr 27 1999 SingleThreadModel.java
5802 Apr 27 1999 UnavailableException.java
./src/javax/servlet/http:
15649 Apr 27 1999 Cookie.java
32100 Apr 27 1999 HttpServlet.java
14856 Apr 27 1999 HttpServletRequest.java
18425 Apr 27 1999 HttpServletResponse.java
10584 Apr 27 1999 HttpSession.java
2950 Apr 27 1999 HttpSessionBindingEvent.java
1966 Apr 27 1999 HttpSessionBindingListener.java
1895 Apr 27 1999 HttpSessionContext.java
8826 Apr 27 1999 HttpUtils.java
720 Apr 27 1999 LocalStrings.properties
./src/javax/servlet/jsp:
622 Apr 27 1999 HttpJspPage.java
660 Apr 27 1999 JSPPage.java
./tmp:
./tmp/1b6f5a49:
./tmp/35475a49:
./webpages:
1967 Apr 28 1999 index.html
./webpages/WEB-INF:
235 Apr 27 1999 mappings.properties
2138 Apr 27 1999 mime.properties
300 Apr 27 1999 servlets.properties
324 Apr 27 1999 webapp.properties
./webpages/WEB-INF/servlets:
1047 Jul 11 13:16 HTTPGetServlet.class
5293 Apr 21 1999 SnoopServlet.class
4898 Apr 27 1999 SnoopServlet.java
./webpages/docs:
./webpages/docs/api:
2506 Apr 21 1999 allclasses-frame.html
10258 Apr 21 1999 deprecated-list.html
7789 Apr 21 1999 help-doc.html
83183 Apr 21 1999 index-all.html
756 Apr 21 1999 index.html
942 Apr 21 1999 overview-frame.html
4289 Apr 21 1999 overview-summary.html
7247 Apr 21 1999 overview-tree.html
33 Apr 21 1999 package-list
618 Apr 21 1999 packages.html
7183 Apr 21 1999 serialized-form.html
1240 Apr 21 1999 stylesheet.css
./webpages/docs/api/javax:
./webpages/docs/api/javax/servlet:
27030 Apr 21 1999 GenericServlet.html
12099 Apr 21 1999 RequestDispatcher.html
15433 Apr 21 1999 Servlet.html
10447 Apr 21 1999 ServletConfig.html
33416 Apr 21 1999 ServletContext.html
12917 Apr 21 1999 ServletException.html
10649 Apr 21 1999 ServletInputStream.html
22170 Apr 21 1999 ServletOutputStream.html
27468 Apr 21 1999 ServletRequest.html
15027 Apr 21 1999 ServletResponse.html
6147 Apr 21 1999 SingleThreadModel.html
15644 Apr 21 1999 UnavailableException.html
1939 Apr 21 1999 package-frame.html
7671 Apr 21 1999 package-summary.html
6194 Apr 21 1999 package-tree.html
10677 Apr 21 1999 package-use.html
./webpages/docs/api/javax/servlet/class-use:
5830 Apr 21 1999 GenericServlet.html
6043 Apr 21 1999 RequestDispatcher.html
./webpages/docs/api/javax/servlet/http:
27615 Apr 21 1999 Cookie.html
36459 Apr 21 1999 HttpServlet.html
33325 Apr 21 1999 HttpServletRequest.html
53488 Apr 21 1999 HttpServletResponse.html
21842 Apr 21 1999 HttpSession.html
12208 Apr 21 1999 HttpSessionBindingEvent.html
9306 Apr 21 1999 HttpSessionBindingListener.html
8509 Apr 21 1999 HttpSessionContext.html
13297 Apr 21 1999 HttpUtils.html
1556 Apr 21 1999 package-frame.html
7080 Apr 21 1999 package-summary.html
6360 Apr 21 1999 package-tree.html
7362 Apr 21 1999 package-use.html
./webpages/docs/api/javax/servlet/http/class-use:
6737 Apr 21 1999 Cookie.html
4338 Apr 21 1999 HttpServlet.html
11913 Apr 21 1999 HttpServletRequest.html
10684 Apr 21 1999 HttpServletResponse.html
8635 Apr 21 1999 HttpSession.html
6799 Apr 21 1999 HttpSessionBindingEvent.html
4451 Apr 21 1999 HttpSessionBindingListener.html
6137 Apr 21 1999 HttpSessionContext.html
4324 Apr 21 1999 HttpUtils.html
23.1.1 Notes
23.1.1.1 Jar files
Copy the:
server.jar
and
servlet.jar
files in the root directory into:
F:\jdk1.2.2\jre\lib\ext
This is the JDK extensions directory. You can't compile and run servlets without doing this.
23.1.1.2 Start the server
You must start the server. This is done by running the
startserver.bat
file which is in the following directory:
f:\jdk1.2.2\jsdk2.1
on my system.
I get variable results with this. Error messages include:
Can't set up server admin
java.rmi.server.ExportException: Listen failed on port: 1109;
nested exception is:
java.net.SocketException: Descriptor not a socket: listen
failed
HttpSessionBindingListener
HttpSessionContext
23.3.2 Classes
Cookie
HttpServlet
HttpSessionBindingEvent
HttpUtils
23.6 Bibliography
Probably the best place to start is
http://java.sun.com/products/servlet/index.html
Follow the links.
The aims of this chapter are to provide a coverage of the package java.util.
Chapter 24 JavaServer Pages 284
24 JavaServer Pages
JavaServer pages (JSP) are Sun's response to Microsoft's Active Server Pages. Both are de-
signed to create dynamic web pages. ASP is restricted to the Microsoft platform. ASP are
found on Microsoft Internet Information Server (IIS) and work under Windows NT Server.
The following url:–
http://mountain-ash.cnit.kcl.ac.uk/
will be the system we will be using for some of the following examples.
JSP is Sun's platform independent variant of ASP. JSP technology uses XML-like tags and
scriptlets written in the Java programming language to encapsulate the logic that generates
the content for the page. Additionally, the application logic can reside in server-based re-
sources (e.g. JavaBeans) that the page accesses with these tags and scriptlets. Any and all
formatting (HTML or XML) tags are passed directly back to the response page. By separat-
ing the page logic from its design and display and supporting a reusable component-based
design, JSP technology makes it fast and easy (if you believe that you'll believe anything!)
to build web-based applications.
24.1 Bibliography
24.1.1 JSP
Visit
http://java.sun.com/products/jsp/
Also have a look at:
http://www.serverpages.com/Java_Server_Pages/
24.1.2 HTML
Visit:–
http://members.aol.com/htmlguru/
or just try putting in html to AskJeeves.
24.1.3 XML
Visit:–
http://www.xml.org/
and
http://www.xml.org/xmlorg_resources/whitepapers.shtml
The aims of this chapter are to provide a coverage of the package java.util.
Chapter 25 Package java.util 286
25 Package java.util
This chapter looks at some of the the java.util package. It should be apparent by now that a
working knowledge of the class library is essential for a good understanding of any object
oriented language.
25.1.2.16 HashSet
This class implements the Set interface, backed by a hash table (actually a HashMap in-
stance).
25.1.2.17 Hashtable
This class implements a hashtable, which maps keys to values.
25.1.2.18 LinkedList
Linked list implementation of the List interface.
25.1.2.19 ListResourceBundle
ListResourceBundle is a abstract subclass of ResourceBundle that manages resources for a
locale in a convenient and easy to use list.
25.1.2.20 Locale
A Locale object represents a specific geographical, political, or cultural region.
25.1.2.21 Observable
This class represents an observable object, or "data" in the model-view paradigm.
25.1.2.22 Properties
The Properties class represents a persistent set of properties.
25.1.2.23 PropertyPermission
This class is for property permissions.
25.1.2.24 PropertyResourceBundle
PropertyResourceBundle is a concrete subclass of ResourceBundle that manages resources
for a locale using a set of static strings from a property file.
25.1.2.25 Random
An instance of this class is used to generate a stream of pseudorandom numbers.
25.1.2.26 ResourceBundle
Resource bundles contain locale-specific objects.
25.1.2.27 SimpleTimeZone
SimpleTimeZone is a concrete subclass of TimeZone that represents a time zone for use
with a Gregorian calendar.
25.1.2.28 Stack
The Stack class represents a last-in-first-out (LIFO) stack of objects.
25.1.2.29 StringTokenizer
The string tokenizer class allows an application to break a string into tokens.
25.1.2.30 TimeZone
TimeZone represents a time zone offset, and also figures out daylight savings.
25.1.2.31 TreeMap
Red-Black tree based implementation of the SortedMap interface.
25.1.2.32 TreeSet
This class implements the Set interface, backed by a TreeMap instance.
25.1.2.33 Vector
The Vector class implements a growable array of objects.
25.1.2.34 WeakHashMap
A hashtable-based Map implementation with weak keys.
25.2 Bibliography
The aims of this chapter are to provide a coverage of some of the the package java.awt.dnd.
Chapter 26 Package java.awt.dnd 292
26 Package java.awt.dnd
This chapter looks at some of the the java.awt.dnd package.
26.2 Bibliography
Aims
The aims of this chapter are to look in more depth at arithmetic and in particular
what support Java has for the IEEE 754 standard. There is a coverage of:
Hardware support for arithmetic.
Integer formats.
Floating point formats: single and double.
Special values: denormal, infinity and not a number - NAN.
Exceptions and flags: divide by zero, inexact, invalid, overflow, underflow.
Chapter 27 IEEE Arithmetic 296
27 IEEE Arithmetic
This chapter is based on material from:
Chivers I.D., Sleightholme J., Introducing Fortran 95, Springer Verlag.
The literature contains details of the IEEE 754 standard and the bibliography contains de-
tails of a number of printed and on-line sources.
27.1 History
When we use programming languages to do arithmetic two major concerns are the ability to
develop reliable and portable numerical software. Arithmetic is done in hardware and there
are number of things to consider:
The range of hardware available both now and in the past.
The evolution of hardware.
and there has been a very considerable change in arithmetic units since the first computers.
The following is a list of hardware and computing systems that the authors have some used
or have heard of. It is not exhaustive or definitive. It reflects the authors age and experi-
ence.
CDC
Cray
IBM
ICL
Fujitsu
DEC
Compaq
Gateway
Sun
Silicon Graphics
Hewlett Packard
Data General
Honeywell
Elliot
Mostek
National Semiconductors
Intel
Zilog
Motorola
Signetics
Amdahl
Texas Instruments
Cyrix
Some of the operating systems include:
NOS
NOS/BE
Kronos
Unix
VMS
Dos
Windows
MVS
VM
CP/M
and again the list is not exhaustive or definitive. The intention is to provide with some idea
of wide range of hardware, computer manufacturers and operating systems that have existed
in the last 50 years.
To help with the anarchy that existed in this area Doctor Robert Stewart (acting on behalf
of the IEEE) convened a meeting which led to the birth of IEEE 754.
The first draft was prepared by Willam Kahan, Jerome Coonen and Harold Stone, called the
KCS draft and eventually adopted as IEEE 754. A fascinating account of the development
of this standard can be found in An Interview with the Old Man of Floating Point, and the
bibliography provides a web address of this interview. Kahan went on to get the ACM Tu-
ring Award in 1989 for his work in this area
This has become a de facto standard amongst arithmetic units in modern hardware. Note
that it is not possibe to precisely describe the answers a program will give and the authors
of the standard knew this. This goal is virtually impossible to achieve when one considers
floating point arithmetic. Reasons for this include:
The conversions of numbers between decimal and binary formats.
The use of elementary library functions.
Results of calculations may be in hardware inaccessible to the programmer.
Intermediate results in subexpressions or arguments to procedures.
The bibliography contains details of a paper that addresses this issue in much greater depth
– Differences Among IEEE 754 Implementions.
Fortran is one of a small number of languages to provide access to IEEE arithmetic, and it
achives this via TR1880 which will become an integral part of Fortran 2000. The C stan-
dard (C9X) addresses this issue and Java offers limited IEEE arithmetic support. More in-
formation can be found in the references at the end of the chapter.
Subtract.
Multiply.
Divide.
Square root.
Remainder.
Round numbers in floating point format to integer values.
Convert between different floating point formats.
Convert between floating point and integer format.
Compare
Base conversion - i.e. when converting between decimal and binary floating
point formats and vice versa.
Exception handling for:
Divide by zero.
Overflow.
Underflow.
Invalid operation.
Inexact.
Rounding directions.
Rounding precisions.
and we will look briefly at each of these requirements.
27.2.1 Single precision floating point format.
This is a 32 bit quantity made up of a sign bit, 8 bit baised exponent and 23 bit mantissa.
The standard also specifies that certain of the bit patterns are set aside and do not represent
normal numbers. This means that valid numbers are in the range 3.40282347E+38 to
1.17549435E-38 and the precision is between 6 and 9 digits depending on the numbers.
The special bit patterns provide the following:
+0
-0
subnormal numbers in the range 1.17549421E-38 to 1.40129846-45
+ infinity
- infinity
quiet NaN (Not a Number)
signalling NaN
One of the first systems that the authors worked with that had special bits patterns set aside
were the CDC 6000 range of computers that had negative indefinite and infinity. The ideas
are not new therefore, as this was in the late 1970s.
The support of positive and negative zero means that certain problems can be handled cor-
rectly including:
The evaluation of the log function which has a discontinuity at zero.
The equation 1
z = 1
z
can be solved when z = -1.
See also the Kahan paper Branch Cuts for Complex Elementary Functions, or Much Ado
About Nothing's Sign Bit for more details.
Subnormals, which permit gradual underflow, fill the gap between 0 and the smallest nor-
mal number.
Simply stated underflow occurs when the result of an arithmetic operation is so small that it
is subject to a larger than normal rounding error when stored. The existence of subnormals
means that greater precision is available with these small numbers than normal numbers.
The key features of gradual underflow are:
When underflow does occur there should never be a loss of accuracy any greater
than from ordinary roundoff.
The operations of addition, subtraction comparision and remainder are always
exact.
Algorithms written to take advanage of subnormal numbers have smaller error
bounds than other systems.
If x and y are within a factor of 2 then x-y is error free, which is used in a num-
ber of algorithms that increase the precision at critical regions.
The combination of postive and negative zero and subnormal numbers means that when x
and y are small and x-y has been flushed to zero the evaluation of:
1
( x − y)
27.3 Resumé
The above has provided a quick tour on IEEE 754.
27.4 ematics
This is the best place to start:
http://www.cs.berkeley.edu/~darcy/Borneo/
Abstract
The design of Java relies heavily on experiences with programming languages past. Major
Java features, including garbage collection, object-oriented programming, and strong static
type checking, have all proved their worth over many years. However, Java breaks with tra-
dition in its floating point support: instead of accepting whatever floating point format a
machine might provide, Java mandates use of the nearly ubiquitous IEEE Standard for Bi-
nary Floating Point Arithmetic (IEEE 754-1985). Unfortunately, Java's specification creates
several problems for numerical computation. Only a proper subset of IEEE 754's required
features are supported by Java; useful IEEE 754 features are either explicitly forbidden or
omitted from the Java specification. Java does not allow use of the IEEE 754 recommended
double extended format on the x86. Using the double extended format often protects simple
numerical formulas from floating point anomalies. Strict adherence to Java's floating point
semantics leads to significant performance penalties on popular architectures, including both
the x86 and PowerPC.
To address these problems, the Borneo language changes and extends Java so that all IEEE
754 features can be expressed and so that new numeric types can be easily created. Borneo
allows either better hardware use than Java or (nearly) exact reproducibility while in all
cases being predictable.
Summary
Unlike other languages designed to support IEEE 754 features (such as Modula-3, C9X, and
RealJava), Borneo does not just add library functions to set and query the floating point
state. Borneo has scoped language declarations to control the rounding mode, sticky flags,
and trapping status. Lexical scoping permits more optimizations and makes reasoning about
the program easier. One major change to Java not directly related to floating point is Bor-
neo's addition of operator overloading. Besides the ability to overload existing operators, as
in C++, Borneo also lets novel, user-defined, operators be defined and overloaded. Except
for some new keywords, Borneo is upwards compatible with Java. Given a Java class P
compiled to bytecode, another Java class cannot determine whether P was compiled under
Borneo semantics or Java semantics. (Borneo semantics disallow some floating point
optimizations permitted in Java).
Also have a look at
http://math.nist.gov/javanumerics/reports/jgfnwg-01.html
27.5 Bibliography
Hauser J.R., Handling Floating Point Exceptions in Numeric Programs, ACM Transaction
on Programming Languages and Systems, Vol. 18, No. 2, March 1996, Pages 139-174.
The paper looks at a number of techniques for handling floating point exceptions in nu-
meric code. One of the conclusions is for better structured support for floating point excep-
tion handling in new programming languages, or of course later standards of existing lan-
guages.
IEEE, IEEE Standard for Binary Floating-Point Arithmetic, ANSI/IEEE Std 754-1985, Insti-
tute of Electrical and Electronic Engineers Inc.
The formal definition of IEEE 754.
http://www.math.psu.edu/dna/disasters/ariadne.html
The Explosion of the Ariane 5: A 64 bit floating point number relating to the horizontal ve-
locity of the rocket with respect to the platform was converted to a 16 bit signed integer.
The number was larger than 32,768, the largest integer storeable in a 16 bit signed integer,
and thus the conversion failed.
27.5.2 Hardware Sources
Osbourne A., Kane G., 4 and 8 Bit Microprocessor Handbook, Osbourne/McGraw Hill.
Good source of information on 4 and 8 bit microprocessors.
Osbourne A., Kane G., 16 Bit Microprocessor Handbook, Osbourne/McGraw Hill.
Ditto 16 bit microprocessors.
Intel, 386 DX Microprocessor Hardware Reference Manual, Intel
The first Intel offering with 32 bit addressing.
Intel, 80386 System Software Writer's Guide, Intel
Developer's Guide to the above.
http://www.intel.com/
Intel's home page.
http://developer.intel.com/design/pentiumiii/
Details of the Pentium III processor.
http://www.cyrix.com/
Cyrix home page.
Bhandarkar D.P., Alpha Implementations and Architceure: Complete Reference and Guide,
Digital Press
Looks at some of the trade offs and design philosophy behind the alpha chip. The author
worked with VAX, MicroVAX and VAX vectors as well as the Prism. Also looks at the
GEM compiler technology that DEC/Compaq use.
http://www.digital.com/alphaserver/workstations/
Home page for the Compaq/DEC Alpha systems.
http://www.sgi.com/
Silicon Graphics home page.
http://www.sun.com/
Sun home page.
http://www.ibm.com/
IBM home page.
27.5.3 Operating Systems
Deitel H.M., An Introduction to Operating Systems, Addison Wesley.
The revised first edition includes case studies of Unix, VMS, CP/M, MVS and VM.
27.5.4 Java and IEEE 754
http://www.cs.berkeley.edu/~darcy/Borneo/
Borneo Language Homepage: Borneo is a dialect of the Java language designed to have
true support for the IEEE 754 floating point standard. Well worth reading.
27.5.5 C and IEEE 754
http://wwwold.dkuug.dk/JTC1/SC22/WG14/
The aims of this chapter are to provide a brief coverage of standardisation efforts, imple-
mentation differences and future developments.
Chapter 28 Language Standardisation 306
28 Language Standardisation
This chapter looks at standardisation efforts, standard conformance, implementation differ-
ences and future developments.
28.1 Sun
Sun are obviously one of the major driving forces behind Java. However other companies
quickly saw the potential that Java had and there was an attempt to get the language stand-
ardised. This has had mixed success. Currently Sun has pulled out of the standardisation ex-
ercise and there have been legal battles involving Microsoft being the most widely known.
The first place to start is at Sun's site. They make available the Java Language Specifica-
tion, and the second edition draft is now available for public review. The draft includes all
changes, clarifications and amendments made to the Java programming language since the
publication of the first edition of the language specification in 1996. Of particular note is
the full integration of the changes made in the 1.1 release of the Java platform into the
specification, especially nested classes and interfaces. The document is available in the fol-
lowing formats:
HTML (tar.Z, ~865K)
HTML (zip, ~600K)
PDF (~3706K)
PostScript (tar.Z, ~1765K)
PostScript (zip, ~1267K)
You've also seen what else they make available during the course by using the on-line doc-
umentation.