A Quick Java CoursePart 2 Michael McDougall CIS 573 September 29, 1999
Outline • More Basic Java • Exceptions • Packages • This • Static fields and methods • Nice Java tricks • Javadoc • Serializing • GUI Programming • Command-line vs. Event-driven applications • Painting the screen
Exceptions • Exceptions are used to signal errors that can’t or shouldn’t be handled by normal data flow. • Example: imagine a method div(x,y) which returns x/y. What do we return if y=0? • Answer: any integer we return might be misinterpreted. Instead we throw an exception.
Exceptions example class ZeroDivisor extends Exception {} class Div { public int div(int x, int y) throws ZeroDivisor { if (y!=0) { return x/y; } else { throw new ZeroDivisor(); } } }
Exceptions example cont. ... Div d = new Div(); try { int q = d.div(12,4); } catch (ZeroDivisor ex) { System.out.print( “Tried to divide by zero”); } finally { //always executed System.out.print(“Done”); }
Try, catch and finally • If an exception is thrown it percolates back up the call stack until it encounters a catch that matches the type of the exception. • The finally block gets executed whether an exception is thrown or not.
Packages • Java has an enormous amount of pre-defined classes (~1500 in jdk1.2). • For convenience classes are grouped into packages. • Examples: • java.util.Vector • java.security.PrivateKey • You can create your own packages.
How to use classes in packages • Classes in packages can be used just like other classes. You just have to specify the package along with the class name. • Example: • java.util.Vector v = new java.util.Vector();
Packages continued • If you get sick of writing java.blah.blah… all the time you can use import at the top of your file. //top of file import java.util.*; import java.security.PrivateKey; … Vector v = new Vector(); PrivateKey k = new PrivateKey();
This • Often an object needs a way to refer to itself. It can do so by using the this keyword.
This continued Class Foo { public void drawPoint(Point p) { …} } Class Point { public void draw() { Foo f = new Foo(); f.drawPoint(this); } }
Static fields • Usually each object has its own copy of all its fields. A static field is shared by all members of a class. Class Point { public static int count =0; public Point() { count ++; } }
Static methods • Methods can be declared static too. Static methods can only refer to static fields and methods. Class Point { public static float distance(Point p1, Point p1) { return sqrt(…); } }
Static fields & methods cont. • Since static fields and methods are the same for all instances of a class you don’t actually need to create an instance to use them. • Example: • int numOfPoints = Point.count; • Int d = Point.distance(p,q);
Static field example • When we write: System.out.print(“Hi”); “out” is a static field of the System class.
Nice Java Tricks • Javadoc – generating documentation for your java code. • Serializing – writing objects to files.
Javadoc & documentation comments • Javadoc is a program that comes with the Java SDK. It generates HTML from java file. • Javadoc reads special comments called documentation comments and includes them in the HTML. • Javadoc allows you to document your code without maintaining a separate file.
Documentation comments • Documentation comments always always take the form :/** blah blah */
Documentation comments example /** Stores a point in the plane.*/ public class Point { /** the x-coordinate */ public int x; /** the y-coordinate */ public int y; /** Constructs from two integers */ public Point(int a, int b) { x=a;y=b; } /** returns the sum of the coordinates */ public int sum() { return x+y;} }
Javadoc example • Now we use javadoc to generate HTML (-private means include private fields and classes): • %javadoc -private Point.java • Generates HTML files for Point, the class tree, index, etc.
Documentation comment tags • Documentation comments can include tags, which javadoc uses when generating the HTML files. • Tags have the form: @<tagname> • Example: /** An elaborate Point. @author Bob @see BoolPoint */ class SpecialBoolPoint extends BoolPoint { ...
Tags • Some tags that javadoc recognizes • @see getName :link to the javadoc for the getName method • @author Bill : the author of a class • @param x The input integer : gives information about a method parameter. • @return A new point :gives information about the returned value.
Tags cont. • @ version 3.6 : the version of the class. • @ exception BadArg thrown if the argument is bad :information about the exceptions that are thrown by a method.
More about javadoc • The Java Programming LanguageSecond Edition. Ken Arnold & James Gosling, Addison Wesley, 1998. • http://www.javasoft.com/products/jdk/1.2/docs/tooldocs/javadoc/index.html • The javadoc documentation
Serializing • The java.io package has methods that let you write objects to files so that they can be loaded later. • If a class implements the java.io.Serializable interface then you can use the writeObject method of java.io.ObjectOutputStream to convert an object to bytes.
Serializing example Class Point implements java.io.Serializable { public int x; public int y; public Point(int a, int b) { x=a; y=b; } }
Serializing example: saving String fileName = “pointfile”; java.io.FileOutputStream outStream = new java.io.FileOutputStream(fileName); java.io.ObjectOutputStream objOutStream = new java.io.ObjectOutputStream(outStream); Point point = new Point(2,3); objOutStream.writeObject(point); objOutStream.close();
Serializing example:loading String fileName = “pointfile”; java.io.FileInputStream inStream = new java.io.FileInputStream(fileName); java.io.ObjectInputStream objInStream = new java.io.ObjectInputStream(inStream); Point point = (Point) objInStream.readObject(); objInStream.close();
Serializing continued • writeObject() recursively writes all the member fields of an object (including the fields of the fields, the fields of the fields of the fields, etc.) • readObject() just does the reverse. • If writeObject() finds a field that is not serializable it will throw an exception.
Serializing continued • writeObject will work on almost all classes automatically. • Some classes have fields which need special treatment. You have to write special methods for such classes.
GUI Programming Outline • Command-line programs vs. GUI-programs • Event driven paradigm • Why events are tricky • Painting the screen
References • http://java.sun.com/docs/books/tutorial/uiswing/index.html. A tutorial about Swing.
Event driven programs • Most ‘command-line’ programs have the following form. Terminate Start Process Data Print Result OS Your Code Your Code OS
Event driven programs cont. • Event driven programs (like GUI Programs, Servers) have a different form. Start Initialize Wait Process Event Terminate
GUI Events • Possible events: • New HTTP request • Clock Tick • “B” key pressed • Mouse Button Down • GUI Programs typically have a large number of possible events.
Maintaining a stable state • Event-driven programs must leave the computer in a reasonable state whenever you finish processing an event. • This can be tricky if there are a lot of possible events; it is hard to account for all possible streams of events. • Often an unexpected combination of events will make a GUI program go bad.
Event steam example: drawing a line. • Say you want your program to draw a line from one point to another using the mouse and the left mouse button. • Expected event sequence: • Left mouse button down • Mouse move • … • Mouse move • Left mouse button up
Drawing a line continued • The programmer has to implement what happens after each event. • Example: • Button Down -> oldPoint := mousePosition • Mouse Move -> do nothing • Button Up -> create line from oldPoint to mousePosition
Possible problems • What if there is no movement? Do you create an empty line? • What if the user switches to another window before the “Button Up” message never arrives? • What if the keyboard or other mouse buttons are pressed?
Robust Applications • Moral of the story: designing an application that can handle all possible combinations of events can be very difficult. • Things that could help: • A Spin-like specification and some way of verifying it • Conservative programming
Painting the Screen • Drawing on the screen is too slow to be done constantly. • Instead, the operating system redraws parts of the screen as necessary. • Typically the GUI Program receives a “paint” message when the screen should be refreshed.
Painting the screen continued • In the Java Swing library the javax.swing.JComponent class is the superclass for most window classes. • When the Operating System wants to repaint the screen the JComponent.paint() method is called.
Paint method example public void paintComponent(Graphics inG) { Point startPoint = getStartDragPoint(); Point endPoint = getCurrentDragPoint(); inG.setColor(Color.blue); inG.drawRect(startPoint.x, startPoint.y, endPoint.x - startPoint.x, endPoint.y - startPoint.y); }
Interacting With the Screen Button Pressed Event Repaint Event … L=new Line(p1,p2); repaint(); … void paint(Graphics g) { drawLine(L); } Wait Wait
Repainting • If you know that the screen is out of date and should be refreshed you can call JComponent.repaint(). This ensures that the window will be repainted sometime in the future.
Concurrency