Given by Geoffrey C. Fox at CPS616 Basic Information Track for Computational Science on Winter-Spring Semester 96. Foils prepared 29 January 1996
Abstract * Foil Index for this file
Overview including History and alpha versus beta issues |
Comparison of Java and Javascript |
Overall Java Philosophy and Features including security etc. |
Java Programming Language |
Object Oriented and Class Structure |
Exceptions |
Applet Programming and Threads |
Abstract Windowing Toolkit |
Networking and I/O; native classes |
Futures and HPCC Implications |
Hot Java is not discussed as beta version not currently available |
This table of Contents Abstract
Instructor: Geoffrey Fox |
teamed with Wojtek Furmanski, Nancy McCracken |
Syracuse University |
111 College Place |
Syracuse |
New York 13244-4100 |
Overview including History and alpha versus beta issues |
Comparison of Java and Javascript |
Overall Java Philosophy and Features including security etc. |
Java Programming Language |
Object Oriented and Class Structure |
Exceptions |
Applet Programming and Threads |
Abstract Windowing Toolkit |
Networking and I/O; native classes |
Futures and HPCC Implications |
Hot Java is not discussed as beta version not currently available |
HotJava is a Web browser that supports dynamically downloadable interactive content. Alpha version of HotJava expected to be replaced by major rewrite |
Arbitrarily sophisticated dynamic multimedia applications inserts called Applets can be embedded in the regular HTML pages and activated on each exposure of a given page. |
Applet constructs are implemented in terms of a
|
Applets are written in Java -- a new general purpose object-oriented programming language from Sun Microsystems. |
Starts in 1991 by Project Green --- a group in Sun that detaches from the main campus as a semi-autonomous task force focused on operating software for consumer electronic devices such as smart set-top boxes |
Gosling (creator of Sun NeWS which had major conceptual impact both on current Java and Telescript models) realizes that C++ is not adequate and initiates development of a new language Oak, later renamed as Java. |
A PDA (Personal Digital Assistant -- codename *7) based on Oak/Java ready in 1993. Green Team incorporates as FirstPerson, Inc. |
*7 proposal to Time-Warner rejected in 1993. 3DO deal falls through in 1994. FirstPerson, Inc. dissolves. |
Small group (~30 people, now Java Team) continues development and decides to adapt Oak as a Web technology. |
An experimental web browser written in Java, called WebRunner and later renamed as HotJava, ready in 1994. |
Java/HotJava published in April '95. |
Netscape licences Java in May '95 and builds Java into Netscape 2.0 -- This confuses ownership and open-ness of Java |
Beta JDK (Java Development Kit) published in summer/fall '95. It is better software but lower functionality than Alpha. |
First alpha Java books appear in fall '95 such as a popular overview by SAMS and technical book "Java!" by Tim Ritchey, edited by New Riders. |
Dec 4 1995 Business Week cover story on "Software Revolution --- The Web Changes Everything" exposes Java as a breakthrough force in the expanding Web/Internet. Also points out that "Java as a business" is yet to be defined. |
In next week, SGI IBM Adobe Macromedia and finally Microsoft adopt/license Java. It appears that Java will be open and should be adopted by open Web community |
Alpha release of Java/Hotjava included:
|
In Short, Alpha Java/HotJava was a complete software release of all system components, free for research and subject to ($125K) licence for business use. |
Version 1.0 of JDK released January 96 by JavaSoft |
Beta/1.0 JDK should be the Internet standard and so compatible with ongoing Java implementations by all licensees, most notably Netscape. Beta/1.0 JDK includes:
|
Release of Beta/1.0 HotJava expected soon and could be very interesting technically for certainly alpha HotJava was very helpful in building customized Graphical User Interfaces
|
Hooked on Java by Java developers Arthur van Hoff, Sami Shaio, Orca Starbuck is (first) serious (but still rather high-level) book on beta Java |
Substantial tutorial and report material available on line http://www.javasoft.com |
Netscape renames Livescript as Javascript and this is an interesting variant of Java which is fully interpreted -- use for overall customization of client |
Use Java for detailed programming and JavaScript for overall integration of client interface and system |
JavaScript: Interpreted by client and NOT compiled |
Java: Compiled on Server before execution on client
|
JavaScript: Object based -- no classes or inheritance -- built in extensible objects |
Java: Object-oriented. Programs consist of object classes with inheritance |
JavaScript: Integrated with HTML as embedded ascii but of course HTML looks rather irrelevant at times! |
Java: Applets distinct from HTML but invoked from HTML Pages |
JavaScript: do not declare variables' datatypes -- Loose typing |
Java: MUST declare variables' datatypes -- Strong typing |
JavaScript -- Dynamic Binding -- object references computed at runtime |
Java -- Static Binding -- object references must exist at compile time |
Java and JavaScript are secure and cannot write to disk |
Document The Java: A White Paper by Sun Microsystems -- October 1995 draft by James Gosling and Henry McGilton -- enumerates the following main features of Java: |
Simple and Familiar |
Object-oriented |
Architecture-neutral |
Portable |
Somewhat Interpreted |
Distributed |
Robust |
Secure |
High performance |
Multi Threaded |
Dynamic |
Java omits several rarely used, poorly understood and confusing features of C++ including operator overloading, multiple inheritance, pointers and automatic type coercions. |
It adds automatic garbage collection which makes dynamic programming easier in Java than in C or C++.
|
It also adds 'Interface' construct, similar to Objective C concept, which often compensates for the lack of multiple inheritance by allowing method calling syntax to be "inherited". |
The resulting language is familiar as it looks like C++ but is simpler and hence easier to program in. |
It also results in a much smaller kernel which is suitable for planned Java ports to consumer electronic devices. Base (alpha) interpreter is ~40Kb, libraries and threads add additional 175Kb. |
Java model can be viewed as a C++ subset, with some dynamic elements inherited from Objective-C (method overloading, garbage collection). |
Structures, Unions and Functions are absorbed into data and methods of Java classes -- Java is Simple! |
The strength of Java object-oriented model is not is sophistication but in simplicity and the extensive class library associated with the system (some 250 public classes were released in both alpha and beta). |
Java class plays also a role of a communication atom in the Web embedding model. Applet classes identify themselves by names in the HTML applet tag. Applet downloads other classes, present in the applet source. Hence, the Java class names play the role of addressing mode for the distributed Java code database. |
C/C++ programming in a heterogeneous network environment requires use and compatibility across several vendor platforms and the corresponding compilers. This problem is solved in Java by designing platform-independent binary representation called Java bytecode (or opcode). |
Java compiler (written in Java and platform-independent) reads Java source and generates Java bytecode. These bytecodes are shipped to client machines upon browser requests. |
Each client machine must run Java interpreter which performs runtime execution of Java bytecodes. Java interpreter is written in POSIX compliant ANSI C and needs to be ported to and conventionally compiled (once) on each individual platform. |
Once the interpreter is ported, application developers don't need to worry at all about platform specificity and differences between native compilers. They write portable Java which is compiled by platform independent Java compiler and executed on Java interpreter, ported to various platforms. |
Java language offers a uniform abstract (virtual) machine model which is identical for all platforms. |
SUN owns the Java Virtual Machine (see online report) -- it is universal while classes can be added by any user |
Unlike in C/C++ where various integers match the architecture of a physical machine at hand, Java byte, char short, int and long are always of the same size, equal to 8, 16, 16(unicode), 32 and 64 bits, respectively.
|
Differences between vendor specific windowing environments (X Windows, MS Windows, Macintosh) are removed in terms of the Abstract Windowing Toolkit (AWT) metaphor. |
AWT is given by ~60 Java classes (alpha) which offer a universal GUI programming model, portable between UNIX, PC and Mac, and translated automatically to native windowing systems on individual platforms by Java interpreters. |
Java represents a compromise between fully compiled (like C/C++) and fully interpreted (like Smalltalk or Perl) models. |
Java "compiler" produces a binary bytecode output which is portable and much smaller than the real binary for a specific machine (Typical bytecode size is of order of the original source code, within a factor of 2). |
Java "interpreter" executes this bytecode and is therefore less dynamic than e.g. Perl interpreter (which performs an equivalent bytecode construction internally and on-the-fly when reading the program source). |
In general, the compilation process is: a) time consuming and b) platform specific. Hence, interpreters are built and used to facilitate a) rapid prototyping and/or b) portability. Java model is focused on platform independence but the development throughput is also reasonable since the Java compiler is fast and generates compact bytecode output. |
Popular TCP/IP based protocols such as FTP or HTTP are supported in terms of network protocol classes. This facilitates various forms of distributed processing. New protocols (e.g. PVM etc.) can added and dynamically installed. |
Distributed computing model of Java is mainly client-server, with Java compiler preparing the opcodes at the server side, and Java interpreter executing it at the client side. |
One can expect more dynamic uses of Java with Java threads on both Server and Client side communicating with each other. This is illustrated by Java based Collaboratory developed by Vishal Mehra as NPAC/Ece Master's Thesis |
Java enforces compiler-time type checking and eliminates this way some error prone constructs of C/C++. |
Pointer arithmetic is fully eliminated which allows e.g. for runtime checking of array subscripts and enforces security of the Java model. |
Explicit declarations are always required, i.e. C-style implicit declarations are abandoned. This allows the Java complier to perform early error detection. |
Rapid prototyping in Java is less natural than in JavaScript,Lisp, Tcl, Smalltalk or Perl, but the software quality assurance of Java is higher than in these more dynamic and 'forgiving' languages. |
Java binaries are shipped across the network and executed on client machines. Security is therefore a critical issue and strongly enforced in Java.
|
Modifications of the C++ model such as eliminating pointer arithmetic and coercion were dictated mainly by the security requirements. |
Most viruses are based on acquiring access to private/protected sectors of computer memory which is impossible in Java. |
Java opcodes are executed at the client side by Java interpreter which operates exclusively on the virtual memory. Hence, unless there are security bugs in the Java interpreter itself, the model is safe and users cannot create security holes by incorrectly or maliciously written applets. |
The byte codes sent across network are verified at the client which prevents evil/corrupted classes from causing problems |
Java interpreter performs on-the-fly runtime execution of the Java bytecodes which results typically in a satisfactory performance. |
Support for generating native machine code out of Java bytecodes, viewed as intermediate compiler form, is also provided and useful for performance demanding applications. |
The performance of the machine code, generated from Java bytecodes, is comparable to that offered by typical C/C++ compilers on the same platform. |
Several of these concepts are in fact similar as in the OSF/ANDF project. Using ANDF terminology, we would call Java compiler a 'producer', and the machine code generator discussed here, an 'installer'. Default Java working mode doesn't use installers but directly interprets the intermediate form (this mode is supported in ANDF by GAI -- Generalized ANDF Interpreter). |
ANDF model is in principle applicable to all languages. Java/HotJava system implements ANDF concepts for the Java language. |
Java model offers preemptive multithreading, implemented in terms of the Thread class. Thread methods offer a set of synchronization primitives based on monitor and conditional variable paradigm by C.A.R. Hoare. Java threads inherit some features from the pioneering Cedar/Mesa System by Xerox Park that gave birth to Macintosh and object-oriented programming. |
A typical use of Java multithreading in applet programming is to have several independent but related simulations (e.g. various sorting algorithms), running concurrently in an applet window. Multithreading is also used internally by the HotJava browser to handle multiple document dynamics. |
Another interesting application domain are multi-HotJava environments to come such as collaboratory or gaming. |
Java threads don't have built-in point-to-point communication primitives. Various thread communication environments can be provided by coupling the thread and network protocol objects. |
Java model is more dynamic than C++ and closer to Smalltalk or Perl. |
Subclasses don't need to to be recompiled after superclass implementation is updated. |
Classes have runtime representation (implemented in terms of the Class class) which allows one to look up type of a given object instance at runtime (in C cannot know if pointer is to integer or browser!) |
C++ has "fragile superclass" problem where must recompile children if change anything (method/instance variable) in a superclass or referenced class -- Java resolves references at runtime and avoids this. |
l Good l Fair l Poor |
One resource is the The Java Language Specification by Sun Microsystems, Inc., March 1995 updated to October 1995. |
This and Java Tutorial can be found on http://www.javasoft.com web site with Java Virtual Machine and the White Paper described earlier |
There is also the Hooked on Java book, its CDROM and the updated online resources refered to in Book |
The CDROM is superceded in many ways by latest JDK 1.0 release |
Program Structure |
Lexical Issues |
Applet versus Application |
Variables and Expressions |
Types and Array |
Control Flow |
Exceptions |
Object Model and Classes |
Interfaces |
Methods |
This is followed by discussion of Implementation in terms of overall Classes, Applet Programming, Threads, Graphics and the Abstract Windowing Toolkit, Networking and I/O, Native classes, HPCC implications |
Source code of a Java program consists of one or more compilation units, implemented as files with .java extension. |
Each compilation unit can contain:
|
Java compiler (called javac) reads java source and produces a set of binary bytecode files with .class extensions, one for each class declared in the source file. For example, if Foo.java implements Foo and Fred classes, then "javac Foo.java" will generate Foo.class and Fred.class files. |
Suppose that Foo implements an applet and Fred is an auxiliary class used by Foo. If HotJava/Netscape encounters a tag <APPLET code="Foo.class">, it will download Foo.class and Fred.class files and it will start interpreting bytecodes in Foo.class. |
Lexical structure inherits a lot from C/C++. There are however some notable differences which are listed below. |
Java characters are based on 16--bit wide Unicode Worldwide Character Encoding rather than the usual 8--bit wide ASCII. |
This allows full support of all alphabets and hence all languages |
Three types of comments are supported:
|
for /** */ one inserts HTML documentation with some simple macros such as @see (to designate see also) BEFORE the method or class being documented |
Java reserves the following keywords: |
abstract boolean break byte byvalue case cast |
catch class const continue default do double |
else extends final finally float for future generic |
goto if implements import inner instanceof int |
interface long native new null operator outer |
package private protected public rest return |
short static super switch synchronized this |
throw throws transient try var void volatile while |
Note goto is not allowed in Java but its still reserved! |
Applications are .java files with a main class which reads arguments and is excuted first |
One uses javac to compile the application converting .java to .class |
Then run the interpreter java with the .class file as argument |
.java files are in Java; .class files are in universal bytecodes |
The resources javac and java are part of JDK and are not in Netscape and so are currently not broadly available. You must log in to our servers to use them |
So instead in this course we will use applets so all the Java threads are distributed around and don't grind our servers to a halt |
Applets should NOT have main method but rather init, stop, paint etc. |
They should be run through javac compiler getting a .class file as before |
Create an HTML file (say HelloWorld.HTML in same directory as .class file) and include in this |
<applet code="Example.class" width=500 height=200 > </applet> in simplest case with no parameters where applet will run in window of given width and height (in pixels) |
If you have JDK on one's machine, one can run the applet with appletviewer HelloWorld.html |
Alternatively run Netscape 2.0 essentially anywhere and applet is interpreted and run by Java interpreter built into Netscape. |
This way we can compile on places with JDK installed but run almost anywhere! |
Each Java variable or expression has a definite type. Simple types such as integers or booleans are built-in. New composite types can be constructed in terms of classes, arrays and interfaces.
|
There are 4 integer types: byte, short, int, long of size 8, 16, 32 and 64 bits, respectively. |
Float is 32 bits, double is 64 bits. Floating point arithmetic and data formats are defined by IEEE754. |
Characters are given by 16bit Unicode charset and represented as short integers. |
One can use casts such as longint = (long) i; |
Arrays are "true" or "first class" objects in Java and no pointer arithmetic is supported. Hence, arrays are handled as all other composite objects and its special role is due only to some syntactic sugar inherited from C/C++. |
An Array is declared as:
|
and created by:
|
or concisely:
|
Subscripts are range checked in runtime and so vec[-1] and vec[128] will generate exceptions. |
Array length can be extracted via the length instance variable, e.g.
|
Arrays of arbitrary objects can be constructed,
|
Arrays can have dynamic sizing
|
Java's expressions are very similar to C and the following are valid: |
2+3 |
(2+3)*i |
i++ /* equivalent to i = i +1 */ |
(i > 0 ) && (j>0) /* Boolean */ |
i <<1 /* Left shift by 1 binary digit */ |
(i>0) ? true:false /* Boolean */ |
i >>> 2 /* Signed right shift by 2 binary digits */ |
"fred" + "jim" is "fredjim" |
/* + Equivalent to . in Perl */ |
(a instanceof B) /* True iff object a is of class B */ |
if(some boolean expression) {..} |
else if(another boolean) {..} |
else {...} |
while(any boolean) {/*DoStuff*/} |
do {/*Whattodo*/} while(another boolean); |
for(expression1; booleanexpression ; expression2) {...} |
naturally starts with expression1, applies expression2 at end of each loop, and continues as long as booleanexpression true |
switch (expression) { /* Just as in C */ |
case Constant1: /* Do following if expression=Constant1 */ |
/* Bunch of Stuff */ |
break; |
case Constant2: /* Do following if expression=Constant2 */ |
/* Bunch of Stuff */ |
break; /* ....... */ |
default: |
/* Bunch of Stuff */ |
break; |
} |
One can break out of (nested) for loops in fashion offered by Perl with different syntax |
outer: // label |
for( int j=0; j<10; j++) { /* Note j only defined in for loop */ |
/* select course j */
|
/* Continue jumps to here to next iteration of loop labelled with outer */ |
} |
One can break out of (nested) for loops in fashion offered by Perl with different syntax |
outer: // label |
for( int j=0; j<10; j++) { /* Note j only defined in for loop */ |
/* select course j */
|
} |
/* break jumps to here out of loop labelled by outer */ |
loopstart: // label |
for( int j=0; j <10; j++) { |
switch(j) { |
case 3: |
break; |
default: |
if( studentgrade[j] == 2.5)
|
/* do some stuff */ |
break; |
} |
} |
/* break loopstart goes to here out of loopstart loop */ |
loopstart: // label of following for loop |
for( int j=0; j <10; j++) { |
switch(j) { |
case 3: |
break; |
default: |
if( studentgrade[j] == 2.5)
|
/* do some stuff */ |
break; |
} // End Switch Block |
/* continue loopstart goes to here for next iteration of loopstart loop */ |
} // End loopstart for loop |
Java supports a hierarchical model of exceptions which allow and indeed require user to supply suitable handlers for any exception that can occur in a Java program |
Note exceptions that can occur in a method must either be caught (i.e. handled inside method) or thrown (i.e. returned to callee) |
Thrown exceptions are like returned arguments and are for instance part of interface to a method |
Exceptions are all (at some level in hierarchy) subclasses of Throwable class |
method1 {
|
} |
method2 throws Exception3 {
|
} |
method3 throws Exception3 {
|
} |
As Examples of hierarchy: |
catch(InvalidIndexException e) {..} would catch particular exception whereas |
catch(ArrayException e) {..} would catch all Arrayexceptions |
Objects are instances of Classes which form a template to allow definition of objects of the same type -- Classes are not objects although one can define static or class variables and methods which are shared by all instances of a class |
The data of an object are called instance variables and they can be accessed for read or write via suitable methods which define the behavor of an object |
/* Movable Point Class */ |
public class mPoint {
|
Both class and its instance variables can be accessed by all other java objects |
Call to method in Object2 (message) from object1 is passed up the class hierarchy until a definition is found |
Call to method in Object2 (message) from object1 is passed up the class hierarchy until a definition is found |
Class declaration in Java shares common aspects with C++ but there are also some syntactic and semantic differences. |
Only single inheritance is supported but aspects of multiple inheritance can be achieved in terms of the interface construct. Interface is similar to an abstract class with all methods being abstract and with all variables being static (global). Unlike classes, interfaces can be multiply-inherited. |
ClassModifiers class className [extends superClass] [implements interfaces] { |
e.g. public class Test extends Applet implements Runnable { |
defines an applet that can use threads which have methods defined by Runnable interface |
This prints in applet window, the classic Hello World string! |
import java.awt.Graphics |
public class HelloWorld extends java.applet.Applet {
|
} |
g which is of class Graphics, is window in which applet runs (i.e. is displayed) |
This is "application" version of previous applet |
class HelloWorldApp {
|
} |
Note args are of class String and needed even though HelloWorldApp has no command line arguments |
This invokes the class Date and creates object today as an instance of this class |
Date() is Constructor of Date class which sets default value (current date) in today |
Date today declares today to be instance of this class |
import java.util.Date; |
class DateApp {
|
} |
This application reads from standard input and counts number of characters which are then printed |
class Count {
|
} |
Possible ClassModifiers are: |
abstract -- Contains abstract methods without implementation -- typically such abstract classes have several subclasses that define implementation of methods |
final -- Cannot have a subclass |
public -- May be used by code outside the class package and (unix) file must be called ClassName.java where ClassName is unique public class in file |
private -- this class can only be used within current file |
friendly(i.e. empty ClassModifier) -- class can be used only within current package |
synchronizable -- Instances of this class can be made arguments of synchronization statements |
MethodModifier ReturnType Name(argType1 arg1, ......) |
Returntypes are either simple types (int, byte etc.), arrays or class names |
Possible MethodModifiers are:
|
paint is an important method in applets which is defined in parent component class as the null method |
It must be overwritten by any dynamic applets that need to update display. |
import java.awt.*; // imports all classes in java.awt package -- this applet needs Graphics, Font, Color which could be listed separately |
public class HelloWorld extends java.applet.Applet { |
Font f = new Font("TimesRoman",Font.BOLD,36); |
public void paint(Graphics g) { |
g.setFont(f); |
g.setColor(Color.red); |
g.drawString("Hello world!", 50, 25); } |
} |
A class can only have one parent class but can implement several interfaces |
interfaces are essentially abstract classes and can have methods without impementation and static variables |
interface Printable {
|
} |
class Cookie implements Printable {
|
} |
class WastePaper implements Printable {
|
} |
We could imagine a Ford Mustang as inheriting from two major sources |
Firstly a set of manufacturing companies -- make these interfaces as "qualitative" |
Secondly from a set of Vehicle types which we will make real classes as there are non trivial methods involved in constructing cars |
Cars MyFordMustang = new Cars(Lots of Options) |
is a particluar instance of class Cars |
Note that Interfaces often play a software engineering as opposed to required functional role |
For instance, the printable interface (which is fictitious and not part of current Java release) establishs that any class implementing it can be "printed" with a standard method -- "print" |
Note that Interfaces are not significantly used in current Java release where perhaps there are 15 times as many class definitions as interface definitions |
Two examples are Runnable and Cloneable both of which extend Object class -- note interfaces like classes can extend existing classes: |
The Cloneable Interface has NO methods but is used to indicate that an instance of this class can be "cloned" i.e. that the clone method (defined for overarching Object class) can be used |
The Runnable Interface has one method run() which must always be overwritten and is used to indicate that class with this interface can use threads without being a subclass of Thread. Applets must use Runnable if they need explicit threads because they explicitly are a subclass of panel and as no multiple inheritance, one cannot be a subclass of two classes |
This class returns object of class String which reverses order of characters in input object source which is also an instance of class String |
class ReverseString {
|
length, CharAt and toString are methods of class String which is used for fixed character strings |
StringBuffer is constructor of class StringBuffer which is used for mutable character strings and has methods append and toString |
Suppose we have defined a class called mPoint for a movable point which has position (x,y) Color color and can be moved by amount (dx,dy) at each step |
mPoint BunchofPoints[2]; /* defines BunchofPoints to be 2 dimensional array of mPoint objects -- it does not instantiate BunchofPoints */ |
FirstPoint = new mPoint(); /* Allocates an instance of mPoint and invokes Constructor of mPoint to Initialize */ |
FirstPoint.dx=5; |
FirstPoint.dy=5; /* Redefines values of instance variables dx,dy for object FirstPoint */ |
mPoint could be defined by |
import java.awt.*; |
public class mPoint {
|
} |
Class: A template for an object which contains variables and methods which can be inherited from other superclasses and whose calling sequence and existence can be defined by interfaces |
Object or Instance: A particular realization of some class; different instances usually have different values for their variables or instances but the same methods |
Simple types: variables defined by int, char etc. are NOT objects but each has an associated wrapper class which can be used with greater power but lower efficiency |
Superclass: A class further up in the inheritance tree |
Subclass: A class further down in the inheritance tree |
Abstract classes:contain abstract methods which are not implemented and only define interfaces. Subclasses will provide implementations |
Method or Instance Method: the usual type of method which is defined in a class and operates in instances of class or subclasses of defining class |
static or class method: A method defined in a class which can operate on the class itself or on any object |
static or class variable: A variable that is owned by the class and all its instances as a whole. It is stored in class and not in particular instances. |
Interface: A collection of abstract behavior(method) specifications that individual classes can then implement |
Package: A collection of classes and interfaces. Classes or interfaces from packages other than java.lang must be explicitly imported or referred to by full package name |
Methods of identical name to class are special -- they are constructors |
mPoint() { /* Default Constructor */
|
} |
We can overload method to define different versions with different numbers and types of arguments |
mPoint(int x, int y) { /* Constructor to set Specific Initial values */
|
} |
Note this refers to current object |
mPoint can have other methods to set its instance variables such as: |
public void setDelta(int _dx, int _dy) {
|
} /* where we don't need this as used _dx, _dy */ |
Any class can have an optional finalizer that will perform any necessary clean-up needed when garbage collector (which is automatic in Java) tries to delete object and free-up resources it uses |
An example is given for an object that uses an I/O stream and needs to close it on termination |
protected void finalize() {
|
} |
Earlier one might have set this up with syntax such as that on next foil |
File file; /* defines file to be object of class File */ |
try{
|
} catch (IOException e) { |
/* This catches ALL I/O errors including read and write stuff */ |
/* After Handling Some How */ |
return; /* but the finally clause will be executed whether or not code terminates normally */ |
} /* We must close file whatever happens */ |
finally {
|
} |
import java.awt.*; /* Imports Graphics Method for display */ |
public class mPoint { /* Continue as before and add */
|
} |
We can define a new class mRectangle that extends mPoint where (x,y,color) from mPoint are lower left hand corner/color and we add width and height |
public class mRectangle extends mPoint {
|
/* overwrite the mPoint's checkBoundry method */
|
} |
The command |
package cps616; |
can be used to group classes together. A package statement can be repeated -- e.g all students could use the above package statement in their Java files and the corresponding classes would be grouped in this one package |
Note classes are called package.Classname where packages in Java system are all termed java.subpackagename |
One uses files in a package by inserting
|
java.lang Contains essential Java classes and is by default imported into every Java file and so import java.lang.* is unnecessary. Thread, Math, Object and Type Wrappers are here |
java.io contains classes to do I/O. This is not necessary (or even allowed!) for applets which can't do I/O in Netscape! |
java.util contains various utility classes that didn't make it to java.lang. Date is here as are hashtables |
java.net contains classes to do network applications. This will be important for any distributed applications |
java.applet has the classes needed to support applets |
java.awt has the classes to support windowing -- The Abstract Windows Toolkit |
java.awt.peer is a secret set of classes with platform dependent details |
public class Object is the root of the Class hierarchy. Every java class has Object as its ultimate parent and so any object (object with a small o is any instance of any class) can use methods of Object |
Methods of Object (used as object.Method()) include: |
clone() Creates a clone of the object |
equals(another object) compares two objects returning boolean answer |
getClass() returns a descriptor of type Class (a child of Object) defining class of object |
toString() returns a String which represents "value" of object. It is expected that each subclass will override this method |
wait() in various forms is used to cause threads to wait |
finalize() contains code to perform when object is deleted by system (I.e. garbage collected) |
Suppose an object is called obj , then we get Class of obj by |
Class itsclass = obj.getClass(); // and the name of this class by: |
String name = itsclass.getName(); |
One can also use instanceof in following fashion |
"foo" instanceof String // is evaluated to true but |
mPoint pt = new mPoint(x,y); |
pt instanceof String // is evaluated to false |
"types" such as int char float etc. are NOT classes |
Thus one cannot use methods such as |
int var; |
var.toString |
Thus ALL types have associated wrappers used like |
Character wrappedchar = new Character(char); |
now wrappedchar has lots of good methods you can use such as: |
wrappedchar.equals(anotherobject); |
wrappedchar.toString(); |
There are also static (class) functions such as: |
toUppercase(char ch); |
isUpperCase(char ch); |
Some of These are in Applet and some in parent (in particular Component) |
public void init() is called ONCE and ONCE only when the applet is loaded or reloaded. Set initial parameters etc. here. |
public void destroy() is what you do when Applet is entirely finished and you need to clean up stray threads or connections to be closed. |
public void start() is called whenever the applet is started which can happen several times during an applet's life-cycle as it starts each time you revisit a page |
public void stop() is called when we temporarily leave Applet to visit another page. A wise move would be to suspend running of Threads to save system resources. |
public void paint(Graphics g) actually has an argument and draws what you want on the screen |
There is somewhat confusing other methods update() and repaint() which need to used in advanced applications. You may need to call repaint() in a dynamic applet to change display but update() would not need to be called as invoked by repaint(). However update() is sometimes best overridden |
public void repaint() is a request by you to the Java runtime to update screen |
public void update(Graphics g) is invoked by repaint() and performs the screen update which involves clearing screen and invoking paint() |
<applet code="fred.class" codebase="classes" width="widthvalue" height="heightvalue" > |
Put a bunch of text here to be displayed by browsers such as Netscape 2.0 on Windows 3.1 that do not support Java |
</applet> |
One can also include INSIDE <applet > tag, attributes available for <img > tag in conventional HTML. These attributes are |
Align=texttop which aligns top of applet with top of the tallest text in the line |
Align=top which aligns top of applet with top of tallest item in the line |
and align= absmiddle, middle, baseline, bottom, absbottom with similar meaning |
hspace=num1 allows num1 pixels to either side of applet and surrounding text |
vspace=num2 allows num2 pixels to top and bottom of applet and surrounding text |
<applet .... > can be followed by |
<param name=attributename1 value="attributevalue1" > ....... |
<param name=attributenameN value="attributevalueN" > |
</applet> |
The Java program accesses this information by |
String attribute; |
attribute = getParamter("attributename1"); |
if( attribute == null )
|
Typically this processing would be in init() method of Applet |
java.awt has several important classes including Graphics, Color, Font and FontMetrics |
Graphics class has primitives to construct basic two dimensional images with methods drawString (text), drawLine, drawRect, fillRect, drawRoundRect (for a rectangle with rounded corners!), draw3DRect (to get shadow effect as in buttons), drawPolygon (general polygon), drawOval, fillOval |
There are also Image, Font, Color operations |
Graphicsinstance.setFont(particularFont) will set the current Font in the instance Graphicsinstance of graphics class to the value particularFont of class Font. There are several other such Font related methods in the Graphics class |
The class Font has an important constructor used as in |
Font particularFont = new Font("TimesRoman",Font.PLAIN,36); |
where one can use Courier Helvetica etc. instead of Time Roman |
Font.PLAIN, Font.BOLD, Font.ITALIC are possible text styles |
FontMetrics fm = getFontMetrics(particularFont); // allows one to find out about the font |
fm.stringWidth("text"); // returns pixel width of string "text" |
fm.getHeight(); // returns total height of one line of Font |
Color c = new Color (redvalue, greenvalue, bluevalue); // red/green/bluevalue can be specified as integers in 0.....255 or floating point numbers from 0 to 1. |
c is generated as a Color in RGB format. |
graphicsobject.setColor(c); // sets current color in graphicsobject which is used for all subsequent operations |
graphicsobject.setFont(particularFont); // similarily sets font hereafter as on previous page |
There are particular Color instances already defined such as |
Color.white equivalent to Color(255,255,255) |
Color.black as equivalent to Color(0,0,0) |
Color.pink as equivalent to Color(255,175,175) |
One can implement threads in two ways
|
Only the second way is possible for applets as these already extend Applet class and so cannot multiply inherit from the Thread class |
Threads must have a run method which is code Thread executes. |
If you are using first way, this is written for this particular thread and overrides run() in Thread class |
In second way, the created Thread automatically takes its run() method to be the run method of the applet |
import java.awt.Graphics; |
import java.util.Date; |
public class Clock extends java.applet.Applet |
implements Runnable { |
Thread clockThread; |
public void start () { |
if (clockThread == null) { |
clockThread = new Thread (this, "Clock"); |
clockThread.start (); |
} |
} |
public void run () { |
while (clockThread !=null) { |
repaint (); |
try { clockThread.sleep(1000);
|
} // end while |
} // end run() |
public void paint (Graphics g) { |
Date now = new Date (); |
g.drawString (now.getHours() + ":"+ now.getMinutes() + ":"+now.getSeconds(), 5, 10); |
} |
public void stop () { |
clockThread.stop(); |
clockThread = null; |
} |
} // End Digital Clock Applet |
Unless you are careful, dynamic applets will give flickering screens |
This is due to cycle |
paint(g) |
update(g) clearing screen |
paint(g) drawing new screen ..... |
where flicker caused by rapid clear-paint cycle. |
There are two ways to solve this problem which involve changing update in different ways
|
Sun distributes a general purpose Animation applet with the Java Development Kit |
Advantages:
|
Disadvantage:
|
1. Prepare a directory. and cd to this directory. |
2. Copy Animator.class, ParseException.class, and ImageNotFoundException.class into your directory. |
3. create a directory audio and put your audio file in it. |
Your audio files can be called 0.au, 1.au, etc.
|
4. create a directory images and put your image files in it.
|
5. prepare a HTML page which has the following type of applet tag: |
<applet code=Animator.class width=200 height=200> |
<param name=imagesource value="images"> |
<param name=endimage value=10> |
<param name=soundsource value="audio"> |
<param name=soundtrack value=spacemusic.au> |
<param name=sounds value="1.au|2.au|3.au|4.au|5.au|6.au|7.au|8.au|9.au|0.au"> |
<param name=pause value=200> |
</applet> |
the imagesource attribute indicate you put your image files in directory images. |
the endimage value 10 indicate that you have 10 image files held in
|
The soundsource indicate that you put your sound files in audio directory. |
The sounds attribute lets you express your audio file sequence. |
the pause attribute is the pause (ms) between each image frame. |
There are other parameters which can be set such as: |
<param name=startup value="loading-msg.gif"> |
This image will show up first to remind user that image is loading. |
This sets background color and initializes applet bounding rectangle to this color |
public void update(Graphics g) { |
g.setColor(getBackground()); |
g.fillRect(0,0,width,height)); |
g.setColor(getForeground(); |
paint(g); |
} |
getBackground() and getForeground() are methods in component class |
fillRect() is a method in Graphics class |
public class ColorSwirl extends java.applet.Applet |
implements Runnable { |
Font f= new Font ("TimesRoman", Font.BOLD, 48); |
Color colors [] = new color [50] |
Thread runThread; |
public void start () { |
if (RunThread == null) { |
runThread = new Thread (this); |
runThread.start ();
|
} |
public void run () { |
float c = 0; // initialize the color array |
for (int i = 0; i < colors.length; i++) { |
colors [i] = Color.getHSBColor (c, (float) 1.0, (float) 1.0); |
c +=.02; } |
int i = 0; // cycle through the colors |
while (true) { setForeground (colors [i]); |
repaint (); |
i++; |
try {Thread.sleep(50);} |
catch (InterruptedException e) {} |
if (i == color.length) i = 0; |
} // End while(true) |
} // end run() |
public void stop () {
|
runThread.stop(); |
runThread = null;
|
} |
public void paint(Graphic g) { |
g.setFont(f); |
g.drawString ("All the Swirly Colors", 15,50); |
} |
public void update(Graphics g) { |
paint(g); } // No need to clear background as unchanged! -- only color of letters changes |
} // end Applet ColorSwirl |
Here you have two "graphics contexts" (frame buffers of the size of the applet), and you construct the next image for an animation "off-line" in the second frame buffer. |
This frame buffer is then directly copied to the main applet Graphics object without clearing image as in default update() |
Image OffscreenImage; // Place to hold Image |
Graphics offscreenGraphics; // The second graphics context which contains offscreenImage |
offscreenImage = createImage(width,height); |
offscreenGraphics = offscreenImage.getGraphics(); |
The previous statements could be in init() while in paint(), one will construct applet image in offscreenGraphics as opposed to the argument g of paint(). So one would see statements such as: |
e.g. offscreenGraphics.drawImage(img,10,10,this); |
Finally at end of paint(), one could transfer the double buffered image to g by |
g.drawImage(offscreenImage,0,0,this); |
One would also need to override the update() method by |
public void update(Graphics g) { |
paint(g); |
} |
Events ( distinguish these from Exceptions!) are the way the AWT interacts with the user at mouse or keyboard. |
The AWT calls particular event handlers (analogous to exception or interrupt handlers) when user interacts with system in particular ways. |
The handling is defined in packages java.awt and java.awt.peer (the machine dependent stuff) with method handleEvent() in class Component(peer) |
One could add additional capability here for systems with nifty virtual reality and other user interfaces but we won't cover this here! |
public boolean keyDown(Event evt, int key) {} method is called when you press keyboard. |
The Event class has various special class (static) variables defined including |
Event.F1 -- the F1 key |
Event.UP The Up arrow etc. |
The Component class (grandparent of Applet) has a rich set of Event handlers which you should override if you wish to process particular input |
public boolean mouseDown(Event evt, int x, int y) {
|
} |
Other handlers are mouseDrag, mouseEnter (enters current component), mouseExit, mouseMove (with its button up), keyUp, keyDown |
In Java, the GUI (Graphical User Interface) is built hierarchically in terms of Components -- one Component nested inside another starting with the smallest Buttons, including Menus, TextFields etc. and ending with full Window divided into Frames, MenuBars etc. |
Not all useful Classes are inherited from Component. For instance Menu inherits from MenuComponent (interface) --> MenuItem --> Menu |
One also needs a set of methods and classes to define the layout of the Components in a particular Panel |
LayoutManager is a java.awt interface with several particular layout strategies implemented as classes under this interface |
The Container class has methods to interact with LayoutManager classes |
In the simplest use of AWT, one could add a Button to an Applet (grandchild of Container) using in the init() method for Applet |
Button b = new Button("Are You Feeling well"); |
add(b); // add() is a Container method |
The various added Components are put in the panel by the LayoutManager using order in this they were added |
A Final critical part of the AWT is the actions generated by these components which are processed by overriding the action() method in Component |
action(Event e, Object Anyargemightliketoreturn); |
We define extra events -- such as those connected with scrolling or selecting buttons to those of basic mouse/keyboard |
This is incomplete! |
add(new Label("aligned left")); // default alignment |
produces a text string using constructor Label of Label class |
add(new Button("Grade is A")); |
add(new Button("Grade is B")); // surely this is lowest grade for a course on such an easy language? |
Checkbox's are on-off toggles implemented as |
add(new Checkbox("Red")); // defaulted to false as initial value which can be changed by user |
add(new Checkbox("Green")); // defaulted to false |
add(new Checkbox("Blue"),null, true); // set to true -- second argument required but ignored here |
Radiobuttons are identical to Checkbox's but grouped so that only one in a group can be on at a time. They use same class for buttons but add CheckboxGroup class |
CheckboxGroup cbg = new CheckboxGroup(); // cbg is group for one set of radiobuttons |
add(new Checkbox("Red", cbg, false)); // cbg is second argument!! |
add(new Checkbox("Green", cbg, false)); |
add(new Checkbox("Blue", cbg, true)); // Only one in group cbg can be true |
Choice is a class that gives a menu where you choose from various items |
TextField is a simple class where user can enter information into fields |
TextArea is a somewhat more sophisticated text entry area which are scrollable and so useful where amount of data to be entered is unlimited |
List is another child of Component that is similar in use to Choice but gives a fixed size list which can be scrolled and where you can select one or more entries |
Scrollbar is a class that defines a horizontal or vertical scrollbar. Note this is distinct from scrollbars that come with TextArea and List |
Canvas is a simple class which are used to draw on as in artist's canvas. They cannot contain other components |
Upto now, we have described how to build typical Applet panels inside browser window. There are classes that allow one to generate complete windows separately from the browser window |
Window Class has subclasses Frame and Dialog |
Frame("TitleofWindow"); // creates a window with memubar and given title
|
MenuBar(); // defines a menubar which can be used in a frame |
Menu("Type"); // defines a menu which can itself have hierarchically defined submemus |
Dialog(Frame, String Title, boolean mustbeansweredatonceornot); // defines a dialog box |
Dialog boxes are used for transient data
|
We already discussed handling Mouse and Keyboard Events. These AWT components come with new actions which need to be handled with an action() method in your applet |
Put action ( a method of class Component) in Container instance that is at lowest possible level so you can customize action to things in that Container |
action(Event evt, Object arg)'s are looked for in same fashion as exceptions. Scan up Containers looking for a method of this name. Scanning stops when you find an action and that method returns true |
evt.target holds the object that caused the Event |
Object Arg returned depends on particular Component invoked |
There are further evt.id's associated with the various peculiar Components -- see description of class Event for current detailed description. |
Suppose we have a bunch of buttons in a particular Container saying Red, Green, Blue as we illustrated earlier. Then a good action method would be |
public boolean action(Event evt, Object arg) { |
if( evt.target instanceof Button)
|
return true; // tell runtime that this event fully processed |
} |
void changeColor(String bname) { // A suitable user routine to be called by above action |
if( bname.equals("Red")) setBackground(Color.red); |
else if (bname.equals("Green")) setBackground(Color.green); |
else if (bname.equals("Blue")) setBackground(Color.blue); |
else setBackground(Color.pink); // our favorite color |
} |
The various panels in a container are laid out separately in terms of their subcomponents |
One can lay components out "by hand" with positioning in pixel space |
However this is very difficult to make machine independent. Thus one tends to use general strategies which are embodied in 5 LayoutManger's which all implement the LayoutManager Interface. One can expect further custom LayoutManager's to become available on the Web |
setLayout(new FlowLayout()); // creates a basic flow layout in your panel -- actually unnecessary as default |
Other available LayoutManager's are GridLayout(), BorderLayout() (default for Frame's), CardLayout() (Used for dynamic layouts) and GridBagLayout() (the most flexible) |
BorderLayout has five cells called North South East West Center and components are assigned to these cells with the add method. As used in a window, one would naturally use:
|
Remember this is default for a Frame Container |
FlowLayout is a one dimensional layout where components are "flowed" into panel in order they wre defined. When a row is full up, it is wrapped onto next row |
GridLayout is a two dimensional layout where you define a N by M set of cells and again the components are assigned sequentially to cells starting at top left hand corner -- one component is in each cell |
GridBagLayout uses a new class GridBagConstraints to customize positioning of individual components in one or more cells |
CardLayout lays out in time not space and each card (Displayed at one time) can be laid out with one of spatial layout schemes above |
Layout's can be made very sophisticated using an hierarchical approach |
setLayout(new GridLayout(1,3,10,5)); // Number of cells in y, Number in x, Horizontal gap, Vertical Gap |
subpanel1 = new MysubpanelClass(); // Add arguments to make subpanel1 special |
subpanel2 = new MysubpanelClass(); |
add(Some Simple Component such as a Button); |
add(subpanel1); |
add(subpanel2); |
.......... |
Class MysubpanelClass extends panel { // has constructor |
MysubpanelClass() { // that includes another layout such as |
setLayout(new GridLayout(7,7,5,5); // etc. |
This area will evolve rapidly as existing I/O systems get linked to Java with special classes such as those needed to link MPI (HPCC Message Passing) or Nexus (Well known distributed memory thread package) |
One can establish Web Connection with URL class and access documents there |
One can set up a more general URLConnection for more general input/output operations through Web(HTTP) protocol |
One can set up a Socket link which is permanent rather than on again off again Web client-server interaction |
One can send messages and so transfer information between different Applets |
One can (outside Netscape) access same functionality as usual UNIX stdio library |
First you set the URL in various ways using something like |
String npacurl = "http://www.npac.syr.edu/index.html"; |
try {theinputurl=newURL(npacurl);} // URL class is in java.net |
catch ( MalformedURLException e) {
|
where you are meant to test to see if URL is legal! |
The simplest thing to do now is to see this page with |
getAppletContext().showDocument(theinputurl, Frame targetdisplayframe); |
More interesting is to access a URL and process the information there! |
This is done using a stdio like stream (generalizes pipe) which is supported in java.io package with usual buffering capabilities |
There are methods in class URL -- InputStream in = url.openStream(); // opens an InputStream associated with given url |
More general is instanceofURL.openConnection() establishes a general connection and returns an instance of class URLConnection
|
Note that one can connect not just to HTML files but also to CGI scripts i.e. programs at server and so obtain flexible connectivity |
In java.io, there are several classes that throw IOExceptions -- please catch them! |
The class InputStream is basic and it has methods such as read() skip() (bytes in a stream) available() (bytes remaining in stream) close(). |
InputStreams can be created from memory |
inputStream s = new ByteArrayInputStream(buffer, 100, 300); // creates a stream of 300 bytes in locations 100 to 399 |
More usefully, they can be created from a UNIX file |
inputStream s = new FileInputStream("/usr/gcf/greatidea"); |
There is a clever class called FilterInputStream which can be used to add value to a raw InputStream. You can define your own filters but important ones provided are:
|
String line; // Here is a useful example |
try { URLConnection conn = npacurl.openConnection(); |
conn.connect(); // could set options after creation of conn in above line and before connect method invoked |
InputStream in = conn.getInputStream(); // establish an InputStream on this connection |
DataInputStream data = new DataInputStream(new BufferedInputSream(in)); // set up two filters allowing both buffering and line access to InputStream |
while ((line = data.readline()) != null ) {
|
} catch (IOException e) {processerror} |
Note one useful exception EOFException which can be caught and remove testing in read loops |
One can essentially augment supplied Java Runtime by supplying your own C or other code implementing a particular functionality in a higher performance mode |
This of course generates machine dependence and should only be used if really needed |
First for classes you wish to implement in native fashion, put in your java code lines like: |
public native mustgofast(arguments); // default functions |
static {System.loadLibrary("faststuffhere");} // static and in class and so runs only ONCE! and loads the native code |
The activities that has gone into defining High Performance Fortran (HPF) and HPC++ can be reexamined for Java which is quite well suited for parallelism as
|
Interesting Compiler challenge independent of parallelism, is to produce efficient code from bytecodes. Here a technique called "just in time" compilation does compilation at runtime and can probably increase performance of Java code by a factor of 10 or so to become comparable with performance of C |
Surely many will produce Fortran C PASCAL to Java translators so you can webify your existing applications
|
Current runtime (java Threads) assume shared memory but there are interesting possible distributed memory and distributed shared memory implementations |
One can imagine a dataparallel interface where methods would implement array and other data parallel operations with distributions specified by annotations as in HPF
|
Important implication for parallel CORBA using Java classes to interface with CORBA |
Java based servers will allow data and task parallel Java to implement World Wide compute webs |