Java Tutorial, May 14, 1996 The Java Programming Language 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 Most of the books cited earlier have CDROM's with examples or the JDK. Java Language Discussion -- Table of Contents Program Structure Lexical Issues Applet versus Application Variables and Expressions Types and Array Control Flow Object Model and Classes Methods Interfaces Exceptions This is followed by discussion of Implementation in terms of Applet Programming, Threads, Graphics and the Abstract Windowing Toolkit, Networking and I/O, Native classes, HPCC implications Program structure and the simplest examples Java Language -- Program Structure Source code of a Java program consists of one or more compilation units, implemented as files with .java extension. Each compilation unit can contain: a package statement import statements class declarations interface declarations 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 , it will download Foo.class and Fred.class files and it will start interpreting bytecodes in Foo.class. Java Language -- Lexical Issues I 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: // ignore all till the end of this line /* ignore all between starts */ /** an insert into an automatically generated software documentation */ for /** */ one inserts HTML documentation with some simple macros such as @see (to designate see also) BEFORE the method or class being documented Java Language -- Lexical Issues II 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 Versus Applets - I 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 Applications Versus Applets - II 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 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! Hello World Applet from Sun Tutorial Getting Started This prints in applet window, the classic Hello World string! import java.awt.Graphics public class HelloWorld extends java.applet.Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } } g which is of class Graphics, is window in which applet runs (i.e. is displayed) Hello World Application from Sun Tutorial Getting Started This is "application" version of previous applet class HelloWorldApp { public static void main (String args[]) { System.out.println("Hello World!"); } } Note args are of class String and needed even though HelloWorldApp has no command line arguments Java Language Basics Java Language -- Variable/Expression Types 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. Note booleans are either TRUE or FALSE -- they are not 0, 1 ,-1 ... 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++. Java Language -- Types: Array An Array is declared as: int vec[]; and created by: vec = new int[128]; or concisely: int vec[] = new int[128]; 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. int len = vec.length will assign len = 128. Arrays of arbitrary objects can be constructed, e.g. Thread myThreadList[] = new Thread[1024]; Arrays can have dynamic sizing int sizeofarray = 67; int vec[] = new int[sizeofarray]; Java Language -- Expressions 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 */ Java Language -- Control Flow I if(some boolean expression) { .. } else if(another boolean) { .. } else { ... } while(any boolean) { /* Do Stuff */ } do { /* What to do */ } 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; } Java Language -- Control Flow II -- continue 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 */ for( int i=0; i<15; i++) { if(studentgrade[j][i] == 4.0) { /* Celebrate */ continue outer; // go to next iteration of outer loop } } /* Continue jumps to here to next iteration of loop labelled with outer */ } Java Language -- Control Flow III -- break and for loop 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 */ for( int i=0; i<15; i++) { if(studentgrade[j][i] == 4.0) { /* Celebrate */ break outer; // go to end of outer loop } } } /* break jumps to here out of loop labelled by outer */ Java Language -- Control Flow IV -- break and switch loopstart: // label for( int j=0; j <10; j++) { switch(j) { case 3: break; default: if( studentgrade[j] == 2.5) break loopstart; /* go to end of loop */ /* do some stuff */ break; } } /* break loopstart goes to here out of loopstart loop */ Java Language -- Control Flow V -- continue and switch loopstart: // label of following for loop for( int j=0; j <10; j++) { switch(j) { case 3: break; default: if( studentgrade[j] == 2.5) continue loopstart; /* go to next iteration of loop */ /* do some stuff */ break; } // End Switch Block /* continue loopstart goes to here for next iteration of loopstart loop */ } // End loopstart for loop The Java Object Model: Classes, Instances and Methods The Java Object Model Overview 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 { public int x, y; /* Instance Variable */ public int dx = 1, dy = 1; /* More Instance Variables */ Both class and its instance variables can be accessed by all other java objects Date Application from Sun Tutorial Anatomy of an Application 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 { public static void main (String args[]) { Date today = new Date(); System.out.println(today); } } Counting Application from Sun Tutorial Nuts and Bolts of Java This application reads from standard input and counts number of characters which are then printed class Count { public static void main(String args[]) throws java.io.IOException { int count = 0; while (System.in.read() != -1) count++; System.out.println("Input has " + count + " chars."); } } Java Language -- Overview of Classes 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 Instantiating an Object from its Class 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 { int x, y; int dx = 1, dy = 1; Color color = Color.black; } Constructors of Objects Methods of identical name to class are special -- they are constructors mPoint() { /* Default Constructor */ x=0; y=0; } 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 */ this.x = x; this.y = y; } 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) { dx = _dx; dy = _dy; } /* where we don't need this as used _dx, _dy */ Class Finalizers 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() { try { file.close(); } catch (Exception e) { /* Catches ANY exception */ } } Earlier one might have set this up with syntax such as that on next foil Java Language -- Types of Classes 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 will not have accesses interrupted by any other threads running in parallel Java Language -- Methods MethodModifier ReturnType Name(argType1 arg1, ......) Returntypes are either simple types (int, byte etc.), arrays or class names Possible MethodModifiers are: public -- This method is accessible by all methods inside and outside class protected -- This method is only accessible by a subclass private -- This method is only accessible to other methods in this class friendly(i.e. empty) -- This method is accessible by methods in classes that are in same package final -- a method that cannot be overriden static -- This method is shared by ALL instances of this class and can be invoked with .method syntax as well as .method synchronized -- This method locks object on entry and unlocks it on exit. If the object is already locked, the method waits until the lock is released before executing native -- to declare methods implemented in a platform -- dependent language, e.g. C. A little more complicated Paint Method for Applets 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); } } Some More Methods for mPoint import java.awt.*; /* Imports Graphics Method for display */ public class mPoint { /* Continue as before and add */ public void setColor(Color color) { this.color = color;} public void checkBoundry(Rectangle rect) { /* check if object crosses boundary */ int nx = x+dx; /* caculate new location */ int ny = y+dy; if ( (nx < rect.x) || (nx >= rect.x+rect.width) ) dx = -dx; if ( (ny < rect.y) || (ny >= rect.y+rect.height) ) dy = -dy; } public void move(Graphics g) { /* move object */ paint(g); /* use XOR to hide object */ x += dx; /* update location */ y += dy; paint(g); /* draw object on new location */ } public void paint(Graphics g) {} } The Java Object Model: Inheritance and the Class Hierarchy, Interfaces, and Packages Inheritance or Subclassing 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 { int w, h; public mRectangle(int _x, int _y, int _w, int _h) { super(_x, _y); /* call mPoint's constructor */ w = _w; h = _h; } /* End mRectangle Constructor */ /* overwrite the mPoint's checkBoundry method */ public void checkBoundry(Rectangle rect) { int nx = x+dx; int ny = y+dy; if ( (nx < rect.x) || (nx+w >= rect.x+rect.width) ) dx = -dx; if ( (ny < rect.y) || (ny+h >= rect.y+rect.height) ) dy = -dy; } public void paint(Graphics g) { /* Override mPoint Method */ g.setColor(color); g.drawRect(x, y, w, h); } } Use of Methods Defined in Parent Call to method in Object2 (message) from object1 is passed up the class hierarchy until a definition is found Use of Methods Defined in Parent but overridden in child class Call to method in Object2 (message) from object1 is passed up the class hierarchy until a definition is found Java Language -- Interfaces 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 { void print(); void print(String str); } class Cookie implements Printable { void print() { System.out.println("Cookie"); } } class WastePaper implements Printable { void print(String str) { int i,len=str.length(); for(i=0; i < len; i++) { singlechar = str.charAt(i); System.out.println("This is character No." + i + " " + singlechar); } } } Cars as an Examples of Interfaces/ Multiple Inheritance 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 Picture of Interfaces and Classes for Cars and their Manufacture Cars MyFordMustang = new Cars(Lots of Options) is a particluar instance of class Cars More on Interfaces -- II 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: More on Interfaces -III- Real Examples 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 Overview of Packages 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 import cps616.* at beginning of file that neededs classes from cps616 package In this case classes in cps616 package can be refered to by just using their Classname Without import command, one must explicitly say cps616.Classname Java System Packages 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 Useful Basic Classes The Overarching Object Class 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) Determining and Testing Class of Object 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 java.lang.Object Wrappers "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); ReverseString Class from Sun Tutorial The String and StringBuffer 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 { public static String reverseIt(String source) { int i, len= source.length(); StringBuffer dest = new StringBuffer(len); for( i= (len-1); i >=0 ; i--) { dest.append(source.charAt(i)); } return dest.toString(); } } 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 Summary of Object-Oriented Concepts Summary of Object-Oriented Concepts - I 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 Summary of Object-Oriented Concepts - II 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 More on the Java Language: Exceptions Java Language -- Handling Errors Using Exceptions 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 { try { call method2; } catch (Exception3 e) { doErrorProcessing(e); } } method2 throws Exception3 { call method3; } method3 throws Exception3 { call dividebyzeroorreadfileorsomething; } Examples of Exception Hierarchy As Examples of hierarchy: catch(InvalidIndexException e) { .. } would catch particular exception whereas catch(ArrayException e) { .. } would catch all Arrayexceptions Handling Exceptions in Closing a File File file; /* defines file to be object of class File */ try{ file = new File("filenameyouwant"); ....... file.write("stuff put out"); } 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 { file.close(); }