Académique Documents
Professionnel Documents
Culture Documents
Tous droits
réservés.
Ce produit ou document est protégé par un copyright et distribué avec des licences qui en restreignent l’utilisation, la
copie, la distribution, et la décompilation. Aucune partie de ce produit ou de sa documentation associée ne peut être
reproduite sous aucune forme, par quelque moyen que ce soit, sans l’autorisation préalable et écrite de Sun et de ses
bailleurs de licence, s’il y en a.
Des parties de ce produit pourront être dérivées du système UNIX® licencié par Novell, Inc. et du système Berkeley 4.3
BSD licencié par l’Université de Californie. UNIX est une marque enregistrée aux Etats-Unis et dans d’autres pays et
licenciée exclusivement par X/Open Company Ltd. Le logiciel détenu par des tiers, et qui comprend la technologie
relative aux polices de caractères, est protégé par un copyright et licencié par des fournisseurs de Sun.
Sun, Sun Microsystems, le logo Sun, sont des marques déposées ou enregistrées de Sun Microsystems, Inc. aux Etats-Unis et
dans d’autres pays. Toutes les marques SPARC, utilisées sous licence, sont des marques déposées ou enregistrées de SPARC
International, Inc. aux Etats-Unis et dans d’autres pays. Les produits portant les marques SPARC sont basés sur une
architecture développée par Sun Microsystems, Inc.
Les interfaces d’utilisation graphique OPEN LOOK® et Sun™ ont été développées par Sun Microsystems, Inc. pour ses
utilisateurs et licenciés. Sun reconnaît les efforts de pionniers de Xerox pour la recherche et le développement du concept
des interfaces d’utilisation visuelle ou graphique pour l’industrie de l’informatique. Sun détient une licence non exclusive
de Xerox sur l’interface d’utilisation graphique Xerox, cette licence couvrant aussi les licenciés de Sun qui mettent en
place l’interface d’utilisation graphique OPEN LOOK et qui en outre se conforment aux licences écrites de Sun.
Le système X Window est un produit de X Consortium, Inc.
CETTE PUBLICATION EST FOURNIE “EN L’ETAT” SANS GARANTIE D’AUCUNE SORTE, NI EXPRESSE NI
IMPLICITE, Y COMPRIS, ET SANS QUE CETTE LISTE NE SOIT LIMITATIVE, DES GARANTIES CONCERNANT LA
VALEUR MARCHANDE, L’APTITUDE DES PRODUITS A RÉPONDRE A UNE UTILISATION PARTICULIERE, OU LE
FAIT QU’ILS NE SOIENT PAS CONTREFAISANTS DE PRODUITS DE TIERS.
Please
Recycle
D
to this:
public void actionPerformed(ActionEvent event) {
Follow the general steps below to convert a 1.0 component into a 1.1
listener.
import java.awt.event.*
For example:
newComponentObject.addActionListener(this);
1.0.x 1.1
Canvas
MOUSE_DRAG/mouseDrag Dialog mouseDragged(MouseEvent)
MOUSE_MOVE/mouseMove Frame MouseMotionListener mouseMoved(MouseEvent)
Panel
Window
KEY_PRESS/keyDown keyPressed(KeyEvent)
KEY_RELEASE/keyUp Component KeyListener keyReleased(KeyEvent)
KEY_ACTION/keyDown keyTyped(KeyEvent)*
KEY_ACTION_RELEASE/keyUp
a. No 1.0 equivalent
1.0.x 1.1
Checkbox
CheckboxMenuItem ItemListener itemStateChanged(ItemEvent)
Choice
WINDOW_DESTROY windowClosing(WindowEvent)
WINDOW_EXPOSE Dialog WindowListener windowOpened(WindowEvent)
WINDOW_ICONIFY Frame windowIconified(WindowEvent)
WINDOW_DEICONIFY windowDeiconified(WindowEvent)
windowClosed(WindowEvent)*a
windowActivated(WindowEvent)*
windowDeactivated(WindowEvent)*
componentMoved(ComponentEvent)
WINDOW_MOVED Dialog ComponentListener ComponentHidden(ComponentEvent)*
Frame componentResized(ComponentEvent)*
componentShown(ComponentEvent)*
SCROLL_LINE_UP
SCROLL_LINE_DOWN AdjustmentListener
SCROLL_PAGE_UP (Or use the new ScrollPane adjustmentValueChanged(AdjustmentEvent)
SCROLL_PAGE_DOWN Scrollbar class)
SCROLL_ABSOLUTE
SCROLL_BEGIN
SCROLL_END
The biggest part of converting most 1.0 AWT-using programs to the 1.1
API is converting the event-handling code. The process can be
straightforward, once you figure out which events a program handles
and which components generate the events. Searching for “Event” in a
source file lets you find the event-handling code.
Note – While you are looking at the code you should note whether
any classes exist solely for the purpose of handling events; you might
be able to eliminate such classes.
Table D-1 can be used in the conversion process to help map 1.0 events
and methods to their 1.1 counterparts.
● The first column lists each 1.0 event type, along with the name of
the method (if any) that is specific to the event.
● The second column lists the 1.0 components that can generate the
event type.
● The third column lists the listener interface that helps you handle
the 1.1 equivalents of the listed events.
Event Handling
When upgrading to the 1.1 release, the simplest way to convert event-
handling code is to leave it in the same class, and make it a listener for
that type of event.
References
D-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
C
1. Add a find method to the MyVector class that returns the location
of the element passed as an argument.
For example:
$ java MyVectorFind 3.14
3.14 is located at index 1
Number of vector elements is 4 and are:
5
3.14
Hi there!
abcd
$ java MyVectorFind c
args[0]=c, not found in vector
Number of vector elements is 4 and are:
5
3.14
Hi there!
abcd
For example:
$ java MyVectorDelete 3.14
Elements 3.14 successfully deleted from vector.
Number of vector elements is 3 and are:
5
Hi there!
abcd
Vector C-7
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
C
1 import java.util.*;
2
3 public class MyVector extends Vector {
4 public MyVector() {
5 super(1,1); // storage capacity & capacityIncrement
6 }
7
8 public void addInt(int i) {
9 addElement(new Integer(i)); // addElement requires Object arg
10 }
11
12 public void addFloat(float f) {
13 addElement(new Float(f));
14 }
15
16 public void addString(String s) {
17 addElement(s);
18 }
19
20 public void addCharArray(char a[]) {
21 addElement(a);
22 }
23
24 public void printVector() {
25 Object o;
26 int length = size(); // compare with capacity()
27 System.out.println("Number of vector elements is " + length
+ " and they are:");
Vector C-5
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
C
Methods (Continued)
● public final synchronized void removeElementAt(int
index) – Deletes the element at the specified index. It throws
ArrayIndexOutOfBoundsException if index is invalid.
Variables
The Vector class contains the following instance variables:
Methods
Below are some of the methods in the Vector class. Refer to the Java
API for a description of all methods in this class.
Vector C-3
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
C
The Vector class provides methods for working with dynamic arrays
of varied element types.
java.lang.Object
java.util.Vector
Synopsis
public class Vector extends Object implements Cloneable
Constructors
The constructors for the Vector class are:
Objectives
This appendix examines the Vector object in detail.
C-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
B
Summary
Accessing Strings
1 /*
2 * NWH.c
3 * A native method HelloWorld implementation in C
4 */
5 #include <stdio.h>
6 #include <StubPreamble.h>
7 #include <javaString.h>
8 #include “NativeHello4.h”
9
10 void NativeHello4_nativeHelloWorld4(struct HNativeHello4 *this,
11 struct Hjava_lang_String *message,
12 long count)
13 {
14 char *C_message;
15
16 C_message = makeCString(message);
17 for (; count > 0; count--)
18 printf(“%s\n”, C_message);
19 }
Accessing Strings
Accessing Strings
Here is an example of the HelloNativeWorld4() method that takes
two arguments: the message to print and the number of times to print
it.
1 class NativeHello4 {
2 // Declare your native method call
3 public native void nativeHelloWorld4(String message, int count);
4
5 // Load the library containing the native method implementation
6 static {
7 System.loadLibrary(“nativeTest”);
8 }
9 }
10 // The Java Class Using NativeHello4
11 class UseNative4 {
12
13 public static void main (String args[]) {
14
15 // Create a new object containing your native method
16 NativeHello4 nh4 = new NativeHello4();
17
18 // Call it!
19 nh4.nativeHelloWorld4(“You did it!!”, 4);
20 }
21 }
22
Accessing Strings
Two other functions exist for converting Java strings to C strings. Both
conversion functions allocate memory for the converted string on the
fly. However, these utilities handle the memory for the converted
strings differently.
Accessing Strings
As you may recall, Java strings consist of 16-bit unicode characters.
C strings, however, consist of 8-bit ASCII characters. Because strings
are common objects which are passed between Java code and native
code, several functions have been defined to help make string
manipulation simpler.
● void javaStringPrint(Hjava_lang_String *)
● int javaStringLength(Hjava_lang_String *)
For example, consider writing a class that stores the loop counter as
state information.
1 class NativeHello3 {
2
3 public int count;
4
5 public NativeHello3(int i) {
6 count = i;
7 }
8
9 public native void nativeHelloWorld3();
10
11 static {
12 System.loadLibrary(“nativeTest”);
13 }
14 }
Inside your C program, you can now access your count variable using
unhand().
1 void NativeHello3_nativeHelloWorld3(struct HNativeHello3 *this) {
2 printf(“Hello Native World!\n”);
3 printf(“Java Class member count = %d.\n”,unhand(this)->count);
4 }
Passing an Argument
When you define the native method in Java, you can supply an
argument just as you do when declaring other methods.
public native void nativeHelloWorld2(int count);
This declaration will produce the following entry in the header file
NativeHello2.h:
extern void NativeHello2_nativeHelloWorld2(
struct HNativeHello2 *,long);
Now rewrite your C method to loop for the supplied number of times.
1 #include <stdio.h>
2 #include <StubPreamble.h>
3 #include "NativeHello2.h"
4
5 void NativeHello2_nativeHelloWorld2(struct HNativeHello2 *h,
long count) {
6 for (; count > 0; count--)
7 printf("Hello Native World!\n");
8 }
Putting It Together
Now that you have all of the pieces, you must tell the system how to
assemble them. First, compile your C program. Remember to include
the automatically generated stub file. You also may need to specify the
location of the include files.
The two include directories you must access to compile this code are
$JAVA_HOME/include and $JAVA_HOME/include/solaris. You can
specify them on the command line or you can modify your INCLUDE
environment variable.
C:\> cl NativeHello.c NHW.c -FenativeTest.dll -MD -LD javai.lib
Once you have created the library file, you can run your native
method test program:
% java UseNative
Hello Native World!
or
C:\> java UseNative
Hello Native World!
At this point, the C program is the only piece of code missing. To write
the C code, you need two special include files and the function
definition from the header file.
Of course, any other header files necessary for your functions should
be included.
Find the basic information you need to start implementing your native
method in the NativeHello.h file. For each function declared in the
header file, you provide the body. Here is the NativeHello.h file
generated by javah:
1 /* DO NOT EDIT THIS FILE - it is machine generated */
2 #include <native.h>
3 /* Header for class NativeHello */
4
5 #ifndef _Included_NativeHello
6 #define _Included_NativeHello
7
8 typedef struct ClassNativeHello {
9 char PAD; /* ANSI C requires structures to have a least one
10 member */
11 } ClassNativeHello;
12 HandleTo(NativeHello);
13
14 extern void NativeHello_nativeHelloWorld(struct HNativeHello *);
15 #endif
Once you have wrapped your native methods into a class, you can
create objects of that class to access the native methods, just as you
would with regular class methods. For example, this is a program that
creates a new NativeHello object and calls your
nativeHelloWorld method:
1 class UseNative {
2 public static void main (String args[]) {
3 NativeHello nh = new NativeHello();
4 nh.nativeHelloWorld();
5 }
6 }
Compile your .java files now (using javac) so that the .class files
will be available for the rest of the process. This also helps catch any
small typing errors you may have made.
Once you have created these files, make them accessible by other
programs. While you will not modify these specific files, the header
file provides you with the information you need to write the C
program. The stub file will be linked into your library.
A Native HelloWorld
The Java interpreter executes the defined static code block when the
class is loaded. In the example above, the nativeTest library is
loaded when the class NativeHello is loaded.
Native HelloWorld
The first task will be to call a native method from a Java program. To
do this, create a native method for the HelloWorld program.
(Stub file simply provides the glue code between Java data
structures and their C counterparts.)
5. Combine the C code, header files, and stub file into a dynamic
loadable library.
There are two changes from the other public void methods you
have written:
Native Methods
You have seen many features and basic functions within the Java
programming language. However, you may want to perform tasks
with Java-based applications that you cannot accomplish with the Java
programming language alone. In these instances, you can use native
methods to link in C programs that handle your specific needs.
Objectives
At the end of this module, you will be able to:
● Create the Java code to load libraries and call native methods
B-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
A
GridBagConstraints Examples
GridBagConstraints Examples
GridBagConstraints Examples
The remainder of the sample code sets constraints for each new button
and then calls makebutton() to create the button.
1. c.gridwidth = GridBagConstraints.REMAINDER; //end row
2. makebutton("Button4", gridbag, c);
3.
4. c.weightx = 0.0; //reset to the default
5. makebutton("Button5", gridbag, c); //another row
6.
7. c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last in
row
8. makebutton("Button6", gridbag, c);
9.
10. c.gridwidth = GridBagConstraints.REMAINDER; //end row
11. makebutton("Button7", gridbag, c);
12.
13. c.gridwidth = 1; //reset to the default
14. c.gridheight = 2;
15. c.weighty = 1.0;
16. makebutton("Button8", gridbag, c);
GridBagConstraints Examples
In the code on the previous page, you set certain variables within c
with GridBagConstraints. The GridBagLayout layout manager
must now be instructed to associate those constraints with the
component you are about to add. This is done in line 5 using
GridBagLayout’s setConstraints() method.
GridBagConstraints Examples
Line 9 assigns an x weight of 1.0. This affects how space is filled within
any given row and determines how the components in that row are
resized.
GridBagConstraints Examples
The following discussion is based on the Java code that produces this
GUI:
insets
Specifies the external padding of the component—the minimum
amount of space between the component and the edges of its display
area.
anchor
Used when the component is smaller than its display area, anchor
determines where (within the area) to place the component. Valid
values are GridBagConstraints.CENTER (the default),.NORTH,
.NORTHEAST, .EAST, .SOUTHEAST, .SOUTH, .SOUTHWEST, .WEST,
and .NORTHWEST.
fill
Used when the component's display area is larger than the
component's requested size, fill determines whether (and how) to
resize the component. Valid values are GridBagConstraint.NONE (the
default), GridBagConstraint.HORIZONTAL (make the component
wide enough to fill its display area horizontally, but do not change its
height), GridBagConstraint.VERTICAL (make the component tall
enough to fill its display area vertically, but do not change its width),
and GridBagConstraint.BOTH (make the component fill its display
area entirely).
GridBagLayout Manager
Utilizing GridBagConstraints
The first five statements in the snippet of code on the previous page
are not particularly new to you. You have been instantiating objects
since the early days of your Java programming career. You have also
used setLayout() many times to establish the layout manager
controlling the layout of your components.
guiConstraints.anchor = GridBagConstraints.CENTER;
GridBagLayout Manager
GridBagLayout Functionality
Like GridLayout, the GridBagLayout layout manager aligns
components within a rectangular grid of "cells." Where GridLayout
and GridBagLayout differ is in that GridBagLayout utilizes an object
called GridBagConstraints.
...
GridBagLayout Manager
Objectives
This appendix examines the GridBagLayout layout manager in detail.
A-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
14
Exercises
Work in pairs on this lab so you can use the host name of a machine
other than your own. The purpose of this lab is to create a server and
client pair—one program that will request a file from the other.
1. Extend the client code to enable the client to request multiple files.
2. Extend the client to save the file to disk if an error is not returned.
UDP Sockets
DatagramSocket
DatagramSocket is used to read and write UDP packets. This class
has three constructors that allow you to specify which port and
internet address to bind to:
UDP Sockets
DatagramPacket
DatagramPacket has two constructors: one for receiving data and one
for sending data:
Notes
Server
Register with
ServerSocket (port #) this service Client
Wait for a
ServerSocket.accept() connection Socket (host, port#)
Socket() (Attempt to connect)
OutputStream OutputStream
InputStream
InputStream
Socket.close () Socket.close ()
The code to implement this simple model is shown on the next two
pages.
Port Numbers
Port numbers in TCP/IP systems are 16-bit numbers and are in the 0–
65535 range. In practice, port numbers below 1024 are reserved for
predefined services, and you should not use them unless you want to
communicate with one of those services (such as telnet, SMTP mail, ftp
and so forth).
Sockets
Socket is the name given, in one particular programming model, to the
endpoints of a communication link between processes. Because of the
popularity of that particular programming model, the name socket has
been reused in other areas, including Java.
Once the network connection has been set up, using the streams
associated with that connection is very similar to using any other
stream.
Objectives
At the end of this module, you will be able to:
14-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
Exercises
3. Allow the user to stop and start the animation using successive
mouse clicks.
Threads 13-37
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
SyncStack Class
SyncStack.java
1 package mod13;
2 public class SyncStack
3 {
4 private int index = 0;
5 private char [] buffer = new char[6];
6
7 public synchronized char pop() {
8 while (index == 0) {
9 try {
10 this.wait();
11 } catch (InterruptedException e) {
12 // ignore it..
13 }
14 }
15 this.notify();
16 index--;
17 return buffer[index];
18 }
19
20 public synchronized void push(char c) {
21 while (index == buffer.length) {
22 try {
23 this.wait();
24 } catch (InterruptedException e) {
25 // ignore it..
26 }
27 }
28 this.notify();
29 buffer[index] = c;
30 index++;
31 }
32 }
SyncStack Class
Consumer.java
1 package mod13;
2 public class Consumer implements Runnable
3 {
4 SyncStack theStack;
5
6 public Consumer(SyncStack s) {
7 theStack = s;
8 }
9
10 public void run() {
11 char c;
12 for (int i = 0; i < 20; i++) {
13 c = theStack.pop();
14 System.out.println("Consumed: " + c);
15 try {
16 Thread.sleep((int)(Math.random() * 1000));
17 } catch (InterruptedException e) {
18 // ignore it..
19 }
20 }
21 }
22 }
Threads 13-35
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
SyncStack Class
SyncTest.java
1 package mod13;
2 public class SyncTest
3 {
4 public static void main(String args[]) {
5 SyncStack stack = new SyncStack();
6 Runnable source = new Producer(stack);
7 Runnable sink = new Consumer(stack);
8 Thread t1 = new Thread(source);
9 Thread t2 = new Thread(sink);
10 t1.start();
11 t2.start();
12 }
13 }
Producer.java
1 package mod13;
2 public class Producer implements Runnable
3 {
4 SyncStack theStack;
5
6 public Producer(SyncStack s) {
7 theStack = s;
8 }
9
10 public void run() {
11 char c;
12 for (int i = 0; i < 20; i++) {
13 c = (char)(Math.random() * 26 + 'A');
14 theStack.push(c);
15 System.out.println("Produced: " + c);
16 try {
17 Thread.sleep((int)(Math.random() * 100));
18 } catch (InterruptedException e) {
19 // ignore it..
20 }
21 }
22 }
23 }
Putting It Together
The pop() method is similar, and shares the comments just made.
These pieces now must be assembled into complete classes and have a
harness attached to get it all running. The final code appears in the
following sections.
Threads 13-33
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
Putting It Together
Notice that the wait() call has been made explicitly as this.wait().
The use of this is redundant, but has been included to emphasize that
the rendezvous is being made on this stack object. The wait() call is
placed in a try/catch construction. Because of the possibility of
wait() exiting on an interrupt(), you must loop the test in case the
thread is roused from wait() prematurely.
Putting It Together
SyncStack Class
A newly constructed SyncStack should be empty. This can easily be
arranged using the default initialization of the values, but will be done
here explicitly as a matter of good style. The following code can be
used to build our class:
class SyncStack
{
private int index = 0;
private char [] buffer = new char[6];
Threads 13-31
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
Putting It Together
Consumer
The consumer thread will run the following method:
public void run() {
char c;
for (int i = 0; i < 20; i++) {
c = theStack.pop();
System.out.println(" Consumed: " + c);
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
// ignore it..
}
}
}
This will collect 20 characters from the stack, with a delay between
each attempt. The delay here is between 0 and 2 seconds. This means
that the stack will be emptied slower than it will be filled, and hence
should quickly fill up completely.
Now consider the construction of the stack class; an index and a buffer
array are needed. The buffer should not be too large since the point of
this exercise is to demonstrate correct operation and synchronization
when the buffer fills. In this case, the array will contain six characters.
Putting It Together
Producer
The producer thread will run the following method:
Threads 13-29
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
Putting It Together
Start by looking at the outline of the stack object and the details of the
threads that will produce and consume. Then look at the detail of the
stack and the mechanisms used to protect it and implement the
thread communication.
The stack class, called SyncStack to distinguish it from the core class
java.util.Stack, will offer the following public API:
public void push(char c);
public char pop();
Using this mechanism, you can coordinate the washing and drying
threads quite simply, all without needing to know the identity of those
threads. Every time an operation that guarantees that the other thread
can do useful work is performed, we notify() the drain board object
is notified. Every time a thread tries to work but cannot proceed
because the drain board is either empty or full, it waits on the drain
board object.
Threads 13-27
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
By calling addDish, the Washer thread would add a wet plate to the
drain board and notify the waiting Dryer thread that there was a
change.
If the drying thread is the only one waiting, then it will be awakened
and become a contender for running again. If more than one thread is
waiting, and a single notify() is issued, then only one of the waiting
threads will be removed from the set. In many systems that implement
a wait/notify mechanism, the thread that wakes up is the one that has
been waiting the longest. However, Java does not provide this
guarantee.
Notice that the notify() call is issued in this case without regard to
whether any threads are waiting or not. If the notify() method is
called when no threads are blocked in the wait pool, the call has no
effect. Calls to notify() are not stored.
The Solution
It is possible to program a solution to this scenario using the
suspend() and resume() methods. Such a solution would require
both threads to be created in cooperation, since each requires a handle
on the other. Because of this inconvenience, Java provides a
communication mechanism based on instances of objects.
Threads 13-25
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
Introduction
Often different threads are created specifically to perform unrelated
tasks. Sometimes, however, the jobs they perform are actually related
in some way. When this occurs, it may be necessary to program some
interaction between the threads. There are many standard ways of
programming thread interaction. Given any one mechanism, the
others can be implemented based on that one. This section examines
the mechanism that Java offers and describes its use.
The Problem
Why might two threads need to interact? As a simple example,
consider two people, one is washing dishes and the other is drying the
dishes. These people represent our threads. Between them is a shared
object, the drain board. Both people are lazy and would rather sit
down if they have nothing useful to do. The dryer cannot start drying
something unless there is at least one item on the drain board.
Similarly, if the drain board becomes full because the washer is going
faster, then the washer cannot proceed until the drain board has some
space.
However, marking the method in this way allows users of the method
to know that synchronization is taking place. This can be important
when designing against deadlock, which discussed in the next section.
Deadlock
In programs where multiple threads are competing for access to
multiple resources, there may be a possibility of a condition known as
deadlock. This occurs when one thread is waiting for a lock held by
another thread, but the other thread is waiting for a lock already held
by the first thread. In this condition, neither can proceed until after the
other has passed the end of its synchronized block. Since neither is
able to proceed, neither can pass the end of its block.
Threads 13-23
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
Putting It Together
As has been suggested, the synchronized() mechanism only works if
the programmer puts the calls in the correct places. How to put
together a properly protected class will now be discussed.
Consider the accessibility of the data items which form the delicate
parts of the object. If these are not marked as private, they can be
accessed from code outside the class definition itself. In this case, you
must trust that other programmers will not omit the protections that
are required. This is not a safe strategy. For this reason, the data should
always be marked as private.
The lock flag is given back to its object automatically when the thread
which holds it passes the end of the block associated with the
synchronized() call that originally obtained the flag. Java takes great
care to ensure that the flag is always returned correctly, hence if the
synchronized block generates an exception or a loop break jumps out
of the block, the flag will be returned properly. Also, if a thread issues
a synchronized call on the same object twice, the flag will be correctly
released on exit from the outermost block and the innermost one is
effectively ignored.
Threads 13-21
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
It is important to realize that this has not, of itself, protected the data
in the object this. If the pop() method, without modification, is
invoked by another thread, there is a risk of damaging the consistency of
the this object.
Threads 13-19
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
Threads 13-17
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
which effectively serves to ignore the character "r". After this, it then
returns the character "q". So far, the behavior has been as if the letter
"r" had not been pushed, so it is difficult to say if there is a problem.
But now look at what happens when the original thread, a, continues
to run.
Notice that this configuration implies the "q" is valid and the cell
containing "r" is the next empty cell. In other words, "q" will be read as
having been placed into the stack twice, and the letter "r" will never
appear.
Introduction
This module discusses the use of the synchronized keyword. This
provides the Java language with a mechanism to allow programmer
control over threads which are sharing data.
The Problem
Imagine a class which represents a stack. This class might first appear
as:
1 public class Stack
2 {
3 int idx = 0;
4 char [] data = new char[6];
5
6 public void push(char c) {
7 data[idx] = c;
8 idx++;
9 }
10
11 public char pop() {
12 idx--;
13 return data[idx];
14 }
15 }
The behavior of this model requires that the index value contain the
array subscript of the next empty cell in the stack. The "predecrement,
postincrement" approach is used to generate this information.
Threads 13-15
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
Which to Use?
Given a choice of approaches, how can you decide between them?
There are points in favor of each approach.
So far, you have seen how threads can be created with a separate class
which implements Runnable. In fact, this is not the only possible
approach. The definition of the Thread class states that it implements
the Runnable interface. It is possible to create a thread by creating a
class which extends Thread rather than implementing Runnable.
1 public class myThread extends Thread {
2 public void run() {
3 while (running) {
4 // do lots of interesting stuff
5 sleep(100);
6 }
7 }
8
9 public static void main(String args[]) {
10 Thread t = new myThread();
11 t.start();
12 }
13 }
Here there is only one class, myThread. When the Thread object is
created it is given no arguments. This form of constructor creates a
thread which uses its own built-in run() method.
Threads 13-13
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
join()
The join() method causes the current thread to wait until the thread
on which the join method is called terminates. For example:
TimerThread tt = new TimerThread (100);
tt.start ();
...
public void timeout() {
// Wait here for the timer thread to finish
tt.join ();
...
// Now continue in this thread
...
}
where the join method will either suspend the current thread for a
number of timeout milliseconds or until the thread it is called on
terminates.
A pair of Thread methods are available for this. They are called
suspend() and resume(). For example:
1 public class Xyz implements Runnable {
2 public void run() {
3 // do lots of interesting things...
4
5 // then wait until told to continue
6 Thread.currentThread().suspend ();
7 // now do more things...
8 }
9 }
Testing a Thread
It is sometimes possible for a thread to be in an unknown state (for
example, this might occur if your code is not directly in control of a
particular thread).The method isAlive() is used to determine if a
thread is still viable. Alive does not imply that the thread is running,
only that it has been started and has neither been stopped, nor run off
the end of its run() method.
sleep()
Terminating a Thread
When a thread returns from the end, its run() method dies. After this,
it cannot run again.
Notice that in this case, the execution of stop() will destroy the
current execution context and hence no more of the run() loop will be
executed in this context. The use of Thread.currentThread() is not
restricted to this specific example of stop().
Threads 13-9
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
Notice the use of try and catch. Also note that the sleep() call is a
static method in the Thread class and hence is referred to as
Thread.sleep(x). This argument specifies the minimum number of
milliseconds for which the thread must be made inactive. The
execution of the thread will not resume until after this period, which
includes time for other threads to block.
Thread Scheduling
Although the thread becomes runnable, it does not necessarily start
immediately. Only one action at a time can be done on a machine that
has only one CPU. How the CPU is allocated when more than one
thread could usefully be working is discussed next.
All threads which are runnable but not running are kept on queues
according to their priority. The first thread on the highest priority non-
empty queue will run. When a thread stops running because of pre-
emption, it is taken from the running state and placed at the back end
of the runnable queue. Similarly, a thread which becomes runnable
after being blocked (sleeping or waiting for I/O, for example) always
joins the back end of its queue.
Given that Java threads are not necessarily timesliced, you must
ensure that the code for your threads gives other threads a chance to
execute from time to time. This can be achieved by issuing the
sleep() call in the main loop at various intervals.
Threads 13-7
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
new
wait
notify
sleep
runnable awaken blocked
suspend
resume
block I/O
complete I/O
stop
dead
New thread
}
Thread t
CPU
Code Data
Xyz class Instance "r" of Xyz
Threads 13-5
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
For example,
1 public class Xyz implements Runnable {
2 int i;
3 public void run() {
4 while (true) {
5 System.out.println("Hello " + i++);
6 }
7 }
8 }
A thread or
CPU execution context
Code Data
A thread comprises three main parts. First, there is the virtual CPU.
Second, there is the code that this CPU is executing. Third, there is the
data that the code works on.
Threads 13-3
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
13
You do not need to be concerned with how this effect is achieved, just
consider the implications from a programming point of view. If you
have more than one job being performed, this is similar to having
more than one computer. In this module, a thread, or execution context,
is considered to be the encapsulation of a virtual CPU with its own
program code and data. The class java.lang.Thread in the core Java
libraries allows users to create and control their threads.
Objectives
Upon completion of this module, you will be able to:
● Create separate threads in Java, controlling the code and data that
are used by that thread
13-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
12
Exercises
1. Use the Paint program from Module 9 and save the state of the
canvas to a file.
2. Add a menu option to the Paint program that allows the user to
save to a file and restore from a file. Use the File Dialog class to
allow the user to select a file with a .pix extension.
Reading
Reading the object is as simple as writing it, with one caveat—the
readObject() method returns the stream as an Object type, and it
must be cast to the appropriate class name before methods on that
class can be executed.
1 public class UnSerializeDate {
2 UnSerializeDate () {
3 Date d = null;
4 try {
5 FileInputStream f = new
6 FileInputStream("date.ser");
7 ObjectInputStream s = new
8 ObjectInputStream(f);
9 d = (Date) s.readObject ();
10 s.close ();
11 } catch (Exception e) {
12 e.printStackTrace ();
13 }
14
15 System.out.println("Unserialized Date object
from date.ser");
16 System.out.println("Date: "+d);
17 }
18
19 public static void main (String args[]) {
20 new UnSerializeDate();
21 }
22 }
Writing
Writing and reading an object to a file stream is a simple process.
Consider the following code fragment that sends an instance of a
java.util.Date object to a file:
1 public class SerializeDate {
2 SerializeDate() {
3 Date d = new Date ();
4 try {
5 FileOutputStream f = new
6 FileOutputStream("date.ser");
7 ObjectOutputStream s = new
8 ObjectOutputStream(f);
9 s.writeObject (d);
10 s.close ();
11 } catch (IOException e) {
12 e.printStackTrace ();
13 }
14 }
15
16 public static void main (String args[]) {
17 new SerializeDate();
18 }
19 }
Serializable
Serializable
Object Graphs
When an object is serialized only the data of the object is preserved;
methods and constructors are not part of the serialized stream. When a
data variable is an object, the data members of that object are also
serialized. The tree, or structure of an object’s data, including these
sub-objects, constitutes the object graph.
Some object classes are not serializable because the nature of the data
they represent is constantly changing; for example, streams such as
java.io.FileInputStream and java.io.FileOutputStream, and
java.lang.Thread. If a serializable object contains a reference to a
non-serializable element, the entire serialization operation fails and a
NotSerializableException is thrown.
● long getFilePointer();
Sets the file pointer to the specified absolute position. The position
is given as a byte-offset from the beginning of the file. Position 0
marks the beginning of the file.
● long length();
Returns the length of the file. Position length() marks the end of
the file.
Appending Information
You can use random access files to accomplish an appending mode for
file output.
myRAFile = new RandomAccessFile("java.log","rw");
myRAFile.seek(myRAFile.length());
// Any subsequent write()s will be appended to the file
Often you will find that you want to read data within a file without
reading the file from beginning to end. You may want to access a text
file as a database in which case you move around reading one record,
then another, and then another—each in different parts of the file. The
Java language provides a RandomAccessFile class for handling this
type of input or output.
Accessing Information
RandomAccessFile objects expect to read and write information in the
same manner as data input and data output objects. You have access to
all of the read() and write() operations found in the
DataInputStream and DataOutputStream classes.
Once you have created a File object, you can use any of the following
methods to gather information about the file:
File Names
● String getName()
● String getPath()
● String getAbsolutePath()
● String getParent()
File Tests
● boolean exists()
● boolean canWrite()
● boolean canRead()
● boolean isFile()
● boolean isDirectory()
● boolean isAbsolute();
● long lastModified()
● long length()
● boolean delete()
Directory Utilities
● boolean mkdir()
● String[] list()
Files
Before you can perform I/O operations on a file, you must obtain basic
information about that file. The File class provides several utilities for
dealing with files and obtaining basic information about these files.
The constructor you use often depends on the other file objects you
can access. For example, if you use only one file in your application,
use the first constructor. If, however, you use several files from a
common directory, using the second or third constructors may be
easier.
Note – You can use a File object as the constructor argument for
FileInputStream and FileOutputStream objects in place of a String.
This allows better independence from the local file system conventions
and is generally recommended.
Unicode
Java uses Unicode for representing strings and characters, and it
provides 16 bit versions of streams to allow characters to be treated
similarly. These 16 bit versions are called readers and writers. As with
streams, a variety of them are available in the java.io package.
Using this conversion scheme, Java is able to use the full flexibility of
the local-platform character set while still retaining platform
independence through the internal use of Unicode.
In addition to basic file access, Java provides you with the ability to
use uniform resource locators (URLs) as a means of accessing objects
across a network. You implicitly use a URL object when accessing
sounds and images using the getDocumentBase() method for applets.
String imageFile = new String ("images/Duke/T1.gif");
images[0] = getImage(getDocumentBase(), imageFile);
Caution – Remember that most users may have their browser security
! set to not allow applets to access files.
DataInputStream Methods
byte readByte()
long readLong()
double readDouble()
DataOutputStream Methods
void writeByte(byte)
void writeLong(long)
void writeDouble(double)
Notice that the methods of the DataInputStream are paired with the
methods of the DataOutputStream.
These streams have methods for reading and writing strings, but these
methods should not be used. They have been superseded by readers
and writers that will be discussed later.
PipedInputStream andPipedOutputStream
Piped streams can be used for communicating between threads. A
PipedInputStream object in one thread receives its input from a
complementary PipedOutputStream object in another thread. The
piped streams must have both an input side and an output side to be
useful.
InputStream
SequenceInputStream FileInputStream
PipedInputStream ByteArrayInputStream
FilterInputStream StringBufferInputStream
DataInputStream
LineNumberInputStream
PushbackInputStream BufferedInputStream
FileOutputStream outfile =
new FileOutputStream("results.dat");
Note – Towards the end of this module you will learn about two other
classes which add to Java file I/O capabilities.
OutputStream Methods
void write(int)
void write(byte[])
void write(byte[], int, int)
These methods write to the output stream. As with input, you should
always try to write data in the largest practical block.
void close()
Output streams should be closed when you have finished with them.
Again, if you have a stack and close the top one, this closes the rest of
the streams.
void flush()
These three methods provide access to the data from the input pipe.
The simple read method returns an int which contains either a byte
read from the stream or -1, which indicates the end of file condition.
The other two methods are read into a byte array and return the
number of bytes read. The two int arguments in the third method
indicate a subrange in the target array which needs to be filled.
Note – For efficiency, always read data in the largest practical block of
data.
void close()
When you have finished with a stream, you should close it. If you
have a "stack" of streams, using filter streams, you should close the
stream at the top of the stack. This operation also closes the lower
streams.
int available()
This module examines how the Java language uses streams to handle
byte and character I/O (including stdin, stdout, and stderr). Later
sections examine some specific details of handling files and working
with the data they contain.
Stream Fundamentals
A stream is either a source of bytes or a destination for bytes. The order
is significant. So, for example, a program that wants input from a
keyboard can use a stream to do so.
The two basic categories of streams are: input streams and output
streams. You can read from an input stream, but cannot write to it.
Conversely, you can write to an output stream, but cannot read from
it. To read bytes from an input stream, there must be a source of
characters associated with the stream.
In the java.io package some streams are node streams, that is they
read from or write to a specific place such as a disk file or an area of
memory. Other streams are called filters. A filter input stream is created
with a connection to an existing input stream. This is done so that
when you try to read from the filter input stream it supplies you with
characters that originally came from the other input stream.
w d
o o r l
l
"Flow" of
l bytes down
stream
e
read()
h
Objectives
At the end of this module, you will be able to:
12-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
11
Exercises
1. Use the same step that is in Level 2 lab, write the entire program
rather than use the template. Create an application or an applet
with a button, and a large window area (for example, 400x400
pixels)
Exercises
2. Compare the total size of the .class files that are created.
3. Delete PaintHandler.java.
Inner Classes
Anonymous Classes
It is possible to include an entire class definition within the scope of an
expression. This approach defines the anonymous class and creates the
instance all at once. For example, part of the TwoListenInner could
be rewritten to use an anonymous class:
1 public void go() {
2 f = new Frame("Two listeners example");
3 f.add ("North", new Label ("Click and drag the mouse"));
4 tf = new TextField (30);
5 f.add ("South", tf);
6
7 f.addMouseMotionListener (new MouseMotionAdapter() {
8 public void mouseDragged (MouseEvent e) {
9 String s =
10 "Mouse dragging: X = " + e.getX() + " Y = "
11 + e.getY();
12 tf.setText (s);
13 }
14 } ); // <- note the closing parenthesis
15
16 f.addMouseListener (new MouseEventHandler());
17 f.setSize(300, 200);
18 f.setVisible(true);
19 }
Inner Classes
Inner Classes
If the above code were rewritten with two additional top-level classes
for MouseMotionHandler and MouseEventHandler, three separate
classes would be created and the overall size of the application would
be 2864 bytes.
Inner Classes
Inner classes are best used as a convenience feature for creating event
adapters. Consider the TwoListen class in the Event module rewritten
to include two handler classes within the TwoListen class:
1 import java.awt.*;
2 import java.awt.event.*;
3
4 public class TwoListenInner {
5 private Frame f;
6 private TextField tf;
7
8 public static void main(String args[]) {
9 TwoListenInner tli = new TwoListenInner();
10 tli.go();
11 }
12
13 public void go() {
14 f = new Frame("Two listeners example");
15 f.add ("North", new Label ("Click and drag the mouse"));
16 tf = new TextField (30);
17 f.add ("South", tf);
18
19 f.addMouseMotionListener (new MouseMotionHandler());
20 f.addMouseListener (new MouseEventHandler());
21 f.setSize(300, 200);
22 f.setVisible(true);
23 }
Inner Classes
JDK 1.1 now supports classes that are members of other classes
defined locally with a block of statements or anonymously within an
expression. Inner classes have the following properties:
● The class name can only be used within the defined scope, except
when used in a qualified name. The name of the inner class must
differ from the enclosing class.
● The inner class can use both class and instance variables of
enclosing classes and local variables of enclosing blocks.
Deprecation
Here the 1.1 version uses two new classes: SimpleDateFormat, a class
used to take any String date format and create a Date object, and the
GregorianCalendar class, used to create a calendar with the local
time zone and locale.
Deprecation
The -deprecation flag will report any methods within the class used
that are deprecated. For example, here is a utility class called
DateConverter that converts a date in the format mm/dd/yy to the
day of the week:
1 package myutilities;
2 import java.util.*;
3 import java.text.*;
4 public final class DateConverter {
5
6 private static String day_of_the_week [] = {"Sunday", "Monday",
"Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
7
8 public static String getDayOfWeek (String theDate){
9 int month, day, year;
10
11 StringTokenizer st =
12 new StringTokenizer (theDate, "/");
13 month = Integer.parseInt(st.nextToken ());
14 day = Integer.parseInt(st.nextToken());
15 year = Integer.parseInt(st.nextToken());
16 Date d = new Date (year, month, day);
17
18 return (day_of_the_week[d.getDay()]);
19 }
20 }
When this code is compiled under JDK 1.1 with the -deprecation
flag, you get:
% javac -deprecation DateConverter.java
DateConverter.java:20: Note: The constructor java.util.Date(int,int,int)
has been deprecated.
Date d = new Date (year, month, day);
^
DateConverter.java:23: Note: The method int getDay() in class
java.util.Date has been deprecated.
return (day_of_the_week[d.getDay()]);
^
Note: DateConverter.java uses a deprecated API. Please consult the
documentation for a better alternative.
3 warnings
Deprecation
Between JDK Version 1.0 and JDK Version 1.1, a significant effort was
made to standardize the names of methods. As a result, a significant
number of class constructors and method calls are obsolete. They have
been replaced by method names that follow a more object-oriented
naming convention and, in general, make life less complicated for the
programmer.
Currently in JDK 1.1.1, the deprecated methods exist along with the
new methods, but this situation is going to change. Whenever you are
moving code from JDK 1.0 to JDK 1.1, or even if you are using code
that previously worked with JDK 1.0, it is a good idea to compile the
code with the -deprecation flag.
Interfaces
Abstract Classes
You can declare reference variables of the type of the abstract class.
Final Classes
Java allows the keyword final to be applied to classes. If this is done,
the class cannot be subclassed. The class java.lang.String, for
example, is a final class. This is done for security reasons, since it
ensures that if a method has a reference to a String, it is definitely a
real String and not a modified subclass that might have been
maliciously added.
Final Methods
Individual methods can be marked as final also. If this is done, then
it is not possible to override the method. This is done for security
reasons. The caller of a method can be assured that the proper
behavior will result a subversive alternative.
Final Variables
If a variable is marked as final, the effect is to make it a constant.
Any attempt to change the value of a final variable will cause a
compiler error.
Note – If you mark a variable of reference type (that is any class type)
as final, that variable cannot refer to any other object. It is not,
impossible to change the object’s contents.
Class Methods
Sometimes, you need to access program code when you do not have
an instance of a particular object available. A method that is marked
using the keyword static can be used in this way and is sometimes
called a class method.
public class GeneralFunction {
public static int addUp(int x, int y) {
return x + y;
}
}
Note – This is why main() is declared static and why main() cannot
access any variables that are not the arguments passed from the
command line or static. Java ClassName invokes
ClassName.main() with the arguments passed on the command
line.
Class Variables
You can achieve this effect by marking the variable with the keyword
static. Such a variable is sometimes called a class variable to
distinguish it from a member or instance variable.
public class Count {
private int serialNumber;
private static int counter = 0;
public Count() {
counter++;
serialNumber = counter;
}
}
b. A constructor is called.
(You can control the way that the parent class is constructed if you
need to.)
public class Employee {
String name;
public Employee(String n) {
name = n;
}
}
public Employee(String n) {
this(n, 0);
}
public Employee() {
this(“Unknown”);
}
}
Quite often when you override a method, your real goal is not to
replace the existing behavior but to extend that behavior in some way.
This can be achieved using the keyword super:
public class Employee {
private String name;
private int salary;
Notice that a call of the form super.method() will invoke the entire
behavior, along with any side effects, of the method that would have
been invoked if the object referred to by super.method() had
actually been of the parent class. The method does not have to be
defined in that parent class, it could be inherited from some class even
further up the hierarchy.
Objectives
Upon completion of this module, you will be able to:
● Use the -deprecation flag for the Java compiler to determine the
appropriate JDK 1.1 methods to use
11-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
10
Exercises
2. Try making each square (or circle) a different color. If you import
the java.awt.Color class, you can add color to Java applets using
the setColor method.
import java.awt.Color;
. . .
public void paint(Graphics g) {
g.setColor(Color.blue);
g.drawLine(5, 5, 50, 50);
. . .
}
Exercises
$ javac HwMouse.java
$ appletviewer HwMouse.html
Applet/Application (Continued)
30 // Call the applet methods
31 app.init();
32 app.start();
33 } // end main
34
35 public void paint (Graphics g) {
36 g.drawString ("Hello World", 25, 25);
37 }
38
39 public void destroy () {
40 System.exit (0);
41 }
42 }
43
44 // Class used to control the applet window
45 //
46 class WindowControl extends WindowAdapter {
47
48 Applet c;
49
50 public WindowControl (Applet c) {
51 this.c = c;
52 }
53
54 public void windowClosing (WindowEvent e) {
55 c.destroy ();
56 }
57 }
It is possible to create Java code that can be used as both a Java applet
and a Java application from a single class file. There is a little more
work involved in understanding what the application requires, but
once created, the applet/application code can be used as a template
for more complicated programs.
Applet/Application
Here is the “Hello World” example coded as an applet/application:
1 // Example of Hello World that is both
2 // an applet and an application
3 //
4
5 import java.applet.Applet;
6 import java.awt.*;
7 import java.awt.event.*;
8
9 public class AppletApp extends Applet {
10
11 // An application will require a main()
12 public static void main (String args[]) {
13
14 // Create a Frame to house the applet
15 Frame frame = new Frame("Application");
16
17 // Create an instance of the class (applet)
18 AppletApp app = new AppletApp();
19
20 // Add it to the center of the frame
21 frame.add("Center",app);
22 frame.setSize (200, 200);
23 frame.validate();
24 frame.setVisible(true);
25
26 // Register the AppletApp class as the
27 // listener for a Window Destroy event
28 frame.addWindowListener
29 (new WindowControl (app));
Reading Parameters
Inside the applet, you can use the method getParameter() to read
these values.
import java.awt.*;
import java.applet.*;
If the parameter name cannot be found in any <param> tag inside the
<applet></applet> pair, then getParameter() returns null. A
production program should handle this gracefully.
The parameter type is always a String. If you need this in other forms
you must convert it. For example, to read an int parameter:
int speed = Integer.parseInt (getParameter (“speed”));
The program below displays the location of the mouse click within the
applet:
1 //
2 // HelloWorld extended to watch for mouse input
3 // "Hello World!" is reprinted at the location of
4 // the mouse click.
5 //
6
7 import java.awt.*;
8 import java.awt.event.*;
9 import java.applet.Applet;
10
11 public class HwMouse extends Applet
12 implements MouseListener {
13
14 int mouseX=25;
15 int mouseY=25;
16
17 // Register the mousePressed Event
18 public void init () {
19 addMouseListener (this);
20 }
21
22 public void paint(Graphics g) {
23 g.drawString("Hello World!", mouseX, mouseY);
24 }
25
26 public void mousePressed(MouseEvent evt){
27 mouseX = evt.getX();
28 mouseY = evt.getY();
29 repaint();
30 }
31
32 // We are not using the other mouse events
33 public void mouseClicked (MouseEvent e) {}
34 public void mouseEntered (MouseEvent e) {}
35 public void mouseExited (MouseEvent e) {}
36 public void mouseReleased (MouseEvent e) {}
37
38 }
Mouse Input
One of the most useful features the Java language supports is direct
interactivity. An application can pay attention to the mouse and react
to changes in the mouse.
Recall from Module 8 that the 1.1 Event Model supports an event type
for each type of interactivity. Mouse events are received by classes that
implement the MouseListener interface, which receives events for:
You can also treat audio clips like images. You can load them and play
them later.
Once a clip is loaded, use one of three methods associated with it:
play, loop, or stop.
To start the clip playing and have it loop (automatically repeat), use
the loop method in the java.applet.AudioClip class:
sound.loop();
Audio Clips
The Java language also has methods to play audio clips. These
methods are in the java.applet.AudioClip class. You will need the
appropriate hardware for your computer to play audio clips.
Playing a Clip
The easiest way to listen to an audio clip is through Applet’s play
method:
play(URL soundDirectory, String soundfile);
A common URL to use with the play() method is the directory where
the HTML files are located. Access that location through the
getDocumentBase() method:
play(getDocumentBase(), "bark.au");
For this to work, the HTML file and the bark.au file must be in the
same directory.
All Java programs have access to network facilities using the classes in
the java.net package that is discussed in Module 14. Applets
additionally have methods that allow them to determine information
about the browser environment in which they have been launched.
Using the URL object as a starting point, you can fetch sounds and
images into your applet.
Description (Continued)
Browsers that are not Java-enabled will display any regular HTML
included between your <applet> and </applet> tags; Java-enabled
browsers ignore regular HTML between these two tags.
Notice that the general format of this tag is the same as any other
HTML, using the < and > symbols to delimit the instructions. All the
parts shown here are required. You must have both <applet ...>
and </applet>. The <applet ...> part specifies a code entry and
a width and height.
Note – In general, you should treat applets as being of fixed size and
use the size specified in the applet tag. You will find out later that it is
possible under some conditions to change the size of an applet, but the
results are not always tidy.
Description (Continued)
● width = pixels height = pixels – These required attributes give the
initial width and height (in pixels) of the applet display area, not
including any windows or dialogs that the applet brings up.
Syntax
Below is the complete syntax for the applet tag:
<applet
[archive=archiveList]
code=appletFile.class
width=pixels height=pixels
[codebase=codebaseURL]
[alt=alternateText]
[name=appletInstanceName]
[align=alignment]
[vspace=pixels] [hspace=pixels]
>
[<param name=appletAttribute1 value=value>]
[<param name=appletAttribute2 value=value>]
. . .
[alternateHTML]
</applet>
Description
● archive = archiveList – This optional attribute describes one or
more archives containing classes and other resources that will be
“preloaded.” The classes are loaded using an instance of an
AppletClassLoader with the given CODEBASE. The archives in
archiveList are separated by a comma (,).
Note – This file is relative to the base URL of the HTML file you are
loading it from. It cannot include a path name. To change the base URL
of the applet, use the codebase tag.
Synopsis
appletviewer [-debug] urls ...
If the HTML file passed to the appletviewer does not contain a valid
<applet> tag, the appletviewer will do nothing. The appletviewer
does not display other HTML tags.
The only valid option to the appletviewer is the -debug flag which
starts the applet in the Java debugger, jdb. Compile your Java code
with the -g option to see the source code in the debugger.
Example
The appletviewer command shown below starts the appletviewer:
$ appletviewer HelloWorld.html
The appletviewer
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel java.awt.Window
java.awt.Frame
java.applet.Applet
sun.applet.AppletViewer
The appletviewer
AWT Painting
The Applet model requires that you adopt a specific strategy for
maintaining your display:
● Your paint() method should render the display based only on the
contents of the model. This allows it to regenerate the display
consistently whenever it is called, and handle exposure correctly.
Note – A single AWT thread handles all component painting and the
distribution of input events. Because of this handling, you should
avoid letting paint() or update()run too long. In extreme cases, you
will need the help of other threads to achieve this. Thread
programming is the subject of a later module.
AWT Painting
The following diagram shows the ways that paint(), update(), and
repaint() methods are related:
update() -
clear area
call paint()
paint()
AWT Painting
The first of these conditions is exposure; where part of the display has
been damaged and must be replaced. This damage can occur at any
time and your program must be able to resolve this situation.
Applet Methods
stop()
The stop() method is called when the applet ceases to be “live.” This
happens when the browser is iconized or it follows a link to another
URL. The applet can use this method to stop animation.
1 public void stop() {
2 musicClip.stop();
3 }
The applet life cycle is a little more complex than what has been
discussed so far. There are three major methods that relate to its life
cycle: init(), start(), and stop().
init()
This member function is called at the time the applet is created and
loaded into a Java-enabled browser (such as the appletviewer). The
applet can use this method to initialize data values. This method is
called when the applet is first loaded. init() runs to completion
before start() is called.
start()
Once the init()method completes, the start() method “tells” the
applet it should become “live.” It also happens whenever the browser
is restored after being iconized or when the browser returns to the
page containing the applet after moving to another URL. This means
the applet can use this method to start animation and play sounds.
1 public void start() {
2 musicClip.play();
3 }
Writing an Applet
Applet Display
Applets are essentially graphical in nature, so although you can issue
System.out.println() calls, you will not normally do so. Instead,
you will create your display in a graphical environment.
Writing an Applet
Both the init() and start() methods run to completion before the
applet becomes “live,” and because of this they cannot be used to
program ongoing behavior into an applet. In fact, unlike the main()
method in a simple application, there is no method that executes
continuously throughout the “life” of the applet. You will see later
how to do this using threads, but for now, you cannot do this.
Writing an Applet
To be an applet, the class must be public and the file name must match
the name of the applet class; in this case, HelloWorld.java.
Furthermore, the class must be a subclass of the class
java.applet.Applet.
java.lang.object
java.awt.Component
java.awt.Container
java.awt.Frame java.awt.Panel
java.applet.Applet
This hierarchy shows that an applet can be used directly as the starting
point for an AWT layout. Because an applet is a panel, it has a flow
layout manager by default.
What Is an Applet?
What Is an Applet?
Loading an Applet
Because an applet runs in the environment of a Web browser, it is not
started directly by typing a command. You must create an HTML file
which tells the browser what to load and how to run it. You then
“point” the browser at the URL that specifies that HTML file. (The
format of the HTML file is discussed later in this module.) For
example:
<HTML>
:
2. Browser loads HTML document
<APPLET CODE = ...>
</APPLET>
Browser
Loading...
Objectives
Upon completion of this module, you will be able to:
● Use applet methods to read images and files from URLs (uniform
resource locators)
10-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
9
Exercises
Printing
The Java 1.1 printing system allows the use of local printer control
conventions. Users will see a printer selection dialog box when a print
operation is started. They can then choose options such as paper size,
print quality, and which printer to use.
Frame f = new Frame("Print test");
Toolkit t = f.getToolkit();
PrintJob job = t.getPrintJob(f, "MyPrintJob", null);
Graphics g = job.getGraphics();
You can use any of the graphics class drawing methods to write to the
printer. Alternatively, as shown here, you can ask a component to
draw itself onto the graphic. The print() method asks a component
to draw itself in this way, but it only relates to the component that it
has been called for. In the case of a container, you can use the
printComponents() method to cause the container and all the
components that it holds to be drawn onto the printer.
g.dispose();
job.end();
When you have completed the job, call the end() method on the print
job object. This indicates that the print job is complete and allows the
printer spooling system to run the job and release the printer for other
jobs.
Fonts
The font used for displaying text in a component can be specified by
using the method setFont(). The argument to this method should be
an instance of the java.awt.Font class.
No constants are defined for fonts, but you can create a font by
specifying the name of the font, the style, and the point size.
Font f = new Font(“TimesRoman”, Font.PLAIN, 14);
● Dialog
● Helvetica
● TimesRoman
● Courier
● Font.BOLD
● Font.ITALIC
● Font.PLAIN
● Font.BOLD + Font.ITALIC
Colors
Two methods are used to set the colors of a component, these are
● setForeground()
● setBackground()
PopupMenu
CheckboxMenuItem
MenuItem
Menu
Note – The menus shown here are empty, which accounts for the
appearance of the File menu.
MenuBar
The MenuBar does not support listeners. As part of the normal menu
behavior, anticipated events that occur in the region of a menu bar will
be processed automatically.
Menus
Menus are different from other components in one crucial way: you
cannot add menus to ordinary containers and have them laid out by
the layout manager. You can only add menus to specific things called
menu containers. You can only start a menu “tree” by putting a menu
bar into a frame, using the setMenuBar() method. From that point,
you can add menus to the menu bar and menus or menu items to the
menus.
ScrollPane
The ScrollPane creates and manages the scroll bars and holds a
single component. You cannot control the layout manager it uses.
Instead, you can add a Panel to the scroll pane, configure the layout
manager of that panel, and place your components into that panel.
FileDialog
Dialog
Dialogs are not normally made visible to the user when they are first
created. They are usually “popped up” in response to some other user
interface action such as the pressing of a button.
public void actionPerformed(ActionEvent ev) {
d.setVisible(true);
}
Note – You should treat a Dialog as a reusable device. That is, you
should not destroy the individual object when it is dismissed from the
display. It should be kept for later reuse. The garbage collector can
make it too easy to waste memory. Remember, creating and initializing
objects takes time and should not be done without some thought.
List
TextComponent
Both text area and text field are documented in two parts. If you look
up a class called TextComponent you will find many essential
documented methods. This is because text area and text field are
subclasses of text component.
You have seen that the constructors for both TextArea and TextField
classes allow you to specify a number of columns for the display.
Remember that the size of a displayed component is the responsibility
of a layout manager, so these preferences might be ignored.
Furthermore, the number of columns is interpreted in terms of the
average width of characters in the font that is being used. The number
of characters that are actually displayed might vary radically if a
proportionally spaced font is used.
TextArea
You can add general component listeners to the text area, but because
the text is multi-line, pressing the Enter key simply puts another
character into the buffer. If you need to recognize “completion of
input,” you can put an Apply or Commit button next to a text area to
allow the user to indicate this.
TextField
Like the text area, the text field can be set to read only. It does not
display scrollbars in either direction, but can scroll overly long text left
to right if needed.
Label
A Label object simply displays a single line of text. The program can
change the text, but the user cannot. No special borders or other
decorations are used to delineate a label.
Label l = new Label(“Hello”);
add(l);
Canvas
Canvas
Canvas
The Canvas can “listen” to all the events that are applicable to a
general component. Notably you may want to add KeyListener,
MouseMotionListener, or MouseListener objects to it to allow it to
respond in some way to user input. The methods in these interfaces
receive KeyEvent and MouseEvent objects, respectively.
Choice
The Choice component provides a simple “select one from this list”
type of input:
Choice c = new Choice();
c.addItem("First");
c.addItem("Second");
c.addItem("Third");
c.addItemListener(this);
add(c);
When the Choice is clicked on, it displays a list of items that have
been added to it. Notice that the items added are String objects.
Checkboxes
Buttons
Initially, the components of the AWT are described. These are used to
construct user interfaces. You need to be aware of the full set of UI
components so that you can choose appropriate ones when building
your own interfaces.
Objectives
Upon completion of this module, you will be able to
9-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
8
Exercises
1. Use the GUI code you created from the previous lab for this
exercise. Write an event code that will connect the calculator’s user
interface to the appropriate event handlers for the functions on a
calculator.
1. Begin with the Teller.java GUI code you created for the
previous module.
Event Adapters
● mouseClicked (MouseEvent)
● mouseEntered (MouseEvent)
● mouseExited (MouseEvent)
● mousePressed (MouseEvent)
● mouseReleased (MouseEvent)
This way, the Listener routine that you define can extend the
Adapter class and override only the methods that you need.
For example:
import java.awt.*;
import java.awt.event.*;
Multiple Listeners
The AWT event listening framework actually allows multiple listeners
to be attached to the same component. In general, if you want to write
a program that performs multiple actions based on a single event, you
should code that behavior into your handler method. However,
sometimes a program’s design requires multiple unrelated parts of the
same program to react to the same event. This might happen if, say, a
context sensitive help system is being added to an existing program.
The events caused by moving the mouse with a button pressed can be
picked up by a class that implements the MouseMotionListener
interface. This interface requires two methods, mouseDragged() and
mouseMoved(). Even if you are only interested in the drag
movement, both methods must be provided. The body of the
mouseMoved() method can be empty, however.
mouseMoved(MouseEvent)
mouseReleased(MouseEvent)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mouseClicked(MouseEvent)
keyReleased(keyEvent)
keyTyped(keyEvent)
focusLost(FocusEvent)
componentHidden(ComponentEvent)
componentResized(ComponentEvent)
componentShown(ComponentEvent)
windowOpened(WindowEvent)
windowIconified(WindowEvent)
windowDeiconified(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
componentRemoved(ContainerEvent)
Categories of Event
The general mechanism for receiving events from components has
been described in the context of a single type of event. A number of
events are defined in the java.awt.event package, and third-party
components can be added to this list.
● Although the current JDK supports the JDK 1.0 event model in
addition to the delegation model, the JDK 1.0 and JDK 1.1 event
models cannot be mixed.
The ButtonHandler class is the handler class that the event will be
delegated to.
1 import java.awt.event.*;
2 public class ButtonHandler implements ActionListener {
3 public void actionPerformed(ActionEvent e) {
4 System.out.println("Action occurred");
5 }
6 }
Panel
Action event
Button Action handler
actionPerformed (ActionEvent e) {
...
Events are objects that are only reported to registered listeners. Every
event has a corresponding listener class (interface). The class that
implements the listener interface defines each method that can receive
an Event object.
Each listener interface also defines what methods can receive events.
Components that do not register a listener do not receive events and
are not propagated.
JDK 1.0 uses a hierarchal event model, and JDK 1.1 uses a delegation
event model. While this course covers the JDK 1.1, it is important to
recognize how these two event models compare.
Frame
Panel
For example, in the figure above, a mouse click on the Button object
(contained by a Panel on an Frame) sends an action event to the
Button first. If it is not handled by the Button, the event is then sent
to the Panel, and if it is not handled there, the event is sent to the
Frame.
What Is an Event?
When the user performs an action at the user interface, this causes an
event to be issued. Events are objects that describe what happened. A
number of different types of event classes exist to describe different
general categories of user action.
Event Sources
An event source (at the user interface level) is the result of some user
action on an AWT component. For example, a mouse click on a button
component will generate (source) an ActionEvent. The ActionEvent
is an object (class) that contains information about the status of the
event:
Event Handlers
When an event occurs, the event is received by the component that the
user interacted with; for example, the button, slider, text field, and so
on. An event handler is a method that receives the event object so that
the program may process the user’s interaction.
Objectives
Upon completion of this module, you will be able to:
● Determine from the event object details about the user action that
originated the event
8-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
7
Exercises
1. Create a GUI that will provide the front-end user interface for the
Teller.java application created in Module 5. You may need to
research some components that are not described in this module
(they are described later).
When the example is run, the resulting display looks like this:
Observe that the North region of the border layout is now effectively
holding two buttons. In fact, it holds only the single panel but that
panel contains the two buttons.
The size and position of the panel is determined by the border layout
manager, the preferred size of a panel is determined from the
preferred size of the components in that panel. The size and position
of the buttons in the panel are controlled by the flow layout that is
associated with the panel by default.
Panels are created using the constructor Panel(). Once a Panel object
is created, it must be added to another container. This is done the same
as before, using the add() method of the container.
Notes
Layout Managers
Layout Managers
CardLayout (Continued)
31 // create a label to attach to each panel, and
32 // change the color of each panel, so they are
33 // easily distinguishable
34
35 l1 = new Label("This is the first Panel");
36 p1.setBackground(Color.yellow);
37
38 l2 = new Label("This is the second Panel");
39 p2.setBackground(Color.green);
40
41 l3 = new Label("This is the third Panel");
42 p3.setBackground(Color.magenta);
43
44 l4 = new Label("This is the fourth Panel");
45 p4.setBackground(Color.white);
46
47 l5 = new Label("This is the fifth Panel");
48 p5.setBackground(Color.cyan);
49
50 // Set up the event handling here ....
51
52 // add each panel to my CardLayout
53 f.add(p1, "First");
54 f.add(p2, "Second");
55 f.add(p3, "Third");
56 f.add(p4, "Fourth");
57 f.add(p5, "Fifth");
58
59 // display the first panel
60 myCard.show(f, "First");
61
62 f.setSize (200, 200);
63 f.setVisible(true);
64 }
Layout Managers
CardLayout (Continued)
A fragment of the code is shown here:
1 import java.awt.*;
2 import java.awt.event.*;
3
4 public class CardTest implements MouseListener {
5
6 Panel p1, p2, p3, p4, p5;
7 Label l1, l2, l3, l4, l5;
8
9 // Declare a CardLayout object,
10 // so I can call its methods
11 CardLayout myCard;
12 Frame f;
13
14 public static void main (String args[]) {
15 CardTest ct = new CardTest ();
16 ct.init();
17 }
18
19 public void init () {
20 f = new Frame ("Card Test");
21 myCard = new CardLayout();
22 f.setLayout(myCard);
23
24 // create the panels that I want
25 // to use as cards
26 p1 = new Panel();
27 p2 = new Panel();
28 p3 = new Panel();
29 p4 = new Panel();
30 p5 = new Panel();
Layout Managers
CardLayout
The CardLayout Manager enables you to treat the interface as a series
of cards, one of which is viewable at any one time. For example, here
is a Frame with five cards. A mouse click in the Panel on the Frame
switches to the next card.
A mouse click in this panel switches the view to this panel and so on.
Layout Managers
Layout Managers
The order in which components are added to the grid determines the
cell that they occupy. Lines of cells are filled left to right, like text, and
the “page” is filled with lines from top to bottom.
Layout Managers
You can only add a single component to each of the five regions of the
border layout manager. If you try to add more than one, only one will
be visible. Later modules show how you can use intermediate
containers to allow more than one component to be laid out in the
space of a single border layout manager region.
Layout Managers
Layout Managers
North occupies the top of a panel, East occupies the right side, and so
on. The Center area represents everything left over once the North,
South, East, and West areas are filled.
Layout Managers
Layout Managers
Unlike other layout managers, the flow layout does not constrain the
size of the components it manages, but instead allows them to have
their preferred size.
Options on a flow layout allow you to flush the components to the left
or to the right if you prefer that to the default centering behavior.
When the area being managed by a flow layout is resized by the user,
the layout could change. For example:
After user or
program resizes
A Simple Example
f.add(b1)
This tells the frame f (which is a container) that it is to contain the
component b1. Buttons are examples of Java components. The size and
position of b1 are under the control of the frame’s layout manager
from this point onward.
f.pack()
This method tells the frame to set a size that “neatly encloses” the
components that it contains. In order to determine what size to set the
frame, f.pack()queries the layout manager, which is responsible for
the size and position of all the components within the frame.
f.setVisible(true)
This method causes the frame, and all its contents, to become visible to
the user.
A Simple Example
f.setLayout(new FlowLayout())
This creates an instance of the flow layout manager, and installs it into
the frame. There is a default layout manager for every frame, but it is
not used for this example. The flow layout manager is the simplest in
the AWT and positions components somewhat like words on a page,
line by line. Note that the flow layout centers each line by default.
A Simple Example
Container Layouts
Layout Managers
The following layout managers are included with the Java language:
● GridLayout
● CardLayout
● GridBagLayout
Panels
Creating Panels
Here is the result:
Panels
Panels, like frames, provide the space for you to attach any GUI
component, including other panels.
Creating Panels
Panels are created using the constructor Panel(). Once a Panel object
is created, it must be added to a Window or Frame object in order to be
visible. This is done using the add() method of the Container class.
Frames
produces:
Frames
A Frame is a subclass of Window. It is a Window with a title and resize
corners.
The program below creates a simple frame with a specific title, size,
and background color:
1 import java.awt.*;
2 public class MyFrame extends Frame {
3 public static void main (String args[]) {
4 MyFrame fr = new MyFrame("Hello Out There!");
5 // Component method setSize()
6 fr.setSize(500,500);
7 fr.setBackground(Color.blue);
8 fr.setVisible(true); // Component method show()
9 }
10 public MyFrame (String str) {
11 super (str);
12 }
13 ...
14 }
Notes
Positioning Components
The position of a component in a container is determined by a layout
manager. A container keeps a reference to a particular instance of a
LayoutManager. When the container needs to position a component it
invokes the layout manager to do so. The same delegation occurs when
deciding the size of a component.
Component Sizing
Because the layout manager is generally responsible for the size and
position of components on its container, you should not normally
attempt to set the size or position of components yourself. If you try to
do so (using any of the methods setLocation(), setSize() or
setBounds()), the layout manager overrides your decision.
setLayout(null);
Note – The fact that a container can hold not only components, but also
other containers is critical and fundamental to building complex layouts.
java.lang.Object BorderLayout
CardLayout
CheckboxGroup
Color
Dimension
Event
Font
FlowLayout
FontMetrics
Graphics
GridBagConstraints
GridBagLayout
GridLayout
Image
Insets
Point
Polygon
Rectangle
Toolkit
MenuComponent MenuBar
MenuItem Menu - Popup Menu
Component CheckboxMenuItem
Button
Canvas
Applet (java.applet package)
Checkbox
Choice
Panel
Container
Window
Label
List Dialog FileDialog
Scrollbar Frame
TextComponent TextArea
TextField
Objectives
Upon completion of this module, you will be able to:
● Describe and use the flow, border, grid and card layout managers
to achieve a desired dynamic layout
7-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
6
Exercises
2. Use the try and catch statements to recover from the exception.
1. Use the bank package you created in the lab from Module 5 and
add the following exceptions:
To throw an exception that you have created, use the syntax below:
throw new ServerTimedOutException(“Could not
connect”, 80);
Example
Consider a client-server program. In the client code, you try to connect to
the server and expect the server to respond within five seconds. If the
server does not respond, your code could throw an exception (such as a
user-defined ServerTimedOutException) as follows:
public void connectMe(String serverName) throws
ServerTimedOutException {
int success;
int portToConnect = 80;
success = open(serverName, portToConnect);
if (success == -1) {
throw new ServerTimedOutException(
“Could not connect”, 80);
}
}
There are two things the programmer can do which satisfy this
requirement: The first is to use a try {} catch (){} block where the
catch names any superclass of the thrown Exception counts as
handling the situation, even if the catch block is empty.
The second thing is to indicate that the exception is not handled in this
method, and that it will therefore be thrown out of this into the calling
method. This is done by marking the method declaration with a
throws clause as follows:
Following the keyword throws is a list of all the exceptions that might
be raised inside the method, but do not have handling in place.
Although only one exception is shown here, a comma-separated list
can be used if there are multiple possible exceptions that are not
handled in the method.
Exceptions
Common Exceptions
The Java language provides several predefined exceptions. The
following are two of the more common exceptions you might
encounter:
● Open a socket other than back to the host that served the
applet, or
Exception Categories
There are three broad categories of exceptions in Java. In fact, Java
defines the class java.lang.Throwable, which acts as the parent class
for all objects that can be thrown and caught using the exception
handling mechanisms. There are three essential subclasses of this,
which are shown in the diagram below:
Throwable
Exception Error
RuntimeException
The Throwable class should not be used; instead, use one of the other
three to describe any particular exception. The purpose of each
exception is described below:
Exception Handling
Example Revisited
The following example is a rewrite of the main() method from page 6-3. The
exception generated in the earlier version of the program is caught and the
array index is reset to 0.
1 public static void main (String args[]) {
2 int i = 0;
3 String greetings [] = {
4 "Hello world!",
5 "No, I mean it!",
6 "HELLO WORLD!!"
7 };
8 while (i < 4) {
9 try {
10 System.out.println (greetings[i]);
11 } catch (ArrayIndexOutOfBoundsException e){
12 System.out.println("Re-setting Index Value");
13 i = -1;
14 } catch (Exception e) {
15 System.out.println(e.toString());
16 } finally {
17 System.out.println("This is always printed");
18 }
19 i++;
20 } // end while()
21 } // end main()
The message displayed on the screen alternates among the following as the
loop is executed:
Hello world!
This is always printed
No, I mean it!
This is always printed
HELLO WORLD!!
This is always printed
Re-setting Index Value
This is always printed
Exception Handling
The Java language has utilities that enable you to figure out what
exception was thrown and then try to recover.
finally Statement
The finally statement defines a block of code that you always want to
have executed, regardless of whether an exception was caught or not.
The following sample code and description is taken from the white
paper by Frank Yellin, “Low Level Security in Java”:
try {
startFaucet();
waterLawn();
}
finally {
stopFaucet();
}
For example, the Java language guarantees that the faucet is turned off
even if an exception occurs while starting the faucet or watering the
lawn. The code inside the brackets after the try is called the protected
code.
The only time the finally statement would not be executed is if the
System.exit() method gets executed within the protected code. The
program then terminates immediately.
Exception Handling
Exception Example
Consider a simple extension of the version of the HelloWorld.java
program (which cycles through messages) created in the lab:
1 public class HelloWorld {
2 public static void main (String args[]) {
3 int i = 0;
4
5 String greetings [] = {
6 "Hello world!",
7 "No, I mean it!",
8 "HELLO WORLD!!"
9 };
10
11 while (i < 4) {
12 System.out.println (greetings[i]);
13 i++;
14 }
15 }
16 }
Exceptions
Objectives
Upon completion of this module, you will be able to:
● Define exceptions
6-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
5
Exercises
1. Modify the Level 1 lab so you can subclass the Account for the
specifics of a CheckingAccount class.
Grouping Classes
The directory abc that forms the base of this hierarchy must be located
somewhere on the CLASSPATH.
CLASSPATH has not been used before since if the variable is not set at
all, the default behavior of the tools automatically includes the
standard location of the distribution classes and the current working
directory. If you want to access packages that are located in other
places, you must set the CLASSPATH variable explicitly.
The Java compiler will both create the package directory and move
the compiled class file to it when the -d option is used.
% javac -d /home/anton/mypackages Employee.java
Grouping Classes
Grouping Classes
Packages
Java provides the package mechanism as a way to group together
related classes. So far, all of these examples have belonged to the
default or unnamed package.
When you use a package declaration you do not need to import the
same package or any element of that package. Remember that the
import statement is used to bring classes in other packages into the
current namespace. The current package, whether explicit or implicit,
is always part of the current namespace.
Overriding Methods
Overriding Methods
Overriding Methods
As well as being able to take an existing class and produce a new one
based on the old, adding additional features, it is possible to modify
existing behavior of the parent class.
If a method is defined in a new class such that the name, return type,
and argument list exactly matches those of a method in the parent
class, then the new method is said to override the old one.
Note – Remember that the same name but different argument list is
simply overloading, and it causes the compiler to look at the supplied
arguments to decide which method to call.
Subclassing
Casting Objects
In circumstances where you have received a reference to a parent class,
and you have determined that the object is actually a particular
subclass by using instanceof operator, you can restore the full
functionality of the object by casting the reference.
public void method(Employee e) {
if (e instanceof Manager) {
Manager m = (Manager)e;
System.out.println(“This is the manager of ” +
m.department);
}
// rest of operation
}
If you do not make the test using instanceof, you run the risk of the
cast failing. Generally any attempt to cast an object reference is
subjected to several checks:
● Casts “up” the class hierarchy are always legal, and in fact do not
require the cast operator, they can be done by simple assignment.
● For “downward” casts, the compiler must be satisfied that the cast
is at least possible. For example, any attempt to cast a Manager
reference to a Contractor reference is definitely illegal, since the
Contractor is not a Manager. The class to which the cast is taking
place must be some subclass of the current reference type.
● If the compiler allowed the cast, then the reference type is checked
at runtime. For example, if it turns out that the instanceof check
was omitted from the source, the object being cast was not in fact
an object of the type it is being cast to, then an Exception occurs.
Exceptions are a form of runtime error, and are the subject of a
later module.
Subclassing
Subclassing
Using this approach you can write methods that accept a “generic”
object, in this case an Employee, and work properly on any subclass of
that. Hence you might produce a method in an application class that
takes an employee and compares it with a certain threshold salary to
determine the tax liability of that employee. Using the polymorphic
facilities, you can do this quite simply:
public TaxRate findTaxRate(Employee e) {
// do calculations and return a tax rate for e
}
// Meanwhile, elsewhere in the application class
Manager m = new Manager();
:
TaxRate t = findTaxRate(m);
You can even write a sort method that puts the employees into age or
salary order without having to worry that some are actually managers.
Subclassing
Polymorphism
Describing a Manager as an Employee is not just a convenient way of
describing the relationship between these two classes. Recall that the
Manager gets all the attributes, both members and methods, of the
parent class Employee. This means that any operation that is
legitimate on an Employee is also legitimate on a Manager. If the
Employee has methods raiseSalary() and fire(), then the
Manager class does also.
This leads to the idea that objects are polymorphic, that is they have
“many forms.” A particular object can have the form of a Manager, but
it also has the form of an Employee. It turns out that, in Java, there is
one class which is a parent class for all others. This is the
java.lang.Object class. So, in effect, our earlier definitions were
shorthands for:
public class Employee extends Object
and
public class Manager extends Employee
Using the variable e as is, you can only access the parts of the object
that are part of an Employee, the Manager specific parts are hidden.
This is because as far as the compiler is concerned, e is an Employee,
not a Manager. Therefore, the following is illegal:
e.department = “Finance”; // illegal
Subclassing
Single Inheritance
Java only allows a class to extend one other class. This restriction is
called single inheritance. The debate over the relative merits of single
and multiple inheritance is the subject of extensive discussions among
object-oriented programmers. Java imposes the single inheritance
restriction because it is considered to make the resulting code more
reliable, although this sometimes makes more work for the
programmer. Module 11 examines a facility called interfaces that
allows some of the benefits of multiple inheritance.
There are only two ways that a class can gain a constructor, either you
write the constructor, or, because you have written no constructors at
all, the class has a single default constructor.
Subclassing
Subclassing
So, a way is needed to create a new class from an existing class; this is
called subclassing.
The default constructor enables you to create object instances with new
Xxx(), otherwise you would be required to provide a constructor for
every class.
Constructors
The explicit initialization mechanism just described provides a simple
way to set the starting values of fields in an object. Sometimes,
however, you actually need to execute a method to perform the
initialization. You may need to handle possible errors. You may want
to use loops or conditionals to determine the initialization. You may
want to also pass arguments into the construction process so that the
code that requests the construction of the new object can control the
object it creates. One example is objects like buttons, which need a text
string to act as the label.
You have seen how you must execute a call to new xxx() in order to
allocate space for a new object. You have also seen that sometimes
arguments can be placed in the parenthesis, for example, new
Button(“Press me”). Calling the constructor causes the following
things to happen:
1. First, the space for the new object is allocated and the default
initialized. In Java, this phase is indivisible to ensure that you
cannot have an object with random values in it.
Now suppose that you need a different print method for printing each
of the int, float, and String types. This is reasonable, since the
different data types will require different formatting, and probably
varied handling. You could create three methods, called printint(),
printfloat(), and printString(), respectively. However, this is
tedious.
Java, along with several other languages, allows you to reuse a method
name for more than one method. Clearly this can only work if there is
something in the circumstances under which the call is made that will
distinguish which method is actually needed. In the case of the three
print methods, it is possible to make this distinction on the basis of the
arguments.
By reusing the method name, you end up with the following methods:
public void print(int i)
public void print(float f)
public void print(String s)
When you write code to call one of these methods, the appropriate one
is chosen according to the type of argument or arguments you supply.
Encapsulation
In addition to protecting the data of an object from improper
modification, forcing the user to access the data through a method
enables a class to be reused more simply by ensuring that required
side effects are properly handled. In the case of the Date class, for
example, consider how the tomorrow method should be constructed.
If the data were entirely accessible, each user of the class would have
to increment the day value, test it against the number of days in the
current month, and handle month end (and possibly year end)
conditions. This is tedious and error prone. Although these needs are
well understood for dates, other data types might have similar
constraints that are not well known. By forcing the user of the class to
use the supplied tomorrow() method, everyone can be assured that
the necessary side effects will be handled consistently and correctly
every time.
The method checks to see if the day that it has been asked to set is in
fact valid. If it is not, it ignores the request and prints a message. You
will see later that Java provides a much more effective mechanism for
handling out-of-range method arguments. For now, however, you can
see that this Date class is effectively protected against overvalue dates.
Rules about how a method can properly be called (such as, “the value
of the argument must be within the valid range of day numbers for the
month in the object”) are called preconditions. Careful use of
precondition tests can make a class much easier to reuse, and much
more reliable in reuse, since the programmer using the class will find
out immediately if any method has been misused.
Data Hiding
Using the private keyword in the declaration of day, month, and
year in the Date class has the effect of making it impossible to access
these members from any code except methods in the Date class itself.
So given declaration for the Date class, the following code is illegal:
public class DateUser {
public static void main(String args[]) {
Date mydate = new Date();
mydate.day = 21; // illegal!
}
}
Preventing access to the data variables directly may seem odd, but it
actually has great advantages for the quality of the program that uses
the Date class. Since the individual items of data are inaccessible, the
only way to read or write to them is through methods. So if your
program requires internal consistency of the members of the class, this
can be managed by the methods of the class itself.
Consider a Date class that allows arbitrary access to its members from
outside. It would be very easy for code to do any of the following:
Date d = new Date();
d.day = 32; // invalid day
d.month = 2; d.day = 30; // plausible but wrong
d.month = d.month + 1; // omit check for wrap round
There are occasions when the keyword this is not redundant. For
example, you might want to call a method in some entirely separate
class and pass a reference to the instance of the object as an argument.
For example:
Birthday bDay = new Birthday (this);
Pass-by-value (Continued)
33 // What is the current value?
34 System.out.println (“Int value is: “ + val);
35
36 // Assign the string
37 str = new String (“hello”);
38
39 // Try to change it
40 pt.changeStr (val);
41
42 // What is the current value?
43 System.out.println (“Str value is: “ + str);
44
45 // Now set the ptValue
46 pt.ptValue = 101f;
47
48 // Now change the value of the float
49 // through the object reference
50 pt.changeObjValue (pt);
51
52 // What is the current value?
53 System.out.println (“Current ptValue is: “ +
54 pt.ptValue);
55 }
56 }
Pass-by-value
Java only passes arguments “by-value”; that is, the argument may not
be changed by the method called. When an object instance is passed as
an argument to a method, the value of the argument is a reference to
the object. The contents of the object may be changed in the called
method, but the object reference is never changed.
Defining Methods
Java uses an approach that is very similar to other languages,
particularly C and C++ to define methods. The declaration takes the
following form:
<modifiers> <return_type> <name> ( <argument_list> )
<block>
The <name> can be any legal identifier, with some restrictions based
on the names that are already in use.
Languages like Java that do support abstract data types create a tighter
association between the data and the code. In Java, a method does not
operate on a piece of data. One way to think of it is that the data
modifies its own members. Data performs an operation on itself as
follows:
Date d = ?????;// Some initialized date object
d.tomorrow();
This notation reflects the idea that the behavior is carried out by the
data rather than the other way around. Recall that you can refer to the
fields of the Date class by using the dot notation:
d.day
and that this meant “the day field of the Date object referred to by the
variable d.” Thus, the previous example reads “the tomorrow behavior
of the Date object referred to by the variable d.” In other words, do the
tomorrow operation on the d object.
The idea that methods are a property of the data rather than separate
is a key step on the way to building an object-oriented system. You
will sometimes hear the term message passing. This is used in some
languages to convey the notion of instructing a data item to do
something to itself. In fact, in languages that conventionally use this
terminology, message passing often reflects the nature of the
implementation as well.
When data items are composed into aggregate data types, such as a
date, you can define a number of program pieces or methods that
operate specifically on that type of data. When a programming
language defines a primitive type such as an integer, it also defines a
number of operations (such as add, subtract, multiply, and divide) that
it can perform on instances of that type.
In Java, you can create an association between the date type and the
tomorrow operation as follows:
public class Date {
private int day, month, year;
public void tomorrow() {
// code to increment day
}
}
In Java you can refer to the piece of code named tomorrow as a method,
although you will also hear the terms member function and function.
Note – Do not worry about the meaning of the word private in this
declaration, it will be described later.
Objectives
Upon completion of this module, you will be able to:
5-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
4
Exercises
2. Allow the user to see the word anagrams and take up to five
guesses to unscramble each.
Exercises
2. Create an array of element type int. The array should have four
elements and be assigned to element [0] of the variable, twoD.
3. Write two nested for() loops that print out all the values of
twoD. Arrange the output in a matrix format. (The
System.out.print() method will be helpful here.)
4. Compile and run the program. You should find that it generates a
null pointer exception since the elements [1] to [3] of twoD are
uninitialized.
6. Compile and run the program. This time you should see a non-
rectangular layout of zero values.
8. Create an array that will hold four arrays of int. Then, create an
array of int that will hold four elements, and assign the reference
to this array to the first element of array twoD.
9. Compile and run the program. Observe that the individual arrays
shown by printing the values in oneD are the same as the elements
of the array in twoD.
Arrays 4-11
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
4
Exercises
15. Compile and run the program. Were you right about the values
shown? If not, do you understand what has happened and what
you misunderstood?
17. Compile and run the program. Are the values as you expected?
Exercises
3. Use a for() loop to print out all the values of thisArray. How
do you control the limit on the loop?
4. Compile and run the program. How many values are printed?
What are the values?
8. Compile and run the program. How many values are displayed
for thatArray? What are these values and where do they come
from?
10. Compile and run the program. What do you notice about the
values of thatArray?
11. Create an array of 20 int values. Assign the reference of the new
array to the variable thatArray. Print out the values of both
arrays.
12. Compile and run the program. How many values are shown for
each of the arrays? What are those values?
Arrays 4-9
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
4
Copying Arrays
Once created, an array cannot be resized. However, you can use the
same reference variable to refer to an entirely new array:
int elements[] = new int[6];
elements = new int[10];
In such a case the first array is effectively lost unless some other
reference to it is retained elsewhere.
Array Bounds
Arrays 4-7
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
4
Multi-dimensional Arrays
The object that is created by the call to new is an array. The array
contains four elements. Each of these elements is a null reference to
an element of type array of int. Hence each of the four elements
must be constructed separately. Each of those elements is an array of
int.
Initializing Arrays
This shorthand can be used for any element type while requiring a
reference to each element at each position in the initializing block. For
example:
Color palette[] = {
Color.blue,
Color.red,
Color.white
};
Arrays 4-5
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
4
Initializing Arrays
Java allows a shorthand that will create arrays with initial values:
String names[] = {
"Georgianna",
"Jen",
"Simon",
"Tom"
};
Creating Arrays
You create arrays, like all objects, using the new keyword:
s = new char[20];
p = new Point[100];
The first line creates an array of 20 char values. The second line
creates an array of 100 variables of type Point. It does not, however,
create 100 Point objects. These must be created separately and
individually, for example, as follows:
p[0] = new Point();
p[1] = new Point();
.
.
.
Note – There are more elegant ways to initialize arrays, which will be
introduced shortly.
Arrays 4-3
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
4
Declaring Arrays
The format shown above, with square brackets after the variable name,
is standard for C, C++, and Java. This format leads to complex forms
of declaration that can be quite difficult to read. Therefore, Java allows
an alternative form with the square brackets on the left:
char [] s;
Point [] p;
The result is that you can consider a declaration as having the type
part at the left, and the variable name at the right. You will see both
formats used, but should decide on one or the other for your own use.
Objectives
Upon completion of this module, you will be able to:
● State the need to, and be able to, initialize the elements of an array
4-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
3
Exercises
1. For any given right triangle, the length of the hypotenuse (the
longest side) is given by the formula:
c
b
c= a 2 + b2
a
Flow Control
● break [label];
● continue [label];
Examples
Flow Control
do Loops
Example
1 int i = 0;
2 do {
3 System.out.println("Are you finished yet?");
4 i++;
5 } while (i < 10);
6 System.out.println("Finally!");
Flow Control
Looping Statements
for Loops
Example
while Loops
Example
1 int i = 0;
2 while (i < 10) {
3 System.out.println("Are you finished yet?");
4 i++;
5 }
6 System.out.println("Finally!");
Flow Control
switch Statement
Note – You can only switch on short, int, byte or char data types.
Example
1 switch (colorNum) {
2 case 0:
3 setBackground(Color.red);
4 break;
5 case 1:
6 setBackground(Color.green);
7 break;
8 default:
9 setBackground(Color.black);
10 break;
11 }
Flow Control
Branching Statements
Example
1 int count;
2 count = getCount();// a method defined in the program
3 if (count < 0) {
4 System.out.println("Error: count value is negative!");
5 }
6 else {
7 System.out.println("There will be " + count +
8 " people for lunch today.");
9 }
Note – .
Expressions
Casting
Where values are not assignment compatible, a cast can sometimes be
used to persuade the compiler to recognize an assignment. This can be
done, for example, to “squeeze” a long value into an int variable.
Explicit casting is done like this:
long bigValue = 99L;
int squashed = (int)(bigValue);
Observe that the desired target type is placed in parentheses and used
as a prefix to the expression that must be modified. It may not be
necessary, (but is generally advisable), to enclose the entire expression
to be cast in parentheses. This is because the precedence of the cast
operation can cause problems otherwise.
Note – Recall that the range of short is -215 to 215 -1, and the range of
char is 0 to 216 -1. Hence, assignment between short and char always
requires an explicit cast.
Expressions
The familiar operator >> performs an arithmetic right shift. The result
of this shift is that the first operand is divided by two raised to the
number of times specified by the second operand. For example:
128 >> 1 gives 128/21 = 64
256 >> 4 gives 256/24 = 16
-256 >> 4 gives -256/24 = -16
The logical or unsigned right shift operator >>> works on the bit pattern
rather than the arithmetic meaning of a value and always places zeros
in the most significant bits. For example:
1010 ... >> 2 gives 111010 ...
1010 ... >>> 2 gives 001010 ...
Expressions
Expressions
Logical Expressions
Most Java operators are taken from other languages and behave as
expected.
Expressions
Operators
The Java operators are very similar in style and function to those of C
and C++. The following table lists the operators in order of precedence
(“L to R” means left-to-right associative; “R to L” means right-to-left
associative):
Separator . [] () ; ,
R to L ++ -- + - ~ ! (data type)
L to R * / %
L to R + -
L to R << >> >>>
L to R < > <= >= instanceof
L to R == !=
L to R &
L to R ^
L to R |
L to R &&
L to R ||
R to L ?:
R to L = *= /= %= += -= <<=
>>= >>>= &= ^= |=
Expressions
Variable Initialization
No variable in a Java program is permitted to have an undefined
value. When an object is created, member variables are initialized with
the following values at the time the storage is allocated:
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000' (NULL)
boolean false
All reference types null
Expressions
Variables defined inside a method (you will see later that main() is
not the only method you can define) are called automatic, local,
temporary, or stack variables depending on the preference of the
speaker.
Member variables are created when the object is constructed using the
new Xxxx() call. These variables continue to exist for as long as the
object is needed.
Note – Part of the Java system called the “automatic garbage collector”
destroys objects that are no longer needed. This generally happens
without the programmer’s intervention.
Objectives
Upon completion of this module, you will be able to:
3-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
2
Notes
Exercises
Using the Point class you created in the previous exercise, add code
to the main() method to do the following:
2. Print out the values of the x and y members for both end and
stray variables.
4. Print out the values of the members of both end and stray.
Compile and run the Point class. The values reported by end
reflect the change made in stray, indicating that both variables
refer to the same Point object.
6. Print out the values of the members of both start and end.
Compile and run the Point class again. This time the values of
start are independent of those in stray and end, indicating that
the start variable still refers to a Point object that is different
from the one referred to by stray and end.
Exercises
2. Write a main() method inside your class; below that, declare two
variables of type Point. Call the variables start and end. Create
the objects using new Point() and assign the reference values
into the variables.
3. Assign the x and y members of the object start the value 10.
4. Assign the x value of the end object the value 20, and the y value
of the end object the value 30.
To display numbers, you can use the following form (which will
be described later in this course):
System.out.println(“Start Point = X: " + start.x + "
Y: " + start.y);
Note – The plus symbol (+) converts one operand into a String if the
other is already a String.
Understanding Objects
Terminology Recap
Quite a few terms have been introduced in this module. This section
reviews them briefly.
Aggregate Data Type
A name for a programmer’s model of something. The model is built
by putting variables that specify the state of the entity into a single
definition. Once defined, variables can be created using the type name.
Some languages use the terms record or structured type instead. Java
uses the term Class.
Class
An object-oriented language’s version of an aggregate data type.
Strictly speaking, the idea of a class is a superset of the idea of a
aggregate data type, but the many additional features that make it a
class rather than aggregate data type have not yet been discussed.
Object
An actual instance of a class. The class can be considered as a
template – a model of the object you are describing. An object is what
you get each time you create an instance of a class.
Member
A member is one of the elements that make up an object. The term is
also used for the elements of the defining class. The terms member
variable, instance variable, and field are also used interchangeably.
Reference
In Java, a variable that is defined as having a class type does not
actually keep track of the object data; rather, the variable is a means of
identifying a particular object. This type of variable is called a
reference.
Understanding Objects
In Java, a value of null indicates that the reference does not refer to
any object. This allows the runtime system to detect the use of such a
reference and stops access immediately, cleanly, and platform
independently, without allowing any damage to occur. More details of
this behavior will be presented later.
C and C++ programmers should take care that in Java the literal null
is lowercase, unlike its counterpart in those languages.
Understanding Objects
Four variables are created: two int types and two references to
String. The value of x is seven, and this value is copied into y. Both
x and y are independent variables and further changes to either do not
affect the other.
With the variables s and t, only one String object exists and it
contains the text “Hello”. Both s and t refer to that single object.
x 7 “Hello”
y 7
s 0x01234567
t 0x01234567
Understanding Objects
today ????
today ????
day 0
month 0
year 0
today 0x01abcdef
day 0
month 0
year 0
Understanding Objects
Creating an Object
When variables of any primitive type, that is, any of boolean, byte,
short, char, int, long, float, or double types, are declared, the
memory space is allocated as part of the operation. The declaration of
a variable using a class type such as String or any user-defined type
does not allocate memory space for the object.
In fact, a variable that is declared with a class type is not the data itself,
but rather it is a reference to the data.
Before you can use the variable, the actual storage must be allocated.
This is done by using the keyword new like this:
Date mybirth;
mybirth = new Date();
The first statement, the declaration, allocates just enough space for the
reference. The second statement allocates the space for the three
integers used to form the Date. The assignment sets up the variable
mybirth to correctly refer to the new object. After these two
operations have been performed, you can manipulate the components
of the date type.
Understanding Objects
Each of the elements that make up a class (day, month, and year for
the class date) are called member variables, rather than fields, in
object-oriented terminology. Since Java is an object-oriented language,
the term member variable or simply member will be used.
Understanding Objects
The word class is part of the Java language and must be written
entirely in lowercase. The name Date is written with a capital first
letter by convention rather than language requirement.
Note – A class is much more than just a aggregate data type; these
issues will be addressed later in this course.
A variable can be declared as being of type Date, and the day, month,
and year parts will be implied by this declaration. For example:
Date mybirth, yourbirth;
Using this declaration, Java allows the parts (day, month and year) of
the variables to be accessed using the dot (.) operator. For example:
mybirth.day = 26;
mybirth.month = 11;
yourbirth.year = 1960;
Understanding Objects
Understanding Objects
In the Beginning
Early programming languages and novice programmers tend to treat
variables as isolated things. For example, if a program needs to handle
a date, three separate integers would be declared:
int day, month, year;
This statement does two things. It says that when the programs refers
to day, month, or year it will be manipulating an integer. It also
allocates the storage for those integers.
Other Conventions
Control structures – Use brackets ({ }) around all statements, even single
statements, when they are part of a control structure such as an
if-else or for statement.
if ( condition )
{
do something
}
else { do something else }
Spacing – Place only a single statement on any line, and use four-space
indentations, to make your code readable.
Classes – Class names should be nouns, in mixed case, and with the
first letter of each word capitalized.
class AccountBook
Methods – Method names should be verbs, in mixed case, with the first
letter in lowercase. Within each method name, capital letters separate
words. Limit the use of underscores in method names.
balanceAccount()
32 bits float
64 bits double
Integral literals are of int type unless explicitly followed by the letter
“L”. The L indicates a long value. Note that it is valid Java to use
either an upper- or lowercase L, but lowercase is a poor choice since it
is indistinguishable from the digit one, in most circumstances. Long
versions of the literals shown above are:
2L The decimal value two, as a long.
077L The leading zero indicates an octal value
0xBARNL The 0x prefix indicates a hexadecimal value.
The size and range for the four integral types are shown below. The
range representation is defined by the Java language specification as a
two’s complement and is platform independent.
Java defines eight primitive data types and one special type. These may
be used as literal values, or in variables. The types may be considered
in four categories: logical, textual, integral, and floating point.
Logical – boolean
Logical values have two states. These are often thought of as “on” and
“off,” “true” and “false,” or “yes” and “no.” In Java such a value is
represented by the boolean type. The boolean has two literal values:
true and false.
Note – There are no casts between integer types and the boolean type.
Some languages, most notably C and C++, allow numeric values to be
interpreted as logical values. This is not permitted in Java, and
wherever a boolean is required only the boolean type can be used.
Keywords
Java Keywords
Note – In Java, the literals true, false, and null are lowercase, not
uppercase as in the C++ language. Strictly speaking, these are not
keywords but literals. The distinction is academic, however.
Note – goto and const are keywords that are not used in Java.
Identifiers
● identifier
● userName
● User_name
● _sys_var1
● $change
Identifiers may contain, but must not actually be, keywords. For
example, thisOne is a valid identifier, but this is not, because it is a
Java keyword. Java keywords are discussed next.
Comments
Note – The format of these comments and the use of the javadoc tool
is discussed in the docs/tooldocs/solaris or
docs/tooldocs/win32 directories of the API documentation for JDK
1.1.
Objectives
Upon completion of this module, you will be able to:
2-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
1
Exercises
1. Your instructor will give you instructions on how to start the API
browser and open the index page to the Java API on-line
documents.
3. What classes are defined by this package? What are some methods
in the System class? What package is the System.out.println
method defined in?
1. Write an application called MyCat that will read a line from the
stdin and write the line back out to stdout. Both stdin and
stdout are in the java.lang.System class.
● A list of constructors
● A list of methods
The JDK comes with a set of HTML files which document the API that
is provided by the supplied packages. The layout of this
documentation is hierarchical, so that the home page lists all the
packages as hotlinks. If a particular package is selected, the page will
list all the classes that are members of that package. Each class is
shown as a hotlink, and selecting that link will present a page of
information about that class.
Each class document has the same format, although some aspects
might be omitted if they are not relevant to a particular class.
Runtime Errors
● Naming
If .java file contains a public class, then it must take its file name
from that class.
● Class Count
● Layout
These items must appear in this order. That is, any import statements
must precede all class declarations and if a package declaration is
used, it must precede both the classes and imports.
Compile-Time Errors
The following are common errors seen at compile time:
● HelloWorldApp.java:3: Method
printl(java.lang.String) not found in class
java.io.PrintStream.
System.out.printl ("Hello World!");
^
This error occurs because either the word static or public was
left out of the line containing the main method.
Runtime Errors
● Can't find class HelloWorldApp
Generally, this means that the class name was spelled differently
from the source file name, and a filename.class file was created
with the spelling (including case) of the class definition.
For example,
class HelloWorldapp {
Compiling
Once you have created the HelloWorldApp.java source file, compile
it with the following line:
$ javac HelloWorldApp.java
If the compiler does not return any messages, the new file
HelloWorldApp.class is stored in the same directory as the source
file.
Running
To run your HelloWorldApp application, use the Java interpreter,
java, located in the bin directory.
$ java HelloWorldApp
Hello World!
The above line illustrates the use of a class name, an object name, and
a method call. It prints the string “Hello World!” to the standard
output.
The println method takes a string argument and writes it out to the
standard output stream.
Finally, the last two lines of the program, the two braces, close the
method, main, and the class HelloWorldApp.
7 }
8 }
HelloWorldApp Described
The first three lines in the program are comment lines:
1 //
2 // Sample HelloWorld application
3 //
The next line declares the class name as HelloWorldApp. The class
name specified in the source file creates a classname.class file in the
directory where you compile the application. In this case, the compiler
creates a file called HelloWorldApp.class.
4 public class HelloWorldApp{
The next line in the program is where the execution of the program
starts. The Java interpreter must find this defined exactly as given or it
will refuse to run the program.
If the program is given any arguments on its command line, these are
passed into the main() method, in an array of strings called args. In
this example, no arguments are expected.
HelloWorldApp
1 //
2 // Sample HelloWorld application
3 //
4 public class HelloWorldApp{
5 public static void main (String args[]) {
6 System.out.println ("Hello World!");
7 }
8 }
What Is Java?
Note – All class files imported across the network pass through the
byte code verifier.
Verification Process
The byte code verifier makes four passes on the code in a program. It
ensures that the code adheres to the JVM specifications and does not
violate system integrity. If the verifier completes all four passes
without returning an error message, then the following is ensured:
What Is Java?
A Java interpreter must run code compiled for the JVM. A Java
interpreter has three main tasks:
Class Loader
The Class Loader loads all classes needed for execution of a program.
The Class Loader adds security by separating the namespaces for the
classes of the local file system and those imported from network
sources. This limits any “Trojan-horse” application because built-in
classes are always loaded first.
Once all of the classes have been loaded, the memory layout of the
executable file is determined. At this point specific memory addresses
are assigned to symbolic references and the lookup table is created.
Because memory layout occurs at runtime a Java interpreter adds
protection against illegal addressing of code that attempts to gain
unauthorized access into the operating system.
What Is Java?
Code Security
The figure below illustrates the Java program environment. This figure
will be featured in the following discussion on how Java enforces code
security.
Compile Runtime
Class
Loader
Byte Code
javac Hello.java network Verifier
Hello.class Interpreter
JIT
Code
Runtime Generator
hardware
Java files are “compiled” in the sense that they are converted from the
text format in which programmers write them into a machine-
independent set of byte codes.
At runtime the byte codes that make up a Java program are loaded,
checked, and then run in an interpreter. The interpreter has two jobs: it
executes Java byte code, and makes the appropriate calls through a
system runtime to the underlying hardware.
What Is Java?
Garbage Collection
Many programming languages allow the dynamic allocation of
memory at runtime. The process of allocating memory varies based
upon the syntax of the language, but always involves returning a
pointer to the starting address of the memory block.
What Is Java?
● Register set
● Stack
● Garbage-collected heap
● Memory area
The code format of the JVM consists of compact and efficient byte
codes. Programs represented by JVM byte codes must maintain proper
type discipline. The majority of Java type checking is done at compile
time.
Any compliant Java interpreter must be able to run any program with
class files that conform to the class file format specified in The Java
Virtual Machine Specification.
What Is Java?
● Garbage collection
● Code security
What Is Java?
Java is:
● A programming language
● A development environment
● An application environment
Java is the result of the search for a programming language that would
provide the power of C++ with the security of a type-safe language
like SmallTalk.
Objectives
Upon completion of this module, you will be able to:
References
The Java Virtual Machine Specification, Lindholm and Yellin, Addison-
Wesley, 1997.
1-1
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
Notes
Typeface or
Meaning Example
Symbol
xx Java Programming
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
Course Content
This module explains the Java classes available for reading and
writing both data and text files, and introduces the new
Serialization Application Programming Interfaces (API).
● Module 13 – Threads
● Module 4 – Arrays
All graphical user interfaces in Java are built upon the concept of
Frames and Panels. This module introduces layout management
and containers.
● Create and use the Java GUI components: panels, buttons, labels,
canvases, lists, scrollbars, text fields, and text areas
● Create standalone Java applications, and use the Frame and Menu
classes to add graphics to Java applications
● Use the File I/O class libraries to read and write to and from data
and text files
or have
One difference between the Solaris port of the Java Developer’s Kit
(JDK)™ and the Windows 95/NT port is the environment variables
setup. When using Windows 95/NT JDK, set up the environment
variables in the autoexec.bat file, using semicolons instead of colons.
The entries should look like this:
set JAVA_HOME=c:\java
set CLASSPATH=.;c:\some_package_directory
set PATH=%PATH%;%JAVA_HOME%\bin
Overview
This course discusses some of the advanced features and the
application programming interface (API) of the Java™ programming
language.
The audience for this course includes Java document publishers and
others familiar with implementing elementary programming concepts
using Java or other languages. This is the follow-up course to
Programming For Beginners Using Java (SL-110).
xiii
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
Vector...........................................................................................................C-1
The Vector Class ............................................................................. C-2
Synopsis.....................................................................................C-2
Constructors..............................................................................C-2
Variables....................................................................................C-3
Methods.....................................................................................C-3
Sample Vector Template .........................................................C-5
The Vector Class ............................................................................. C-6
The Vector Lab Exercise .................................................................. C-7
Event 1.0.x to Event 1.1 Conversion .......................................................D-1
Event Handling ................................................................................ D-2
Event Handling Before JDK 1.1..............................................D-2
Event Handling in JDK 1.1 .....................................................D-2
Converting 1.0 Event Handling to 1.1........................................... D-3
Making a Component a Listener ................................................... D-6
xi
Copyright 1997 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
SyncStack Class ........................................................................... 13-34
Exercises ......................................................................................... 13-37
Networking With Java ............................................................................14-1
Networking With Java.................................................................... 14-2
Sockets ......................................................................................14-2
Setting up the Connection .....................................................14-2
Addressing the Connection ...................................................14-3
Port Numbers ..........................................................................14-3
Java Networking Model.........................................................14-4
Notes ................................................................................................. 14-5
Minimal TCP/IP Server ................................................................. 14-6
Minimal TCP/IP Client.................................................................. 14-7
UDP Sockets..................................................................................... 14-8
DatagramPacket.....................................................................14-8
DatagramSocket.....................................................................14-9
Exercises ......................................................................................... 14-10
GridBagLayout Manager .........................................................................A-1
GridBagLayout Manager ............................................................... A-2
GridBagLayout Functionality ...............................................A-3
Utilizing GridBagConstraints ............................................A-4
GridBagConstraints Instance Variables.................................... A-5
gridx and gridy......................................................................A-5
gridwidth and gridheight..................................................A-5
fill............................................................................................A-5
ipadx and ipady......................................................................A-6
insets .......................................................................................A-6
anchor .......................................................................................A-6
weightx and weighty.............................................................A-6
GridBagConstraints Examples................................................... A-7
Native Method Integration ..................................................................... B-1
Native Methods................................................................................ B-2
Native HelloWorld.......................................................................... B-3
Defining Native Methods ....................................................... B-3
Calling Native Methods .................................................................. B-5
The javah Utility .................................................................... B-5
Coding C Functions for Native Methods ..................................... B-6
Putting It Together........................................................................... B-8
Passing Information to a Native Method ..................................... B-9
Passing an Argument .............................................................. B-9
Accessing Object Data Members ......................................... B-10
Accessing Strings ................................................................... B-11
x Server Administration
Copyright 1997 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
Readers and Writers ....................................................................... 12-9
Unicode.....................................................................................12-9
Byte and Character Conversions ..........................................12-9
The Buffered Reader and Writer...........................................12-9
Reading String Input ............................................................12-10
Using Other Character Conversions ..................................12-10
Files ................................................................................................. 12-11
Creating a New File Object..................................................12-11
File Tests and Utilities .................................................................. 12-12
Random Access Files .................................................................... 12-13
Creating a Random Access File...........................................12-13
Accessing Information..........................................................12-13
Appending Information.......................................................12-14
Serializable ..................................................................................... 12-15
Object Graphs ........................................................................12-15
Writing and Reading an Object Stream ..................................... 12-17
Reading...................................................................................12-18
Exercises ......................................................................................... 12-19
Threads.......................................................................................................13-1
Threads and Threading in Java..................................................... 13-2
What Are Threads? .................................................................13-2
Three Parts of a Thread ..........................................................13-3
Creating the Thread................................................................13-4
Starting the Thread .................................................................13-6
Thread Scheduling ..................................................................13-7
Basic Control of Threads ................................................................ 13-9
Terminating a Thread.............................................................13-9
Testing a Thread....................................................................13-10
Putting Threads on Hold .....................................................13-10
Other Ways to Create Threads.................................................... 13-13
Which to Use? ........................................................................13-14
Introduction ...........................................................................13-15
The Problem...........................................................................13-15
The Object Lock Flag ............................................................13-18
Releasing the Lock Flag........................................................13-21
Putting It Together................................................................13-22
Deadlock.................................................................................13-23
Thread Interaction – wait() and notify()............................. 13-24
Introduction ...........................................................................13-24
The Problem...........................................................................13-24
The Solution ...........................................................................13-25
Putting It Together........................................................................ 13-28
Producer .................................................................................13-29
Consumer ...............................................................................13-30
SyncStack Class ...................................................................13-31
ix
Copyright 1997 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
A Simple Image Test..................................................................... 10-19
Audio Clips .................................................................................... 10-20
Playing a Clip ........................................................................10-20
A Simple Audio Test .................................................................... 10-21
Looping an Audio Clip ................................................................ 10-22
Loading an Audio Clip.........................................................10-22
Playing an Audio Clip..........................................................10-22
Stopping an Audio Clip .......................................................10-22
A Simple Looping Test................................................................. 10-23
Mouse Input................................................................................... 10-24
A Simple Mouse Test.................................................................... 10-25
Reading Parameters...................................................................... 10-26
Applet/Application..............................................................10-27
Exercises ......................................................................................... 10-29
Advanced Language Features ................................................................11-1
Invoking Overridden Methods ..................................................... 11-2
Rules About Overridden Methods ............................................... 11-3
Invoking Overloaded Constructors.............................................. 11-4
Invoking Parent Class Constructors............................................. 11-5
Class Variables ................................................................................ 11-6
Class Methods ................................................................................. 11-7
The final keyword........................................................................ 11-8
Final Classes.............................................................................11-8
Final Methods ..........................................................................11-8
Final Variables .........................................................................11-8
Abstract Classes............................................................................... 11-9
Interfaces ........................................................................................ 11-10
Advanced Access Control............................................................ 11-11
Deprecation.................................................................................... 11-12
Inner Classes .................................................................................. 11-15
How Do Inner Classes Work? .............................................11-18
Anonymous Classes .............................................................11-19
Exercises ......................................................................................... 11-20
Stream I/O and Files ................................................................................12-1
Java Stream I/O............................................................................... 12-2
Stream Fundamentals.............................................................12-2
Input Stream Methods............................................................12-3
OutputStream Methods .........................................................12-5
Basic Stream Classes ....................................................................... 12-6
FileInputStream and FileOutputStream.......................12-6
BufferedInputStream and BufferedOutputStream.....12-7
DataInputStream and DataOutputStream ....................12-7
PipedInputStream and PipedOutputStream................12-7
URL Input Streams ......................................................................... 12-8
Opening an Input Stream ......................................................12-8
vii
Copyright 1997 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
Positioning Components..........................................................7-4
Component Sizing.....................................................................7-4
Notes ................................................................................................... 7-5
Frames................................................................................................. 7-6
Creating a Simple Frame..........................................................7-6
Running the Program ...............................................................7-7
Panels .................................................................................................. 7-8
Creating Panels..........................................................................7-8
Creating Panels..........................................................................7-9
Container Layouts........................................................................... 7-10
Layout Managers ....................................................................7-10
A Simple Example........................................................................... 7-11
The main() Method................................................................7-12
new Frame(“GUI Example”)...............................................7-12
f.setLayout(new FlowLayout())....................................7-12
new Button(“Press Me”)...................................................7-12
f.add(b1)................................................................................7-13
f.pack()..................................................................................7-13
f.setVisible(true)............................................................7-13
Layout Managers ............................................................................ 7-14
Flow Layout Manager ............................................................7-14
Border Layout Manager .........................................................7-16
Grid Layout Manager.............................................................7-19
CardLayout .............................................................................7-21
Other Layout Managers .........................................................7-24
Notes ................................................................................................. 7-25
Creating Panels and Complex Layouts ....................................... 7-26
Exercises ........................................................................................... 7-28
The AWT Event Model .............................................................................8-1
What Is an Event? ............................................................................. 8-2
Event Sources.............................................................................8-2
Event Handlers..........................................................................8-2
How Events Are Processed .....................................................8-2
JDK 1.0 Event Model Versus JDK 1.1 Event Model ..................... 8-3
Hierarchal Model (JDK 1.0) .....................................................8-3
Delegation Model (JDK 1.1).....................................................8-5
Java GUI Behavior............................................................................. 8-8
Categories of Event ...................................................................8-8
A More Complex Example ....................................................8-10
Multiple Listeners ...................................................................8-14
Event Adapters................................................................................ 8-15
Exercises ........................................................................................... 8-16
The AWT Component Library ................................................................9-1
Facilities of the AWT ........................................................................ 9-2
TextField........................................................................................... 9-11
vi Server Administration
Copyright 1997 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
Objects and Classes ...................................................................................5-1
Abstract Data Types ......................................................................... 5-2
Defining Methods .....................................................................5-4
Pass-by-value.............................................................................5-5
The this Reference .....................................................................5-7
Data Hiding ...............................................................................5-8
Encapsulation ..........................................................................5-10
Overloading Method Names......................................................... 5-11
Constructing and Initializing Objects .......................................... 5-12
Explicit Member Initialization ..............................................5-12
Constructors.............................................................................5-13
The Default Constructor ........................................................5-14
Subclassing....................................................................................... 5-15
The “is a” Relationship...........................................................5-15
The extends Keyword...........................................................5-16
Single Inheritance....................................................................5-17
Constructors Are Not Inherited............................................5-17
Polymorphism .........................................................................5-18
Method Arguments and Heterogeneous Collections ........5-19
The instanceof Operator.....................................................5-20
Casting Objects ........................................................................5-21
Overriding Methods ....................................................................... 5-22
Comparing Java With Other Languages .............................5-24
Grouping Classes ............................................................................ 5-25
Packages ...................................................................................5-25
The import Statement............................................................5-26
Directory Layout and the CLASSPATH Environment
Variable..................................................................................5-27
Exercises ........................................................................................... 5-28
Exceptions in the Java Language.............................................................6-1
Exceptions .......................................................................................... 6-2
Exception Example ........................................................................... 6-3
Exception Handling .......................................................................... 6-4
try and catch Statements.......................................................6-5
finally Statement ...................................................................6-5
Example Revisited ....................................................................6-6
Exception Categories ........................................................................ 6-7
Common Exceptions.................................................................6-8
The “Handle or Declare” Rule ........................................................ 6-9
Creating Your Own Exceptions .................................................... 6-10
Example ....................................................................................6-10
Exercises ........................................................................................... 6-12
Building Java GUIs....................................................................................7-1
Building Graphical User Interfaces ................................................ 7-3
Containers and Components...................................................7-3
v
Copyright 1997 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
Basic Java Types ................................................................................ 2-5
Logical – boolean.......................................................................2-5
Textual – char and String .........................................................2-5
Integral – byte, short, int, and long ........................................2-6
Floating Point – float and double ...........................................2-7
Variables, Declarations and Assignments ..................................... 2-8
Java Coding Conventions ................................................................ 2-9
Other Conventions..................................................................2-10
Understanding Objects................................................................... 2-11
In the Beginning ......................................................................2-11
Aggregate Data Types ............................................................2-12
Creating an Object...................................................................2-15
Creating an Object – Memory Allocation and Layout.......2-16
Assignment of Reference Variables......................................2-17
Default Initialization and the null Reference Value...........2-18
Terminology Recap.................................................................2-19
Exercises ........................................................................................... 2-20
Notes ................................................................................................. 2-22
Expressions and Flow Control.................................................................3-1
Expressions ........................................................................................ 3-2
Variables and Lifetime .............................................................3-2
Variable Initialization ...............................................................3-3
Operators....................................................................................3-4
Logical Expressions ..................................................................3-5
String Concatenation With + ...................................................3-5
Short Circuit Logical Operators ..............................................3-6
Right-Shift Operators >> and >>>..........................................3-7
Promotion and Casting of Expressions..................................3-8
Casting ........................................................................................3-8
Flow Control ...................................................................................... 3-9
Branching Statements ...............................................................3-9
Looping Statements ................................................................3-11
Special Loop Flow Control ....................................................3-13
Exercises ........................................................................................... 3-14
Arrays ...........................................................................................................4-1
Declaring Arrays ............................................................................... 4-2
Creating Arrays ................................................................................. 4-3
Initializing Arrays ............................................................................. 4-4
Multi-dimensional Arrays ............................................................... 4-6
Array Bounds .................................................................................... 4-7
Copying Arrays ................................................................................. 4-8
Exercises ............................................................................................. 4-9
iv Server Administration
Copyright 1997 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
Contents
About the Course ...................................................................................... xiii
Solaris and Windows 95/NT Setup Differences .......................... xiv
Course Prerequisites.......................................................................... xv
Course Objectives.............................................................................. xvi
Course Content................................................................................ xvii
Typographical Conventions and Symbols ..................................... xx
Notes ................................................................................................... xxi
Getting Started ...........................................................................................1-1
What Is Java? ..................................................................................... 1-2
The Java Virtual Machine ........................................................1-3
Garbage Collection ...................................................................1-5
Code Security.............................................................................1-6
A Basic Java Application.................................................................. 1-9
HelloWorldApp.........................................................................1-9
HelloWorldApp Described ....................................................1-10
Compiling and Running HelloWorldApp................................... 1-13
Compiling.................................................................................1-13
Running ....................................................................................1-13
Troubleshooting the Compilation ................................................ 1-14
Compile-Time Errors..............................................................1-14
Runtime Errors ........................................................................1-14
Java Source File Layout .................................................................. 1-15
Runtime Errors ........................................................................1-15
Using the Java Documentation ..................................................... 1-16
Exercises ........................................................................................... 1-18
Identifiers, Keywords, and Types...........................................................2-1
Comments .......................................................................................... 2-2
Semicolons, Blocks, and Whitespace......................................2-2
Identifiers ........................................................................................... 2-3
Keywords ........................................................................................... 2-4
Java Keywords...........................................................................2-4
iii
Copyright 1997 Sun Microsystems, Inc. All Rights Reserved. SunService October 1997
Copyright 1997 Sun Microsystems, Inc. All rights reserved. 2550 Garcia Avenue, Mountain View, California 94043-1100
U.S.A.
This product and related documentation are protected by copyright and distributed under licenses restricting its use,
copying, distribution, and decompilation. No part of this product or related documentation may be reproduced in any
form by any means without prior written authorization of Sun and its licensors, if any.
Portions of this product may be derived from the UNIX® and Berkeley 4.3 BSD systems, licensed from UNIX System
Laboratories, Inc., a wholly owned subsidiary of Novell, Inc., and the University of California, respectively. Third-party
font software in this product is protected by copyright and licensed from Sun’s font suppliers.
RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the United States Government is subject to the
restrictions set forth in DFARS 252.227-7013 (c)(1)(ii) and FAR 52.227-19.
The product described in this manual may be protected by one or more U.S. patents, foreign patents, or pending
applications.
TRADEMARKS
Sun, the Sun logo, Sun Microsystems, SunSoft, the SunSoft logo, Solaris, SunOS, OpenWindows, DeskSet, ONC, ONC+,
NFS, Java and HotJava are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and certain other
countries. UNIX is a registered trademark in the United States and other countries, exclusively licensed through X/Open
Company, Ltd. OPEN LOOK is a registered trademark of Novell, Inc. PostScript and Display PostScript are trademarks of
Adobe Systems, Inc. All other product names mentioned herein are the trademarks of their respective owners.
All SPARC trademarks, including the SCD Compliant Logo, are trademarks or registered trademarks of SPARC
International, Inc. SPARCstation, SPARCserver, SPARCengine, SPARCstorage, SPARCware, SPARCcenter, SPARCcluster,
SPARCdesign, SPARC811, SPARCprinter, UltraSPARC, microSPARC, SPARCworks, and SPARCompiler are licensed
exclusively to Sun Microsystems, Inc. Products bearing SPARC trademarks are based upon an architecture developed by
Sun Microsystems, Inc.
The OPEN LOOK® and Sun™ Graphical User Interfaces were developed by Sun Microsystems, Inc. for its users and
licensees. Sun acknowledges the pioneering efforts of Xerox in researching and developing the concept of visual or
graphical user interfaces for the computer industry. Sun holds a non-exclusive license from Xerox to the Xerox Graphical
User Interface, which license also covers Sun’s licensees who implement OPEN LOOK GUIs and otherwise comply with
Sun’s written license agreements.
X Window System is a trademark of the X Consortium.
THIS PUBLICATION IS PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES
ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESE CHANGES WILL BE INCORPORATED IN
NEW EDITIONS OF THE PUBLICATION. SUN MICROSYSTEMS, INC. MAY MAKE IMPROVEMENTS AND/OR
CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THIS PUBLICATION AT ANY TIME.
Please
Recycle
Java Programming
SL-275
Student Guide