Many years ago, when Pascal seemed like a rather good idea, the structured programming paradigm shift was, over a period of years, adopted as the educational model by the majority of higher education computing departments. This was accomplished for very sound and well understood pedagogic reasons. It resulted in the widespread adoption of Pascal as a first language, though not as a base language, in the majority of institutions. In time Pascal was replaced with other structured languages such as Ada or Modula 2 although, even today, there is evidence [McCauley 97] that Pascal still retains its pre-eminence.
Several years ago, when Object Orientation seemed like a rather good idea, many departments adopted C++ as a first language. This was despite the compelling evidence and overwhelming opinion that C, and hence C++, was totally unsuitable for novice developers. The impression was left that these departments had followed this path in pursuance of C++'s commercial importance. This impression was confirmed when it emerged [Culwin 95] that these courses were overwhelmingly procedural with a very minor consideration of Object Orientation tagged on at the end.
This year, in the wake of the World Wide Web, Java might seem to be a rather good idea. The rate at which Java has generated interest, both in academia and in commerce, is unprecedented and the reasons underlying this interest have yet to be fully understood. It was against this background that the "Java in the Computing Curriculum" conference was held at South Bank University: London under the aegis of CTI Computing in February 1997.
If there is any common theme to the papers collected from this conference in this journal it is that the paradigm shift in educational practice towards Object Orientation, which should have been caused by the adoption of C++, will be forced by the adoption of Java. Hence, although there was no keynote paper I would commend Phil McLaughlin's paper 'Oh, by the way, Java is Object Oriented ...' to this position. However a fundamental understanding of Java, particularly of the ways in which it differs from C++, is still required for many people and Barry Cornelius's tutorial 'A Taste of Java' is an excellent introduction to the language.
Two previous software development environments, Apple's Hypercard and Microsoft's Visual Basic, have had an impact somewhat comparable to that of Java though, in retrospect, much more muted. Both of these products rapidly gained a reputation for allowing, or even encouraging, the hacking together of applications with a Graphical User Interface whose functionality was flawed and whose usability was underwhelming. There is no guarantee that developers using Java will not fall into a similar trap; but Tim Ball's paper 'Interfacing with the AWT', subtitled 'Software Engineering and the Abstract Window Toolkit' provides a rigorous approach to the engineering of GUIs which should be required reading for all Java developers.
Experience gained from actually using Java in the classroom was, at the time of the conference, very thin on the ground. The paper by Roger Garside, 'Teaching Java at Lancaster' presents the experience of using Java as a first language in the 1996/7 session. The paper from Alan Battersby, 'Initial experience of using Java in a Distributed Computing Module', probably portends a large number of papers which describe Java's advantages in various area's of curriculum. Finally the paper by Chris Wallace, Peter Martin and Bob Lang, 'Not whether Java but how Java', returns to the theme of Java as a first language and advocates a careful introduction of procedural concepts before considering object orientation. The final paper in this Journal, by Fintan Culwin, presents the results of an opinion sampling workshop on Java held at the 4th Dublin conference which resulted in the Java conference being called.
We live in interesting times and in the computing industry in very interesting times. For good reasons or bad the C style of syntax has become the lingua franca of the computing industry and, as with mediaeval academics and Latin, a working knowledge of C syntax is essential to participate in the software development industry. Latin existed, and exists, in many forms and dialects ranging from pig Latin, through ecclesiastical Latin through to classical Latin. The academic advantages of learning Latin were, and are, related only to classical Latin because of the purity of its structure and the influence which it had upon the English language.
I would contend that, if for no other reason, Java, by removing some of the syntactic absurdities of C++ should replace C++ as the dominant language of undergraduate software development education. The side effects of this transition will be to enable the paradigm shift from structured to object oriented programming, which is already long overdue. A further consequence of this, as Alan Battersby's paper presages, will be to de-obsfucate many arcane areas of instruction. The educational use of Java is still in its infancy and many of the pitfalls have yet to be discovered, accordingly we hope to reconvene the Java conference early in 1998 when, hopefully, many more educators will be able to report upon practical experience.
The Java programming language offers a number of features that make it attractive as a teaching vehicle:
Many of the programs that are to be found in current Java books are based on the production of applets for spicing up web pages. As such they contain compromises and are not necessarily good examples to follow for the teaching of software engineering.
In this article I wish to outline how a relatively simple program, implemented in Java, can be used to illustrate a number of software engineering principles. Within the confines of a few pages it is not possible to cover much detail. A fuller version of this document is available on the Internet. (see references) In particular that document shows how the program to be discussed can be developed in a series of steps.
The application to be developed is a simple StopClock (or one-second timer) that shows minutes and seconds and may be started, stopped and reset. A screen shot of the clock in action appears below:
Three buttons control the clock and the permissible operation(s) are indicated by "greying out" the legend on the buttons that are not available. The clock runs in the windowed environment that supports the Java system e.g. Win95 or Motif.
2. An Object Model
Good object-oriented design would suggest that there should be a separation of responsibilities between appropriate objects. The Model-View-Controller paradigm described by Krasner and Pope is an appropriate framework here.
An object model for the application might be shown as:
A Clock object is controlled by a Control Panel object which, in turn, contains three button objects. The Clock object has access to a Display Panel object which contains some kind of fields for displaying the minutes and seconds. In this implementation the display is essentially passive - the Clock object causes the updates to occur.
The user interface will implement a state model and provide visible feedback to the user through appropriate shading of the buttons:
3. The Clock object
The basic Clock object is responsible for counting one-second (or shorter) pulses and causing them to be displayed. A number of strategies are possible for implementing this object and the one taken here is actually to create two coupled objects: a main Clock object and related ClockMechanism. The ClockMechanism is responsible for calling a single function in the Clock object at one-second intervals.
So in ClockMechanism we have:
private Timed myOwner;
public void run()
{
where the object myOwner is the main Clock object and in Clock we have:
private int sec = 0;
private int min = 0;
public void tick()
{
where the displayTime() message invokes an appropriate method in the screen display object.
The ClockMechanism runs in its own thread of control. The sleep(1000) method causes the thread to suspend its execution for at least 1000mS. (This clock will run slow!)
4. Linking the objects
We now have two objects - a Clock and a ClockMechanism that each need to know about the other in order to request services:
We can achieve this by making sure that each object has a suitable reference to the other. However it might not be appropriate for the ClockMechanism, for example, to have access to all of the public interface of a Clock object. In Java there is a language construct called interface that allows us to limit the visibility of methods in an object.
The ClockMechanism object could have been written as:
private Clock myOwner;
public void run()
{
but the decision was taken to use an interface such that only the tick() method was available. The interface is called Timed and it is defined as:
public interface Timed
{
An interface is used to define the methods that can be called - in a sense it defines a new type - certainly as far as the Java compiler is concerned. The Clock class implements this interface:
public class Clock implements Timed
This is a good way of implementing the equivalent of "call- back" functions in Java. The Clock object creates a ClockMechanism object and passes it a reference to itself:
public class Clock implements Timed
{
The ClockMechanism is itself derived from the built- in Thread class and in its constructor it stores the reference to the Clock object it is to control:
public class ClockMechanism extends Thread
{
The entry point for the Java application is a function in the Clock class:
public static void main(String[] args)
This function create a new instance of Clock which, in turn, creates its own ClockMechanism. Each of these objects will stay in existence until one of them is destroyed because of the mutual references - the garbage collector will leave them alone. The call to clock.start() in the Clock() constructor will cause the ClockMechansim to execute its run() method. (Both run() and start() are methods defined in Thread and we override run() to provide the required functionality of our thread.)
5. Software engineering issues
6. The Abstract Windowing Toolkit (AWT)
The core of the model part of the MVC is now finished but it needs a public (inter)face - an on-screen presence.
The Java AWT provides classes that allow us both to create screen output and also to capture events.
To produce a visible window, decorated by the system's own window manager, it is necessary to create a Frame object - i.e. an object derived from the class java.awt.Frame.
For the clock program there are, at least, three strategies open:
Both of the options 1 and 2 suffer from the same kind of problem. A Frame object contains over 75 methods in its public interface and all the code in the Clock object has unrestricted access to them - probably not a good idea. Even worse - a Clock derived from a Frame has these functions in its public interface too! It is attractive in that it is easier to handle events as they can all be captured by the Frame object. As indicated above it would make sense for the user-interface code (view and controller) to be separate from the model code. Many of the example Java programs to be found in current textbooks take one of these two routes - generally deriving an application from Frame. For an example Clock program see pp 535-539 of the excellent SunSoft publication "Core Java" by Cornell and Horstmann.
Taking the third approach we will follow a similar route to that taken when creating the ClockMechanism. The user interface class will be derived from Frame but implement a much more limited interface called TimeDisplay, which is all that will be seen by the Clock. The Clock object should only be responsible for pulse counting and should be able to call upon a suitable display object to carry out the work necessary to present the result on screen. The interface object also needs to process user events and call appropriate methods in the Clock object to start, stop and reset the time.
7. The user interface (GUI) object
This object will act as a container for both the view and controller objects. It must itself be derived from the awt.Frame object so that it can appear on screen. It will implement the TimeDisplay interface so that the Clock object can talk to it:
public class GUI extends Frame
public GUI( Controllable it )
{
The GUI object contains two sub-objects, a DisplayPanel and a ControlPanel and also a reference to the Clock object it is to control. This reference is via a Java interface:
public interface Controllable
{
This interface makes accessible only those methods that are appropriate to a controller. In particular, a controller cannot see, and therefore cannot use, the tick() method. In the same way, the ClockMechanism object cannot see or access the methods start(), stop() etc.
The two sub-objects are both derived from awt.Panel. The displayPanel constitutes the upper section of the screen display holding the time output. The ControlPanel holds the "Start","Stop" and "Reset" buttons.
Looking briefly at the code of the constructor for a GUI object:
setTitle( "GUIClock" ) - this sets the text that will appear in the border of the visible window.
add( "North", displayPanel ) - and the similar line underneath it are responsible for positioning the sub- objects within the window - the actual position is the responsibility of a LayoutManager see below.
pack() and show() cause the Frame to first resize itself so that it accommodates its sub-objects correctly and then to become visible on screen.
8. LayoutManager classes
The Java awt expects that programmers describe how a visible window is to look in terms of "positioning rules" rather than requiring that each object be placed at a prescribed pixel position. This relieves the programmer of the need to interrogate the system to find out the screen resolution etc and it is necessary to make platform independence simpler.
For a Frame object, the default layout is called a BorderLayout. It permits 5 sub-objects to be positioned thus:
The "North" and "South" areas will resize to the maximum width of the Frame but will be no deeper than necessary to hold their components, the "East" and "West" areas expand vertically and the "Center" will expand in both directions.
The Panel objects use a simpler FlowLayout where sub-objects are inserted and centred on a line by line basis. The constructor for the DisplayPanel illustrates this:
public class DisplayPanel extends Panel
public DisplayPanel()
{
Here the four sub-objects, two Label and two TextField objects are added and will appear in the order they were inserted. Resizing the panel (on-screen) so that it is narrow but taller will cause the objects to appear in more than one line. The layout of the ControlPanel is similar.
9. Implementing the GUI functionality
The functionality of the display object is achieved through the single method:
public void displayTime( int min, int sec )
and the GUI object simply passes its values to this method.
The controller object is rather more complicated and requires the processing of events generated by the user.
10. AWT Events
Events are generated either by a user's action or from the operating system. Pressing a key, moving the mouse, clicking a mouse button, uncovering a window can all cause events to be generated. The system always considers a particular awt component to be the legitimate target of the event and it is to this object that the event is sent first. In Java, all events are instances of the class Event and there are a number of public fields of an Event object including:
A method receiving an event can interrogate these fields and decide how to process the event.
10. How do events get to objects?
The simple answer is that a handleEvent( Event e ) method is called with the Event passed as a parameter. However, if the event is not handled in the handleEvent method then a "convenience method" is called for specific classes of event - action(), mouseEnter(), keyDown() .. and so on. Appropriate parameters are passed to these methods. Most component objects are located within AWT containers and, if the component does not handle the event, the container will eventually receive the event - first via handleEvent() then through an appropriate convenience method. Frames and panels are such containers objects.
In the example under consideration, the GUI object is responsible for interacting with the Clock. It is necessary that the processing of the WINDOW_DESTROY event takes place here as it is the object that will first receive the event - when the user closes the window. The following method must therefore be a member of the GUI class:
public boolean handleEvent( Event event )
{
IT IS ESSENTIAL that this method calls the over-ridden method of the parent Frame object otherwise the convenience methods will not be called. The action() method is used to process the responses from buttons as far as interacting with the Clock object is concerned:
public boolean action( Event event,
The argument parameter is, in the case of a Button object, a string containing the button label. The required functionality is provided within the Clock object itself by the following methods:
public void start()
{
public void stop()
{
public void reset()
{
public void kill()
{
There are now two threads of control running - the one running the ClockMechanism and one running the awt components. It is possible that the user could reset the clock just as a time update was taking place. Java provides mechanisms for preventing this type of problem which are outside the scope of this article. However it is possible to provide a guaranteed solution by not allowing reset to occur if the clock is running. The state model presented earlier shows how this could be achieved. It is implemented in the ControlPanel object.
11. Implementing the state model
The ControlPanel object can capture the button events and respond to them before passing them on to the GUI.
The ControlPanel object uses methods available on a button to enable or disable it - which show as black/grey labels. The full code for the ControlPanel is:
public class ControlPanel extends Panel
{
Note: how the action() method returns false even when it has handled a button press. Returning true would prevent the event from reaching the outer Frame object.
12. Software Engineering Issues
By using a number of classes it has been possible to distribute the intelligence around the system - a guideline for object-oriented design (see p64 of Wirfs-Brock ):
13. Conclusion
The Java language is an attractive proposition for software engineering education. It offers a number of important facilities including object-orientation, multi- threaded programming, events, socket-based communication and so on. It is possible to use it to illustrate many of the principles that we, as academics, would like our students to experience. It is important, however, that we realise that many of the "advanced" features may impinge upon otherwise simple programs. (e.g. exceptions must be handled, several threads are always present) The language is also changing. Under the new release (the JDK1.1), the event handling described in this article would be implemented differently although the main architecture of the application would remain essentially unchanged.
References
The full text of the presentation given at the "Java in the Computing Curriculum" meeting together with source code for a set of example programs that further develop the theme of this article sareto be found at the following URL:
Krasner G.E. and Pope S.T. (1988),
"A cookbook for
using the Model-View-Controller user interface paradigm in
Smalltalk-80",
Journal of Object-Oriented Progrmming,
1(3).
Wirfs-Brock R., Wilkerson B. and Wiener L.,
"Designing Object-Oriented Software",
Prentice-Hall
(1990) ISBN 0-13-629825-7
Alan Battersby
The Distributed Computing module is one of the second
level modules offered by the Computing Department in its
undergraduate programme. The module aims are twofold: to
introduce computer networks and to provide some experience
of programming simple distributed applications. Assessment
is by examination and course-work with each component
carrying an equal weight. The workload consists of roughly
eighty hours of work delivered over a twelve week period.
Contact time is a one hour lecture reinforced by a one hour
laboratory session; the remaining time is private study.
Material pertinent to the course (with relevant exercises)
is available on-line at an internal departmental web site.
The course is split into two halves the first half
emphasises the structure of computer networks and has no
programming content; the second part is to introduce
client/server systems, and to demonstrate their
implementation. It is this second half of the course that
is the subject of the rest of this paper.
2. Course Content
A previous version of the module had used C/C++ as the
implementation language. The intention was to build upon the
skills acquired in the first level C++ programming modules.
The characteristics of Client/Server systems were described
starting with simple one-shot clients and ending with
concurrent servers. The laboratory work was presented at
two levels of abstraction. The lowest level required that
the student acquire : a knowledge of UNIX (SunOs 4.1.3)
sockets[1] and their strengths and weaknesses, plus an
appreciation of forking processes and/or using lightweight
threads and semaphores. The higher level of abstraction
involved familiarity with remote procedure calls (rpc) [2]
and the use of rpcgen.
Examination results indicated that students did obtain a
useful overview of these topics in the time available,
because the set questions were generally answered
satisfactorily. The laboratory exercises however proved to
be far more difficult. Many students did not get beyond the
initial simple problems. Relative inexperience, plus the
general pressures on time, ensured that only the brightest
and most dedicated students progressed to the more
interesting problems. Many found their C++ experience did
little to equip them for the general messiness of using
processes, threads and semaphores in a UNIX system. Often
they completed the module with a sense of dissatisfaction at
being unable to progress to the more interesting problems.
It became obvious that the laboratory exercises were not
achieving their aim of reinforcing the material presented
in the lectures. It had been anticipated that several of
the low level programming requirements would prove difficult
for weaker students. However, the feedback received at the
end of the course led to the reconsideration of the
laboratory work in its entirety.
3. The case for using Java
Examination of socket based examples provided in several
texts [3][4][5], led to the consideration of Java as a
possible substitute for C++. It became apparent that Java
was a language offering several advantages over C/C++ for
programming network based applications of the type covered
by the laboratory exercises.
As a platform independent language Java sweeps all operating
system idiosyncrasies out of sight, and provides a cleanly
defined, often simple, interface to all major language
features. Happily, all features required for the laboratory
exercises: sockets, threads, and mutually exclusive access
to shared resources, were included as part of the Java
language.
Socket support comprises two classes Socket and
ServerSocket. These classes elegantly capture the
fundamental asymmetry between socket use in client and
server programs, and help enforce this difference in usage.
Several low level operations (for example, the establishment
of a connection) are performed internally and become
transparent to the programmer, resulting in a simplification
of the program code. A selection of socket constructors
provides added functionality enabling the specification of
the network host as either an Internet address or a string
that is transparently converted to an Internet addresses (by
performing a DNS lookup). Sockets come equipped with easily
accessible streams making the task of writing or reading
data to or from processes straightforward. The result of
this thoughtfulness in the implementation of the socket
class is to reduce the code required to create and support a
connection between client and server. The resulting
programs are clean and simple. Figure 1 presents a fragment
of code to illustrate the principle.
Concurrent processing using threads is elegantly supported.
Classes are executable as threads, either by creating them
as an extension of the base Thread class, or by creating
them as an implementation of the Runnable
interface. An interface presents a list of methods that
must be implemented by a class. Those classes implementing
the Runnable interface must contain a single method
called run() which executes when a thread containing
a reference to the Runnable class starts. Using
threads, one can write a concurrent server in only a few
lines of code using a single ancillary class to handle
communication with the client process. Whenever the server
accepts a client connection it creates a thread to handle
all further communication with that client. The code to
provide this functionality is quite simple (see figure 2).
Encapsulating shared data in a class and providing
synchronized methods to access the data enforces
exclusive access to shared resources. The programmer simply
needs to add the keyword synchronized in the method
definition. An example definition heading would be
public synchronized int getData(). Java handles
synchronisation using hidden internal monitors. If two
threads attempt to access a synchronised method
simultaneously, one will be blocked until the other
completes.
Making a decision to use Java instead of C/C++ as the
language of choice is really only swapping one set of
constraints for another. One has to weigh the simplicity of
the Java code against the problems inherent in learning a
new language in the brief time allocated for practical
exercises. Whilst Java is syntactically quite similar to C++
it nevertheless differs in significant areas. I/O is
often a problem in any language. Unfortunately, stream based
I/O in Java is significantly different from that in C++.
Therefore, I/O was one area where one could expect there to
be problems and misunderstandings. Another potential problem
might occur because Java is a diverse language with many
pre-defined classes. Java is not a "lean" language. It comes
with wide ranging support in many areas and with many built
in classes. Some might find the sheer diversity initially
overwhelming.
On the positive side, four other modules offered on the
course had already introduced the concept of object-oriented
programming. Students were familiar with classes and
inheritance albeit from a C++ viewpoint.
4. The new course
It was decided to trial the use of Java in this module. The
expectations were that the simplicity of the Java code would
allow most students to be more productive than in C or C++,
and that the laboratory exercises would again become a
reinforcement of the lecture material and less of a
encumbrance. The significance of the burden placed on the
student in learning Java was unknown. The expectation was
that the simplification in code would make the exercises
easier, thus promoting a sense of achievement which would
carry students through the learning curve resulting in a
sense of satisfaction instead of one of underachievement.
Focusing attention to a restricted subset of Java ought to
flatten the learning curve. Therefore, the topics covered
would be confined to: classes, sockets, threads, exception
handling, synchronised shared objects, and stand-alone
programs, with emphasis placed on those aspects
syntactically quite similar to C++. Topics such as Packages,
interfaces, threadgroups and the Abstract Windows
Interface(AWT) would not be covered.
The introduction of a higher level of abstraction, as
represented by RPC in the previous course, was problematic.
The equivalent of RPC, remote method invocation or RMI, was
then only at a development stage and so it was not really
practical to cover this topic. However, it was also
impracticable to cover RPC because this would require a
switch back to C after only two to three weeks of Java
programming. Regretfully, the RPC material was replaced by
new material covering the world wide web and three-tier
architectures. The new course syllabus was:
The laboratory exercises associated with the module
were:
5. Evaluation of the course
Java was used as the implementation language for the
Distributed Systems module which ran in the first semester
of the 1996-1997 academic year and was taken by over two
hundred students. One immediately noticeable outcome was
that the course really did run more smoothly. The number of
requests for help were significantly fewer than the previous
year. The switch from C++ classes to Java classes, with its
attendant change in syntax, seemed to pass almost unnoticed,
even threads did not cause any undue concern. All managed
the initial exercises and were able to write and test a
simple concurrent server. The initial practical exercises
were automatically assessed; however the student stock-
server solution had to be demonstrated. For example, the
ability to write a network client was assessed by requiring
the student to write their client so it would implement a
randomly generated protocol assigned to them. They had to
connect their client to a testing server on a given port. If
their client successfully implemented the protocol, a unique
random key value was returned. To gain the marks associated
with this task, the student had then to fill in a form on a
web-page to submit their key to an on-line database
administrator. The simple servers were tested in a similar
manner.
The problems encountered were mainly concerned with I/O and
the use of parsers to read numbers from a stream. Several
explanatory example programs had to be given as examples and
the point covered during lecture time. Some students had to
be persuaded that a different language did not necessarily
mean that a radically different syntax was being used (for
example that a for loop had the same syntax in Java as in
C++).
One unexpected bonus was the interest generated simply
because Java was the language used. The fact that Applets
and the AWT were not being covered did little to affect
this enthusiasm. Attendance at laboratory sessions was
consistently high with many students asking how they could
put Java on their own machines at home.
Feedback at the conclusion of the module was very positive
and very supportive of the use of Java on this course. This
feedback was substantiated in the examination at the end of
the module with over 40% of students attempting both and
over 70% at least one of the questions associated with this
part of the course. Some comments are listed below:
A colleague in an associated college, who was also
presenting this module, did prepare the ground a little
better by replacing the last couple of labs in the first
half of the course with an introduction to Java. This
effectively replaced the first Java exercise and allowed a
longer acclimatisation time before the client/server
exercises. He reported very few problems in changing to
Java. This model will be followed in the presentation of the
module.
6. Conclusions
Java proved to be an ideal language for use in this module.
Its features support the implementation of client/server
systems in a clean, logical and simple way. The simplicity
of its code meant that most students quickly produced
working programs which gave them the confidence to attempt
the later examples. The course ran more smoothly and with
fewer problems than in previous years where C++ was used.
References
J. Bloomer,
M. Daconta,
G. Vanderburg,
Barry Cornelius
1. Introduction
1.1 What is Java?
Java is an object-oriented programming language developed by
Sun Microsystems. It has: strong-typing, garbage collection,
multithreading, exception handling and no architecture-
dependent constructs. It does not have: structs, unions,
pointer arithmetic, operator-overloading and multiple
inheritance. It is accompanied by many packages
(collections of classes) including one for building
GUIs.
1.2 How is it executed?
Unlike most programming languages, Java source code is not
compiled into native code. Instead, a Java compiler
translates Java source code into an architecturally-neutral
intermediate form known as bytecode. Instructions in
this bytecode are interpreted by a Java interpreter.
Sun's Java Developers Kit (JDK) includes a compiler
and interpreter. They provide (free of charge) versions for
Solaris 2.x (both sparc and x86), for Windows 95, for
Windows NT and for MacOS System 7 (and above). Currently,
the version of the JDK that most people use is JDK 1.0.2.
However, the final release of JDK 1.1 is now available. The
next release (JDK 1.1.1) will be a bug-fix release. Both
JDK 1.0.2 and JDK 1.1 can be downloaded from:
1.3 What are Java applications?
A Java application is a conventional program. It must have a
method called main.
Suppose that the file HWTion.java contains the Java
application:
public class HWTion {
It can be compiled by using the Unix/MS-DOS command:
This command produces a file of bytecodes in the file
HWTion.class. This file can then be interpreted (i.e.,
executed) by using the command:
1.4 What are Java applets?
A Java applet is Java source code whose bytecodes will be
executed as part of viewing a WWW page. The applet's author
compiles the Java source code into bytecodes. These
bytecodes will be downloaded from their author's site by a
WWW browser when the WWW page is visited. So, the browser
needs to have a Java interpreter to interpret the bytecodes.
This is true for WWW browsers that are Java-aware, e.g.,
Sun's HotJava, Microsoft's Internet Explorer
or Netscape's Navigator.
Until recently, Netscape Navigator for Windows 3.1 did not
support Java. However, a beta version is now available. For
more details, see:
There is also a version of Internet Explorer (3.0a) that
supports Java on Windows 3.1:
Sun's JDK includes an appletviewer that can be used
if you do not have a Java-aware WWW browser.
Suppose the file HWLet.java contains the Java applet:
import java.awt.Graphics;
It can be compiled by using the command:
This command produces the file HWLet.class.
When a browser reads the WWW page given below, it finds that
it has to retrieve the file HWLet.class. When the bytecodes
in this file arrive, it can interpret them.
HTML>
* Please note that a number of less than symbols are
missing from the above code so that the code can be viewed by you.
You can access a WWW page containing the above HTML
instructions by using the URL:
1.5 Some real examples of applications
One of the first large applications was the WWW browser
produced by Sun called HotJava. So, all of the code
of HotJava is written in the Java programming language. For
more details, see:
Sun has produced an IDE (Integrated Development Environment)
for Java written in Java called Java Workshop:
Borland's AppExpert and Debugger for Java are
written in Java:
Two groups have produced WWW servers written in Java. Sun
has produced Java Web Server (formerly known as
Jeeves) at:
and the World Wide Web Consortium has produced Jigsaw
at:
1.6 Some real examples of applets
A pre-beta release of Corel Office for Java, a
suite of office productivity applications (including
Quattro Pro and WordPerfect) written entirely
in Java, is obtainable from:
Applix's product Anyware Office is a complete suite
of applications (written in Java) including a WYSIWYG word
processor, a 3-D GUI spreadsheet, business graphics and an
e-mail client. The same applications can be executed on
"Webtops, NCs, Windows 95, NT and UNIX desktops and
servers". It costs $295 per concurrent user. See:
1.7 A digression: what is JavaScript?
Here is a WWW page that includes some source code written in
JavaScript:
HTML> HEAD> TITLE> Square demo /TITLE> /HEAD>
* Please note that a number of less than symbols are
missing from the above code so that the code can be viewed by you.
JavaScript is another programming language. You put
JavaScript code in HTML documents with a <SCRIPT> tag. The
JavaScript code is not compiled: instead, it is interpreted
by a JavaScript-aware WWW browser. Netscape Navigator
(including the Windows 3.x version) understands
JavaScript.
You can access a WWW page containing the above HTML
instructions by using the URL:
JavaScript has most of Java's expression syntax and basic
control flow constructs, but it does not have Java's strong
type checking and static typing. You cannot write your own
classes. So, JavaScript is not as powerful as Java. It is
confusing for Java to be included as part of the name
JavaScript.
2. The Java language
2.1 What's been taken out from C/C++?
2.2 What's left?
Java's primitive data types have specified ranges:
Java also has arrays, which can be multi-dimensional.
Java contains C's if, else, for, while, do while and switch
statements. However, all conditions must return a boolean.
So, some of the more obscure conditions of C are prohibited.
2.3 What's new? (a) Garbage collection
People sometimes write Pascal/C/C++ code that inadvertently
dispose/free/delete objects which are still in use:
var p, q:^integer;
In Pascal/C/C++, programs often cause memory leaks by not
using dispose/free/delete on objects no longer in use.
In Java, you do not delete objects: instead, Java has
garbage collection. The garbage collector detects
objects no longer in use, and reuses their space. You also
do not have to provide destructors for classes.
2.4 What's new? (b) Multithreading
In Java, you can easily start more than one thread of
execution.
If a variable is accessed by two (or more) methods which are
called from different threads, you can ensure that the
variable is accessed properly by using synchronized:
public class Store {
2.5 An example of a class
In Java, it is possible to use a class declaration to
define your own type. Suppose that it is necessary to
manipulate some dates in a program. Here is a rather
primitive class declaration:
public class Date {
2.6 A better version of the class Date
A private modifier can be used to hide the representation:
public class BetterDate {
If necessary, other methods can be provided to access the
hidden fields or to update them.
2.7 An example of inheritance
Inheritance can be used when a class is a more
specialized form of another class:
import java.util.Vector;
A Java application that uses the Stack class is at the
URL:
2.8 Exception handling: (a) throwing
If a method detects that some untoward event has occurred,
it can use a throw statement to signify that an
exception has occurred:
import java.util.Vector;
Department of Computing, Nottingham Trent University, Burton
Street, Nottingham NG1 4BU
E-mail : abat@doc.ntu.ac.uk
"UNIX Network Programming",
Prentice Hall
"Power Programming with RPC",
O'Reilly & Associates 1992
"Java for C/C++ programmers",
J. Wiley 1996
"Tricks of the Java Programming
Gurus",
Sams Publishing 1996
IT Service, University of Durham, DURHAM DH1 3LE
E-mail : Barry.Cornelius@durham.ac.uk
URL :
http://www.dur.ac.uk/~dcl0bjc/Java/
}
import java.applet.Applet;
public class HWLet extends Applet {
}
HEAD>
TITLE> HWLet example /TITLE>
/HEAD>
BODY>
Before the output from the applet.
APPLET CODE="HWLet.class" WIDTH=150 HEIGHT=25>
/APPLET>
After the output from the applet.
/BODY>
/HTML>
BODY>
P> Start. /P>
SCRIPT LANGUAGE="JavaScript">
! hide this script from some browsers
function mysquare(myarg) {
} ;
document.write("P>Value returned is: ",
// end of hide >
/SCRIPT>
P> Finish. /P>
/BODY> /HTML>
int *p, *q;
new(p);
p =
malloc(sizeof(int));
p^ := 27;
*p = 27;
q := p;
q = p;
dispose(p);
free(p);
writeln(q^);
printf("%d\n", *q);
}
}
public class UseDate {
}
}
public class UseBetterDate {
}
public class Stack extends Vector {
}
public class BetterStack extends Vector {
}
public class BetterStackException