Home

Online version 3.4

image

Contents

1. eese nennen nennen nre 288 25 1 2 25 R nd Oitmn tret tn Reset eerte ri e ut Eee eere ee tee ta cete te o 288 25 1 2 26 Resource Bundle ics ene eee tege be eee caleta 288 25 1 2 27 Simple FimeZone re aee re ER eh ESO n eH TE Rente ede 288 25 1 2 28 Stack qu 288 25 1 2 29 String POKCmI Zeiss A chute A AE E 288 25 1 2 30 TIMEZONE it dan ene 288 25 1 2 31 Kc UL O 288 25 1 2 32 BAIT 288 25 1 2 33 O E 288 25 1 2 34 WeakHash AA ieee neasaeepinies EE EE EEE EEE eis posits 288 25 1 3 Exception SUMMALY iaa tar 289 25 1 3 1 ConcurrentModificationException esses nennen nennen nete nennen 289 25 1 3 2 EmptyStackBXCepton sit teeth e tbe eee de eere ete ape eroe pow eR pea 289 25 1 3 3 MissingResoutce Exception i needed e ee EE ER ERR CORE HER 289 25 1 3 4 NosuchElementException 2 1 2 2 bosta ea epopee p cc ks oppo Leo iii aenak 289 25 1 3 5 TooManyListenersException esee entente ene nennen enne nnne 289 25 2 IIDHIOEPADIYSi curio tuere oet opt avere o vene Epoca EE eE EE ESE decedens 289 26 Package java A Wi a aida 292 26 1 Package Java dwt dnd JDK ll Acacia io 292 26 1 1 Interface SUOMI il tada 292 26 1 1 1 Autoscroll enna ann tia Iaido 292 26 1 1 2 DragGestureListenet v acne cte A EEA E E EE new asides 292 26 1 1 3 Drag sourceListener init illa 292 26 1 1 4 Drop Targethistemer neneda erea a e Hee eee eet ec et sees 292 26 1 2 Class Summary nene ere iet eb Lee degeret i ee 292 26
2. This example is very similar to the previous but now we don t have the enclosing try catch block Try running both of the programs to see what happens We will come back to the concept of exception handling in much greater depth throughtout the course 5 4 References You should be aware by now of the difference between the built in basic Java data types byte short int long etc and objects When we work with i o for example we have the following conversion taking place when we need to get read in a floating point number String gt Float gt float A String an object and whenever we use a String variable we are actually using a reference to the corresponding object Object references are null when they don t actually refer to any thing For people with a knowledge of pointers this will be quite familiar This has some interesting implications for the operator Try running the following pro gram import java lang class cO public static void main String args String sl s2 s1 Hello s2 Hello if sl s2 System out println 1 email ian chivers kcl ac uk O Ian D Chivers Chapter 5 Strings 88 sl s2 if sl s2 System out println 2 if sl Hello System out println 3 What do you think the output will be 5 5 Unicode Java is of course Unicode based Some knowledge of Unicode is required for successfully using Java with characte
3. eese enne nennen nennen nennen rine 245 15 6 A 55 cee So edenda eset E ER hr UE 245 18 7 Vili TAP N Rr LP Em 245 19 IBM VasualA for Java siii bi aaepe edv de bie eiii bit 248 19 1 Health Warning Veis cott ete oa te ee etes co da ORE Ee e Ped Dae Ria colinda 248 19 2 Mersions and Aval lab uis ts acu Md einn 248 19 2 1 VisualAge Object Connection Partners CD Version 2 0 1 eese 248 19 2 2 MindQ Introduction to VisualAge for Java esee 248 19 2 3 Alpha WOEKS 4 eet AN 248 19 2 3 1 alphaWorks History The Launch eere 248 19 2 4 Other Offerings nette aeree eter et ete e eet eere eee ete Sletten 249 19 5 DocunientatiOb cott td See e cec AE UAE 249 Contents 11 19 3 1 IDE Basics Concepts and Tasks 34 pag8S ooooonnconccnnocinocnnonononcnoncnnncnnncnnnana nono ncnnacnnccnns 249 19 3 2 Getting Started 144 pages ertet e seen licor 249 19 3 3 Visual Composition Concepts and Tasks 267 pagES oooconcnnnnnnocnnnncnnncnnnannonancnnncnnccnns 250 19 3 4 Data Access Concepts and Tasks 61 pages 250 19 3 5 SCM Tools Concepts and Tasks 16 pages 250 19 3 6 AgentRunner Concepts Tasks and Samples 25 pages eee 250 19 3 7 Tool Integrators 20 pdges npe eee re RUP e parole RE eyes 250 A A ON 250 19 3 A M P 250 19 6 Starting up Visual Age for JaVa siete scavtuancotsyneaganssigesagen Shes save soesanneghaa Pav eee adus 251 E A dori R v
4. load the image when the applet begins executing public void init Container c getContentPane c setLayout new FlowLayout email ian chivers Q kcl ac uk O Ian D Chivers Chapter 20 String choices chooseSound new Multimedia 256 Welcome JComboBox Hi s choices chooseSound addItemListener new public void ItemListener itemStateChanged ItemEvent e currentSound stop currentSound chooseSound getSelectedIndex 0 soundl sound2 c add chooseSound ButtonHandler handler new ButtonHandler playSound new JButton Play playSound addActionListener handler c add playSound loopSound new JButton Loop loopSound addActionListener handler c add loopSound stopSound new JButton Stop stopSound addActionListener handler c add stopSound soundl getAudioClip getDocumentBase welcome wav sound2 getAudioClip getDocumentBase hi au currentSound soundl stop the sound when the user switches Web pages i e be polite to the user public void stop currentSound stop private class ButtonHandler implements ActionListener public void actionPerformed rf Ian D Chivers lse if lse if e getSource ActionEvent e playSound currentSound play
5. public static void main String args ToolbarFrame4 tf4 new ToolbarFrame4 tf4 setVisible true Points to note a separate handler class the import of java awt event the import of javax swing the class extends Frame each of the buttons is a JButton explicit call to super class constructor add the window listener create a panel with layout set up the three buttons create a new panel set up the three look and feel buttons 13 5 1 Frames public class Frame extends Window implements MenuContainer A Frame is a top level window with a title and a border 13 5 2 super Constructor Chaining super is a reserved word in Java One of its uses is to call the constructor of a superclass This is what we have in this example 13 6 Example 2 This is taken from the Deitel book Fig 6 9 Craps java Craps import java awt import java awt event import javax swing O Ian D Chivers email ian chivers Okcl ac uk 209 Events Chapter 13 public class Craps extends JApplet implements ActionListener constant variables for status of game final int WON 0 LOST 1 CONTINUE 2 other variables used in program boolean firstRoll true true if first roll int sumOfDice 0 sum of the dice int myPoint 0 point if no win loss on first roll int gameStatus CONTINUE game not over yet graphical user interface components JLabel diellabel die2Label sum
6. 12 2 Label import java awt public class c1111 extends java applet Apple public void init Font f new Font Arial Font PLAIN 20 setFont f add new Label QPR add new Label Arsenal add new Label Spurs 12 3 Button and Label import java awt public class c1112 extends java applet Apple public void init Font f new Font Arial Font PLAIN 20 setFont f add new Button qpr A add new Button arsenal add new Button spurs add new Button chelsea add new Label OPR O lan D Chivers email ian chivers Okcl ac uk 191 AWT Based Windows Programming Chapter 12 add new Label Arsenal add new Label Spurs 12 4 Scrollbar import java awt public class c1113 extends java applet Applet public void init add new Scrollbar add new Scrollbar Scrollbar HORIZONTAL 12 5 Scrollbar with size information import java awt public class c1114 extends Java applet Applet public void init add new Scrollbar add new Scrollbar Scrollbar HORIZONTAL 10 50 1 50 12 6 Checkbox import java awt public class c1115 extends java applet Applet public void init Font f new Font Arial Font PLAIN 20 setFont f add new Checkbox OPR null true add new Checkbox Arsenal
7. analysis build a model of the real world situation system design make the high level decisions about the overall architecture object design build a design model based on the analysis model with imple mentation details implementation translate into an implementation using a particular programming language database or hardware implementation and three kinds of models to describe the system the object model describes the static structure of the objects and their relation ships the dynamic model describes the aspects of the system that change with time the functional model describes the data value transformations within the system and the three models are orthogonal with cross links This book is a must for large scale systems 2 02 3 Practical Steps The two major practical steps are identify the classes within this discriminate between an is a relationship e g where one class is a sub type of another Consider the concept of a point It has two attributes an x and y position So we could write point x y Now consider the concept of a pixel a point with the O Ian D Chivers email ian chivers kcl ac uk 37 An Introduction to Programming Languages Chapter 2 and Object Oriented Programming added attribute of colour Now we could write pixel point colour Thus pixel is a point a has a relationship e g where a class is made up of an object of another class Consider the concepts of engine an
8. try for System out printin Thread currentThread getName Thread sleep delay catch InterruptedException e return 10 5 Example 5 static variable in a thread This example looks at some of the problems that can occur when using static variables public class thread05 extends Thread static int i public static void main String args thread05 tl new thread05 thread05 t2 new thread05 tl start t2 start email ian chivers Q kcl ac uk O Ian D Chivers Chapter 10 Threads 134 public void run for i 0 i if i 0 System out print Thread currentThread getName System out print ny s System out printin i 10 6 Example 6 synchronized This example shows how to avoid potential problems when updating static class variables public class thread07 extends Thread static int i public static void main String args thread07 tl new thread07 thread07 t2 new thread0O7 tl start t2 start public void run for synchronized this i 0 i if i 0 Sys tem out print Thread currentThread getName System out print UP he System out printin i Ian D Chivers email ian chivers kcl ac uk 135 Threads Chapter 10 10 7 Example 7 yield This example shows how to get a degree of predictabili
9. The run method gets the name of the cuurently executing thread and then calls the sleepmethod with the corresponding value for delay 10 3 Example 3 implements Runnable The next two examples are simple variants of the first two examples They utilise the sec ond way of using threads in Java The first way uses simple class extension This way is not appropriate for many problems The following example allows us to subclass another class 1f we want The drawback with this way of doing things is that the Runnable interface does not provide start stop suspend and resume methods the only method implemented is the run method public class thread03 implements Runnable public static void main String args Runnable tl new thread03 Runnable t2 new thread03 new Thread tl start new Thread t2 start public void run for System out printin Thread currentThread getName Let us look at this example now 10 4 Example 4 Implements Runnable This is the equivalent way of doing the second example O lan D Chivers email ian chivers Okcl ac uk 133 Threads Chapter 10 public class thread04 implements Runnable int delay thread04 int t delay t public static void main String args Runnable tl new thread04 50 Runnable t2 new thread04 100 new Thread tl start new Thread t2 start public void run
10. return new File dirname public static void main String args if args length 2 System err prin System err prin Usage java FileCopy source filej destination file else try copy args 0 args 1 catch IOException e System err println e getMessage email ian chivers Q kcl ac uk O Ian D Chivers Chapter 8 Exceptions 116 class FileCopyException extends IOException public FileCopyException String msg super msg Let us look at this example in some depth Copying files is a frequent requirement so it makes sense to make the file copy method that does the work public This means we can easily incorporate this fully tested method in another program with ease In this example we have a main method and thus it is a standalone program There are a number of errors that can occur incorrectly typed source file name incorrectly type destination file name in the wrong part of the directory structure destination file already exists don t have write access to the file don t have write access to a directory The program copes with all of these situations The file is treated as a sequence of bytes the most flexible way of handling both text and binary files Let us look first at the FileCopy copy method public class FileCopy public static void copy String source_name String dest_name throws IOException The copy method is publ
11. Renders the text of the specified String using the current Font and Paint attrib utes in the Graphics2D context abstract void fill Shape s Fills the interior of a Shape using the settings of the Graphics2D context void fill3DRect int x int y int width int height boolean raised Paints a 3 D highlighted rectangle filled with the current color abstract Color getBackground Returns the background color used for clearing a region abstract Composite getComposite Returns the current Composite in the Graphics2D context abstract GraphicsConfiguration getDeviceConfiguration Returns the device configuration associated with this Graphics2D abstract FontRenderContext getFontRenderContext Get the rendering context of the Font within this Graphics2D context abstract Paint getPaint Returns the current Paint of the Graphics2D context abstract Object getRenderingHint RenderingHints Key hintKey Returns the value of a single preference for the rendering algorithms abstract RenderingHints getRenderingHints Gets the preferences for the rendering algorithms abstract Stroke getStroke Returns the current Stroke in the Graphics2D context abstract AffineTransform getTransform Returns a copy of the current Transform in the Graphics2D context abstract boolean hit Rectangle rect Shape s boolean onStroke Checks whether or not the specified Shape intersects the specified Rectangle which is in device space abstract void
12. add new JLabel QPR add new JLabel Arsenal add new JLabel Spurs email ian chivers Okcl ac uk O Ian D Chivers Chapter 14 Swing 218 Compile and run this example Compare with the AWT equivalent 14 10 3 Button and Label import import java awt javax swing public class s1412 extends java applet Applet public void init Font f new Font Arial Font PLAIN 20 setFont f add new JButton gpr add new JButton arsenal add new JButton spurs add new JButton chelsea add new JLabel QPR add new JLabel Arsenal add new JLabel Spurs 14 10 4 JScollBar import import java awt javax swing public class s1413 extends java applet Applet public void init add new JScrollBar add new JScrollBar JScrollBar HORIZONTAL 14 10 5 JScrollBar with size information import java awt import javax swing public class s1414 extends java applet Applet public void init t add new JScrollBar add new JScrollBar JScrollBar HORIZONTAL 10 30 1 50 The parameters changed for the second form of the constructor Check the on line docu mentation for details Ian D Chivers email ian chivers kcl ac uk 219 Swing Chapter 14 14 10 6 CheckBox import java awt import javax swing public class s1415 extends java applet A
13. con QPR Arsenal Spurs Chelsea West Ham Crystal Palace email ian chivers Okcl ac uk 195 AWT Based Windows Programming Chapter 12 12 12 5 GridBagLayout import java awt public class c1133 extends java applet Applet public void nb String s GridBagLayout gb GridBagConstraints gbc Button b new Button s gb setConstraints b gbc add b public void init layout using the GridBagLayout mananger plus constraints Font f new Font Arial Font PLAIN 18 setFont f GridBagLayout gb new GridBagLayout GridBagConstraints gbc new GridBagConstraints setLayout gb gbc gridwidth 4 gbc gridheight 4 gbc weightx 4 0 gbc fill GridBagConstraints HORIZONTAL gbc gridwidth GridBagConstraints REMAINDER nb Goalkeeper gb gbc gbc weightx 1 0 gbc fill GridBagConstraints NONE gbc gridwidth 4 nb Right back gb gbc nb Centre Half gb gbc nb Centre Half gb gbc gbc fill GridBagConstraints HORIZONTAL gbc gridwidth GridBagConstraints REMAINDER nb Left back Pgbygioc 12 12 6 CardLayout This layout manager stacks things like a deck of cards Only the top is visible import java awt CardLayout import java awt public class c1134 extends java applet Applet email ian chivers Q kcl ac uk O Ian D Chivers Chapter 12 AWT Based Windows Programming 196 layout us
14. Exceptions enable us to move towards overall program correctness without writing code that is unintelligible Let us look at examples in a couple of programming languages of reading user input Fortran 90 for example has the concept of implicit gotos via the END and ERR options and also the concept of IOSTAT returing a value to let you know something has gone wrong Pascal and Modula 2 have the concept of EOLN and EOF The following are coding examples that read all input from a user until they type CTRL Z end of file The first is in Pascal the second in Fortran 90 and the third in C The exam ples also highlight the quite different ways that languages have in their handling of end of line and end of file 8 1 Linked List Pascal PROGRAM LinkedList INPUT OUTPUT TYPE Link Node Node RECORD C CHAR Next Link END VAR Root Link Current Link BEGIN NEW Root READ Root C Ian D Chivers email ian chivers kcl ac uk 109 ENI Current Root WHILE NOT EOF BEGIN Exceptions Chapter 8 DO NEW Current Next Current Current Next READ Current C END Current Next NIL Current Root WHILE Current BEGIN NIL DO WRITE Current C Current Currentf Next END Die 8 2 Linked List Fortran 90 PROGRAM C20 01 Simple linked list TYPE Link CHARACTER C TYPE Li
15. Ian D Chivers Chapter 12 add add add add new new new new Bu Bu Bu Bu 12 12 3 GridLayout This layout manager divides the screen into a grid of rows and columns Objects are added AWT Based Windows Programming Spurs Chelsea West Ham Crystal Palace at the top left and we move horizantally until the row is full import java awt public class c1131 extends java applet Applet public void init layout using the GridLayout mananger Font f new Font Arial Font PLAIN 20 setFont f setLayout new GridLayout 4 2 add n add add add add add ew ew ew ew ew ew B UJ UJ UJ UJ UJ con con ton con con con 12 12 4 Gridlayout with size Similar to GridLayout but now the components can vary in size import java awt public class c1132 extends java applet Applet public void TADEO QPR Arsenal Spurs Chelsea West Ham Crystal Palace layout using the GridLayout mananger Font f new Font Arial Font PLAIN 20 setFont f setLayout new GridLayout 4 2 10 10 add add add add add add n n n n n n ew ew ew ew ew ew O Ian D Chivers B UJ UJ UJ UJ UJ con con con con con
16. Note that does not mean that the section of code cannot be timesliced We have a lock set and access cannot be made to whatever the lock has been applied until it has completed If you would like more information see the bibliography at the end of the chapter on threads 9 7 Example 1 The following is a C program to extract all of the ASCII characters from a Microsoft Word file tinclude lt iostream h gt int main unsigned char c unsigned int i 0 while cin get c i tti TE qoe x3 c gt 127 eremo a cout c if i gt 60 amp amp c cout lt lt endl i 0 return 0 The following is a modification to the file copy program that does the same This example is a simple modification of the earlier example on file copying It has been rewritten to extract all of the ascii characters from a Microsoft Word document db This example is from the book _Java in a Nutshell_ by Da vid Flanagan Written by David Flanagan Copyright c 1996 O Reilly amp Associates You may study use modify and distribute this example for any purpose This example is provided WITHOUT WARRANTY either expressed or implied import java io O Ian D Chivers email ian chivers Okcl ac uk 125 i o Chapter 9 public class convert public static void copy String source_name String dest_name throws IOException File source file
17. 19 1 18 2 0 20 19 39 20 40 This means that there is quite a gap between the representation of a problem in the real world and its solution in Java or C or c for that matter As this is one of the major sources of errors getting into our programs it means that Java isn t well suited to the solu tion of many common mathematical problems 6 5 Example 5 2 d array initialisation In this example we look at array initialisation class c0605 public static void main String args int a y for int row 0 row lt 2 row for int column 0 column lt 3 column system out System oul System out printin prin prin a row column N nys 6 6 Whole Array Manipulation There is no whole array manipulation mechanism in Java and it shares this with C However in C we can through the use of classes and operator overloading provide this functionality for one dimensional arrays whilst still using the standard C array indexing notation i e We can also extend this to multi dimensional arrays in C using the no tation Thus Fortran 90 has very clear advantages over both Java and C in the mathematical area email ian chivers Q kcl ac uk O Ian D Chivers Chapter 6 Arrays In Java 96 6 7 Summary There are some problems with arrays in raw Java and the main one is the machine oriented array dimensioning rather than physical world array dimensioning e g
18. 50 add new JLabel Who is your favourite player add new JTextField 20 14 10 10 Passwords import java awt import javax swing public class s1419 extends java applet Applet public void init add new JLabel Type in your password JTextField t new JTextField 20 t setEchoCharacter add t This example won t compile Have a look at the on line documentation and make the neces sary changes to make it work 14 10 11 TextArea import import java awt javax swing public class s1420 extends java applet Applet public void init String s This is some text that is going n to spread over several lines n and use the control characters for n end of line as in c and c add new JTextArea s 10 10 14 11 Layout O lan D Chivers email ian chivers kcl ac uk 221 Swing 14 11 1 Panels Chapter 14 A Panel is the simplest container class A panel provides space in which an application can attach any other component including other panels 14 11 2 FlowLayout import java awt import javax swing public class s1430 extends java applet Applet public void init layout using the FlowLayout mananger Font f new Font Arial Font PLAIN 20 setFont f setLayout new FlowLayout FlowLayout LEFT add new JButton QPR add
19. Java 1 3 increases the support considerably in this area 20 4 Problems Try the example out on the pc You obviously need a sound card and speakers Have a look at what sounds Microsoft provide Can you get them to play email ian chivers Q kcl ac uk O Ian D Chivers 21 Simple Networking Aims The aims of this chapter are to provide a brief coverage of networking Chapter 21 Simple Networking 260 21 Simple Networking This chapter looks at using Java for networking 21 1 Package java net Since JDK1 0 Provides the classes for implementing networking applications Using the socket classes you can communicate with any server on the Internet or implement your own Internet server A number of classes are provided to make it convenient to use Universal Resource Locators URLs to retrieve data on the Internet 21 1 1 Interface Summary ContentHandlerFactory This interface defines a factory for content handlers FileNameMap A simple interface which provides a mechanism to map between between a file name and a MIME type string SocketImplFactory This interface defines a factory for socket implementations SocketOptions Interface of methods to get set socket options URLStreamHandlerFactory This interface defines a factory for URL stream protocol han dlers 21 1 2 Class Summary Authenticator The class Authenticator represents an object that knows how to obtain au thentication for a network connection ContentHand
20. NAVIGATION OR COMMUNICATION SYSTEMS AIR TRAFFIC CONTROL DI RECT LIFE SUPPORT MACHINES OR WEAPONS SYSTEMS IN WHICH THE FAIL URE OF THE SOFTWARE COULD LEAD DIRECTLY TO DEATH PERSONAL INJURY OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE HIGH RISK ACTIVITIES SUN SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES Ef import java util Hashtable import java applet import java io import java awt import java net email ian chivers Q kcl ac uk O Ian D Chivers Chapter 11 author x version i Jonathan Payne oT o o 19 lt G class Bouncelmage tatic oat inelasticity tatic loat Ax 0 0 tatic loat Ay 0 0002f tatic loat Qu ofs eT cer CT E f f f Ann nD lic lic lic Tte lic lic Tire lic Vx Ouse 0 05f TOTO COFCO 8 0 0052 0 001 O n O 0 0 0 0 0 O O o ic float findex Of Bounceltem parent Introduction to Graphics Programming static boolean public void play int n if parent sounds n imagesReadI 182 96f float Math random
21. The next thing of interest is the array indexing This goes from 0 through 11 A little odd at first but don t panic We are used to arrays starting at 1 naturally this is the first element Zero didn t exist in mathematics for quite some time However BASIC is a programming language that offers arrays starting at O and 1 as an option in most implementations Lets look now at the for loop in Java The general sytax is O Ian D Chivers email ian chivers Okcl ac uk 93 Arrays In Java Chapter 6 for inital statement i expression 1 7 expression 2 statement The initial statement normally sets up an initial value for the loop counter In this case month Expression 1 is the loop control mechanism In this case we are interested in stopping once we have processed all 12 months Expression 2 is normally the loop counter increment mechanism In this case increment by one statement is the statement that will be executed whilst expression 1 is true We will look in more detail at the for statement in a later chapter for month 0 month lt 12 month sum sum rainfall month Here we calculate the sum using a simple for loop again Finally we calculate and print out the average 6 2 Example 2 Variant on 1 using alternate syntax class c0602 public static void main String args float sum float 0 0 average float 0 0 float rainfall new float 12 int month System out println Rainf
22. There are a couple of examples in this chapter 21 2 1 Manipulating urls ke import java awt import java net import java applet Applet public class network01 extends Applet Site sites public void init sites new Site 60 sites 0 new Site Home http www kcl ac uk kis support cc fortran sites 1 new Site Fortran 90 http www kcl ac uk kis support cc for tran f90home html sites 2 new Site Cc email ian chivers Q kcl ac uk O Ian D Chivers Chapter 21 Simple Networking 262 http www kcl ac uk kis support cc for tran cpp cpp html sites 3 new Site Java http www kcl ac uk kis support cc for tran java javahome html sites 4 new Site Compiler support on Gum http www kcl ac uk kis support cc fortran com piler html sites 5 new Site Scientific Data Management http www kcl ac uk kis support cc fortran data base database html for int i 0 i sites length i add new Button sites i getTitle public boolean action Event e Object arg if e target instanceof Button String title URL location for int i 0 i lt sites length i title sites i getTitle location sites i getLocation if title equals arg toString gotoSite location return true event handled return false event not handled yet public void gotoSite
23. ball new Thread this ball start public void stop if ball 2null ball stop ball null public void run for 7 O lan D Chivers email ian chivers Okcl ac uk 143 Introduction to Graphics Programming Chapter 11 xt deltax yt deltay if x gt x1 x lt 0 deltax deltax if y yl y lt 0 deltay deltay repaint try Thread sleep 1 catch InterruptedException e public void paint Graphics g g setColor Color blue g fillOval x y 20 20 Compiling with deprecation and JDK 1 2 2 generates a warning about stop 11 17Example 3 Bouncing Balls with double buffering import java awt simple bouncing ball this example uses an off screen area to do the update this technique is common in graph ics and is called double buffering the other technique that this example show is that of so called selectiv rasure This is an other common programming technique in the graphics area rather than repaint the whole screen only the part that has to change is redrawn again worth looking at the sleep times the example has one small snag the selectiv ras doesn t work correctly public class graphic02 extends java applet Applet implements Runnable double x y deltax deltay oldx oldy double x1 300 double y12300 Thread ball
24. java io java lang Float class c0706 public static void main String args float tol float 1 0E 6 float term float 1 0 x float 0 0 etox float 1 0 int nterm 0 Float X new Float x String Line try InputStream i System in DatalnputStream I new DataInputStream i System out printin Type in a number Line I readLine X Float valueOf Line x X floatValue do nterm 1 term x nterm term etox term while term gt tol catch IOException e System out println Exceptions raised e System out println etox email ian chivers Q kcl ac uk O Ian D Chivers Chapter 7 Control Structures 102 7 9 for init statement expression 1 expression 2 statement Equivalent to the DO loop in Fortran or FOR loop in the Pascal family of languages Note that must be used when multiple statements need to be executed ini statement may be declaration or an expression This enables us to introduce for loop control variables at the time we set up the for loop Some people love the ability to intro duce variables in this way others hate it It is the way it is The following highlight this point for int i 0 Declare i and initialise to 0 for i1 0 1 must have been declared prior to this statement expression 1 is the loop control mechanism As long as this is true the for statement will be executed e
25. n false null parent sounds n play public Bouncelmage Bounceltem parent this parent width 65 height JS parent void move float xl x1 yl public x y public void paint Graphics ine E index LE 3i 0 g drawImage parent bounceimagesli null O lan D Chivers parent bounceimages i float yl g null int x int y email ian chivers kcl ac uk 183 Introduction to Graphics Programming Chapter 11 public void step long deltaT boolean collision_x false boolean collision_y false float jitter float Math random 01f 005f x Vx deltaT Ax 2 0 deltaT deltaT y Vy deltaT Ay 2 0 deltaT deltaT if x lt 0 0 x 0 0f Vx Vx inelasticity jitter collision x true play int Math random 3 Dimension d parent size if x width gt d width x d width width Vx Vx inelasticity jitter collision_x true play int Math random 3 y 0 Vy Vy inelasticity jitter collision_y true play int Math random 3 if y height gt d height y d height height Vx inelasticity Vy Vy inelasticity jitter collision_y true a move x y Vy Vy Ay deltaT Vx Vx Ax deltaT findex Vr deltaT if collision x collisi
26. turns 4 With the numeric example experiment with the number format i e use integers reals exponential format What happens 5 Write a program that will read in your name and address and print them out in reverse order O Ian D Chivers email ian chivers Okcl ac uk 4 Arithmetic Expressions and the primitive data types in Java Taking Three as the subject to reason about A convenient number to state We add Seven and Ten and then multiply out By One Thousand diminished by Eight The result we proceed to divide as you see By Nine Hundred and Ninety and Two Then subtract Seventeen and the answer must be Exactly and perfectly true Lewis Carroll The Hunting of the Snark Round numbers are always false Samuel Johnson Aims The aims of this chapter are to introduce the numeric data types available in Java the integer numeric model used in Java the floating point numeric model used within Java the IEEE 754 1985 stan dard the rules for the evaluation of arithmetic expressions the rules that apply in type conversion constants static final char data type boolean data type to introduce briefly all of the operators in Java Chapter 4 Arithmetic and Expressions in Java 60 4 Arithmetic and Expressions in Java This chapter looks at the fundamental numeric data types in Java and the rules for expres sion evaluation There are a large number of operators and a quick look at them
27. types Java draws heavily on C and C for its operators and syntax If you have some back ground in these languages then this obviously helps However there are no pointers in Java or explicit delete mechanisms to free memory Java has a garbage collector Strings and arrays are not fundamental data types they are objects and as such are covered in separate chapters Constants are provided using the static final attributes There is a lot of material in this chapter Don t panic As the course progresses more and more of it will stick 4 14 Package java lang This package provides classes that are fundamental to Java They do not need to be im ported They are automatically imported They have been covered here as I couldn t think of where else they should go 4 14 4 Interface Summary 4 14 1 1 Cloneable A class implements the Cloneable interface to indicate to the Object clone method that it is legal for that method to make a field for field copy of instances of that class 4 14 1 2 Comparable This interface imposes a total ordering on the objects of each class that implements it 414 4 5 Runnable The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread 4 14 Class Summary 4 14 2 1 Boolean The Boolean class wraps a value of the primitive type boolean in an object email ian chivers Q kcl ac uk O Ian D Chivers Chapter 4 Arithmetic and Expressions in Java 74
28. 4 14 2 2 Byte The Byte class is the standard wrapper for byte values 4 14 2 3 Character The Character class wraps a value of the primitive type char in an object 4 14 2 4 Character Subset Instances of this class represent particular subsets of the Unicode character set 4 14 2 5 Character UnicodeBlock A family of character subsets representing the character blocks defined by the Unicode 2 0 specification 4 14 2 6 Class Instances of the class Class represent classes and interfaces in a running Java application 4 44 77 ClassLoader The class ClassLoader is an abstract class 4 14 2 8 Compiler The Compiler class is provided to support Java to native code compilers and related ser vices 4 14 2 9 Double The Double class wraps a value of the primitive type double in an object 4 14 2 10 Float The Float class wraps a value of primitive type float in an object 414 211 InheritableThreadLocal This class extends ThreadLocal to provide inheritance of values from parent Thread to child Thread when a child thread is created the child receives initial values for all InheritableThreadLocals for which the parent has values 4 14 2 12 Integer The Integer class wraps a value of the primitive type int in an object 4 14 2 13 Long The Long class wraps a value of the primitive type long in an object 4 14 2 14 Math The class Math contains methods for performing basic numeric operations such as the ele mentary exponential logarithm s
29. 9 3 java io DataInputStream class Note that this class returns a single Java base type in binary form The value of 1 as an int is the following binary sequence of bits 0000000000000000000001 This means that they cannot be used for user interaction When we interact with users we do so via a stream of characters The character value 1 is represented by the following se quence of bits 00000000001 10001 Remember that Java characters are Unicode based and use 16 bits In practical terms the in teraction will take place in 8 bit ASCII for many people public final boolean read Boolean throws IOException EOFException public final byte readByte throws IOException EOFException public final char readChar throws IOException EOFException public final double readDouble throws IOException EOFException public final float readFloat throws IOException EOFException public final int readInt throws IOException EOFException public final String readLine throws IOException EOFException public final long readLong throws IOException EOFException public final short readShort throws IOException EOFException public final String readUTF throws IOException EOFException public final int readUnsignedByte throws IOException EOFException public final int readUnsignedShort throws IOException EOFException Note that all of these methods are final they cannot be over ridden 9 4 java io DataOutput interface Match
30. FileInputStream FilterInputStream BufferedInputStream DataInputStream LineNumberInputStream PushBackInputStream PipedInputStream SequenceInputStream StringBufferInputStream RandomAccessFile DataInput DataInputStream DataOutput DataOutputStream O Ian D Chivers email ian chivers Okcl ac uk 121 i o Chapter 9 OutputStream ByteArrayOutputStream FileOutputStream BufferedOutputStream DataOutputStream PrintStream FilterOutputStream PipedInputStream StreamTokenizer I recommend looking at the on line documentation that comes with the Java 1 1 jdk Use netscape to browse it All of the information required is there We will only look at a subset of the above in the notes Note that Java does not support file i o from an applet when running on another system i e if we were loading a Java applet from system A and running it on system B then it would not have access to B s file system This would comprimise the security of Java A Java program will have access to the underlying file system 9 1 Class vs Interface A class will provide both the definition and implementation of a set of methods an object supports An interface provides only a definition of the methods The implementation must be pro vided by classes that extend the interface This is the equivalent of an abstract class with virtual methods in C terminology 9 2 Java io DataInput interface An interface that defines the methods for input of the base Java
31. Image bgi Graphics bgg email ian chivers kcl ac uk O Ian D Chivers Chapter 11 Introduction to Graphics Programming 144 public void init setBackground Color white deltax 3 deltay 3 x Math random x1 y Math random yl bgi createImage this size width this size height bgg bgi getGraphics public void start if ball 2null ball new Thread this ball start public void stop if ball null ball stop ball null public void paint Graphics g bgg setColor Color white bgg fillOval int oldx int oldy 20 20 bgg setColor Color blue bgg fillOval int x int y 20 20 g drawlImage bgi 0 0 this oldx x oldy y public void update Graphics g paint 9 public void run Ian D Chivers email ian chivers kcl ac uk 145 Introduction to Graphics Programming Chapter 11 Lori xt deltax yt deltay if x gt x1 x lt 0 deltax deltax if y gt y1 y lt 0 deltay deltay repaint try Thread sleep 1 catch InterruptedException e Compiling with JDK 1 2 2 and deprecation generates warning about size and stop Running the applet on Gum using the appletviewer is very slow Running on a P166 with 64 Mb of memory is faster but there are still problems with trails of where the ball has been
32. Temporary Loop reading characters entil the End Of File EOF Note that one cannot use eof to check for EOF until one has actually tried to read it unlike Pascal while cin gt gt c Loop for all characters ptr new link if ptr NULL cout lt lt Insufficient memory n exit 1 Add new value and clear subsequent link ptr gt c c ptr gt next NULL Update pointers to add new value at end of list The if statement could be omitted by making the first character en tered a special case as in Example 10 1 4 but generallity is a good idea ed if first NULL If this is the first character a Ian D Chivers email ian chivers kcl ac uk 111 Exceptions Chapter 8 first current ptr else Otherwise current next ptr current ptr Now print out the list ptr first while ptr NULL Sut lt lt PEL C ptr ptr gt next cout lt lt endl return 0 8 4 Discussion It is apparent that the essential code is hidden to greater or lessor extent in the requirements to handle special conditions The Pascal code is probably the cleanest The beauty of excep tion handling is that the essential logic of the code is left alone and enclosed within a try statement Let us look at one of the earlier examples to see how simple and straightforward this is in Java import java io class c
33. TextField A TextField object is a text component that allows for the editing of a single line of text TexturePaint The TexturePaint class provides a way to fill a Shape with a texture that is speci fied as a BufferedImage Toolkit This class is the abstract superclass of all actual implementations of the Abstract Window Toolkit Window A Window object is a top level window with no borders and no menubar 11 23 3 Exception Summary AWTException Signals that an Absract Window Toolkit exception has occurred IllegalComponentStateException Signals that an AWT component is not in an appropriate state for the requested operation 11 23 4 Error Summary AWTError Thrown when a serious Abstract Window Toolkit error has occurred The original AWT has some problems associated with it and you can see now why it was necessary to develop a better windowing development system We will look at Swing in a later chapter We will next look at some of the developments that have taken place with the original AWT 11 23 5 java awt Graphics The Graphics class is the abstract base class for all graphics contexts that allow an applica tion to draw onto components that are realized on devices You need to know about what is in this package as the other more recent packages will inherit from this package A Graph ics object has state information needed for the basic rendering operations that Java supports This state information includes the following
34. The function call operator 4 8 2 4 Increment after use 4 8 2 5 Decrement after use 4 8 2 6 Increment before use 4 8 2 7 Decrement before use 4 8 2 8 complement expr post increment expr post decrement expr pre increment expr pre decrement expr subscripting pointer expr O function call expr expr list One s complement operator The operand must be of integral type Integral promotions are performed 4 8 2 9 Logical negation operator 4 8 2 10 As stated not expr unary minus expr email ian chivers Q kcl ac uk O Ian D Chivers Chapter 4 Arithmetic and Expressions in Java 66 4 8 2 11 unary plus expr As stated 4 8 2 12 new create new type The new operator attempts to create an object of the type to which it is applied This type must be an object type and functions cannot be allocated in this way though pointers to functions can 4 8 2 13 O cast type expr An explicit type conversion 4 8 2 14 multiply expr expr Conventional arithmetic multiplication 4 8 215 divide expr expt Conventional arithmetic division 4 8 2 16 modulo or remainder expr expr Remainder 4 8 2 17 plus expr expr Conventional arithmetic addition 4 8 2 18 minus expr expr Conventional arithmetic subtraction 4 8 2 19 lt lt shift left expr lt lt expr Shift left The operands must be of integral type an
35. The next major difference occurs when defing our own class beanO1 In this case we now have an additioal element in the function header and this is Serializable This means that the state of the bean is remembered Another term for this is persistence When developing this example I didn t rebuild the jar file after recompiling the Java source and it ran as before You can examine the archive with jar tvf bean0l jJar We run the program with the following command java jar bean01 jar 15 4 Summary I ve only briefly touched on what beans can do in this chapter They really come into their own when used in conjuction with a visual development environment We are currently trying to install Netbeans on Gum I will notify people when we have successully installed it and I ll provide details on how to use the environment You also have details of IBM Visual Age for Java and I would recommed installing that on your pc and working through the pdf documentation More details are in the chapter on IBM Visual Age for Java 15 5 Useful addresses I would visit the following and print out some of the material You mileage will vary http java sun com beans Sun s home page and a very good place to start O lan D Chivers email ian chivers Okcl ac uk 233 JavaBeans Chapter 15 http java sun com beans training html links to both instructor led and on line training resources specifically for JavaBeans component developers http deve
36. add new Checkbox Spurs 12 7 Checkbox with Grouping import java awt public class c1116 extends java applet Applet public void init Font f new Font Arial Font PLAIN 20 setFont f CheckboxGroup g new CheckboxGroup email ian chivers Q kcl ac uk O Ian D Chivers Chapter 12 AWT Based Windows Programming add new Checkbox QPR g false add new Checkbox Arsenal g false 12 8 List import java awt public class c1117 extends java applet Applet public void init Font f new Font Arial Font PLAIN 20 setFont f List l new List 3 false l addItem Qpr additem Arsenal addItem Spurs additem Chelsea addItem Crystal Palace add 1 12 9 TextField import java awt public class c1118 extends java applet Applet public void init add new TextField Who are you favourite London team 50 add new Label Who is your favourite player add new TextField 20 12 10 Passwords import java awt public class c1119 extends java applet Applet public void init add new Label Type in your password TextField t new TextField 20 t setEchoCharacter add t 192 Ian D Chivers email ian chivers kcl ac uk 193 AWT Based Windows Programming Chapter 12 12 11 TextArea import java awt public class c1120 extends java applet Apple
37. ball start public void stop if ball 2null ball stop ball null public void paint Graphics g bgg setColor Color white bgg fillOval oldx oldy 20 20 bgg setColor Color blue bgg fillOval x y 20 20 g drawImage bgi 0 0 this oldx x oldy y public void update Graphics g paint g Ian D Chivers email ian chivers kcl ac uk 147 Introduction to Graphics Programming Chapter 11 public void run for xt deltax yt deltay if x gt x1 x lt 0 deltax deltax if y gt y1 y lt 0 deltay deltay repaint try Thread sleep 1 catch InterruptedException e This is now quite jerky running on the appletviewer on the pc 11 19Example 6 Loading jpg images static display import java awt Graphics import java awt Image public class ian01 extends java applet Applet Image image01 public void init image0l get Image getCodeBase ian01 jpg public void paint Graphics g g drawImage image01 10 10 this Use Netscape to find some jpegs and ftp them to Gum Have a look at their size Other things to consider are colour information The three most common are 8 bit 256 colours 16 bit and 24 bit colour 8 bit colour isn t too bad especially for thumbnails 11 20Example 7 Loading image simple sc
38. bold f new Font s Font ITALIC 20 setFont f add new Label italic f new Font s Font BOLD Font ITALIC 20 setFont f add new Label bold italic public void start s Helvetica showfont s s TimesRoman showfont s s Courier showfont s s Dialog showfont s 11 23AWT 1 0 x The package java awt contains all of the classes for creating user interfaces and for painting graphics and images A user interface object such as a button or a scrollbar is called in AWT terminology a component Some components fire events when a user interacts with the components The AWTEvent class and its subclasses are used to represent the events that AWT components can fire A container is a component that can contain components and other containers A container can also have a layout manager that controls the visual placement of components in the container The AWT package contains several layout man ager classes and an interface for building your own layout manager Ian D Chivers email ian chivers kcl ac uk 155 Introduction to Graphics Programming Chapter 11 11 23 1 Interface Summary ActiveEvent An interface for events that know how dispatch themselves Adjustable The interface for objects which have an adjustable numeric value contained within a bounded range of values Composite The Composite interface along with CompositeContext defines th
39. import java awt javax swing JApplet public class c0301c extends JApplet public void paint Graphics g g drawString Hello world 10 20 Ian D Chivers email ian chivers kcl ac uk 53 An Introduction to Java Chapter 3 3 8 Hello World JComponent This next example shows how to do it using one of the components from JComponents Note that this is a program not an applet import javax swing JOptionPane public class c0301d public static void main String args JOptionPane showMessageDialog null Hello world System exit 0 We have used the simplest form of the showMessageDialog method We have seen four ways of achieving much the same end result The reasons for this are two fold Firstly there is the concept of a program and an applet Secondly Java is evolving and there are now several ways to achieve more or less the same end result Different books will show you different ways of writing Java applets and programs 3 9 Program for line i o This program example reads a line of input from the user and echos it This example intro duces a number of very important concepts about java import java io class c0302 public static void main String args try InputStream i System in DatalnputStream in new DatalnputStream i String Line System out println Type in a line of text Line in readLine System out printin Line catch IOExceptio
40. runs like a dog P II 266 with 128 Mb of memory Windows NT ok P II 350 192 Mb of memory Windows 98 fine Be patient whichever version you use 17 2 The JDK You need to install a compatible version of the JDK 17 3 Documentation Sun provide 3 documents that can be printed in the release I installed QuickStart 36 pages Tutorials 38 UserGuide 299 and these are all Adobe PDF format I recommend printing them and working through the first two to help you familiarise yourself with the environment There is extensive on line help More difficult to work with though Ian D Chivers email ian chivers kcl ac uk 18 Microsoft Visual J Can you do addition the White Queen asked What s one and one and one and one and one and one and one and one and one and one T don t know said Alice I lost count She can t do addition the Red Queen interrupted Lewis Carroll Through the Looking Glass and What Alice Found There Aims The aims of this chapter are to provide a brief coverage of Microsoft Visual J Chapter 18 Microsoft Visual J 242 18 Microsoft Visual J This chapter looks at Microsoft Visual J 18 1 Availability and Versions There are two versions Standard Professional I ve been using the latter and it provides the following additional features over the standard edition Database access Visual data controls Professional visual development tools Visual component manager Rem
41. true music stop public void paint Graphics g Dimension d size g setColor Color gray g drawRect 0 0 d width 1 d height if images null for int i 0 i lt images length if images i null images i paint 9g If you feel really adventurous replace the sounds too Also have a look at Chapter 11 of the Deitel book 11 36Bibliography One of the best books I ve found is 186 14 pase sf Foley van Dam Feiner Hughes Computer Graphics Principles and Practice Addison Wesley e There is a good coverage of most of the things that you need to know Not cheap about 35 40 uk pounds the last time I looked O lan D Chivers email ian chivers Okcl ac uk 187 Introduction to Graphics Programming Chapter 11 The other source of information is of course the on line JDK documentation This is a mix ture of actual inforation that actually is installed on the College web server or your own pc with links to the Sun site The documentation tells you what is on line and what is on the Sun web server A modem 1s therefore very useful when working at home Sun also make available a lot of examples on their web site I normally bookmark some of the key components to make it easier to use with Netscape email an chiversO kcl ac uk O Ian D Chivers 12 AWT Based Windows Programming When I use a word Humpty Dumpty said in a rather scornful tone it means just what
42. 11 22 4 3D Effects g draw3Drect x y w h true This method has to be repeated several times to obtain the desired effect true raises the rectangle and false gives the effect of a pushed button import java awt public class c1145 extends java applet Applet public void init setBackground Color white public void paint Graphics g g setColor Color blue g draw3DRect 10 10 100 100 true g draw3DRect 11 11 98 98 true g draw3DRect 12 12 96 96 true g draw3DRect 13 13 94 94 true 11 22 5 Polygons There are two ways of doing this using arrays using the polygon class The following two examples show both methods import java awt public class c1146 extends java applet Applet public void init setBackground Color white public void paint Graphics g int x 20 30 40 40 30 20 10 10 20 int y 10 10 20 30 40 40 30 20 10 g setColor Color blue g drawPolygon x y 9 import java awt email an chiversO kcl ac uk O Ian D Chivers Chapter 11 Introduction to Graphics Programming 152 public class c1147 extends java applet Apple public void init setBackground Color white public void paint Graphics g Polygon octagon octagon octagon octagon octagon octagon octagon octagon octagon octagon new P addPoint addPoin addPoin addPoin addPo
43. 16 Some Important Milestones in Program Language Development We look here at some of the major steps forward in the way we approach problem solving using programming languages Often people adopted the following methodologies without having features in a programming language that actually supported them 2 16 1 Structured Programming Structured programming in its narrowest sense concerns itself with the development of pro grams using a small but sufficient set of statements and in particular control statements It has had a great effect on program language design and most languages now support a mini mal set of control structures In a broader sense it subsumes other objectives including sim plicity comprehensibility verifiability modifiability and maintenance of programs The ideas are very well covered in the Dahl Dijkstra Hoare text This is essential reading 2 16 2 Stepwise Refinement The original ideas are very well expressed a a paper by Wirth entitled Program Develop ment by Stepwise Refinement published in 1971 Essential reading 2 163 Data Structuring Concrete vs Abstract Data Types With a concrete data structure you have to know how the data structure is organised explic itly With abstract data types the internals are hidden from you and all you see are a set of procedures that provide the functionality you want 2 16 4 Information Hiding Modules A major step forward in the development of programming languages Th
44. 5 2 1 2 String Example 2 valueOf import java lang class c0504 public static void main String args String s0 s1 s2 s3 s4 Ss5 char c 1 int i 1 long 1 1 float f 1 double d 1 s1 String valueof c s2 String valueOf i Ian D Chivers email ian chivers kcl ac uk 83 Strings Chapter 5 s3 String valueOf 1 s4 String valueOf f s5 String valueOf d System out printin s1 System out printin s2 System out printin s3 System out printin s4 System out printin s5 s0 sl1 s2 s3 s4 s5 System out println s0 The first line is very important This makes available all of the methods within java lang to the following program We can then use shortened forms of the method names within the following program The String class is within java lang This example highlights the differences between the base types and String objects In each case we use the value 1 It has a different meaning in each of the contexts 5 2 1 3 String Example 3 as above but no import statement class c0505 public static void main String args String s0 s1 s2 s3 s4 Ss5 char c 1 int i 1 long 1 1 float f 1 double d 1 sl java lang String valueOf oc s2 java lang String valueOf i s3 java lang String valueOf 1 s4 java lang String valueOf f s5 java lang String valueOf d System out printin s1 System ou
45. Another possibility would be SQL server but this would imply NT as well I am not sure of the cost of SQL server for NT 22 3 2 1 Some entries from the FAQ Are there any ODBC drivers that do not work with the JDBC ODBC Bridge Most ODBC 2 0 drivers should work with the Bridge Since there is some varia tion in functionality between ODBC drivers the functionality of the bridge may be affected The bridge works with popular PC databases such as Microsoft Ac cess and FoxPro How can I use the JDBC API to access a desktop database like Microsoft Access over the network Most desktop databases currently require a JDBC solution that uses ODBC un derneath This is because the vendors of these database products haven t imple mented all Java JDBC drivers The best approach is to use a commercial JDBC driver that supports ODBC and the database you want to use See the JDBC drivers page for a list of available JDBC drivers The JOBC ODBC bridge from Sun s Java Software does not provide network access to desktop databases by it self The JDBC ODBC bridge loads ODBC as a local DLL and typical ODBC drivers for desktop databases like Access aren t networked The JDBC ODBC bridge can be used together with the RMI JDBC bridge however to access a desktop database like Access over the net This RMI JDBC ODBC solution is free Does the JOBC ODBC Bridge work with Microsoft J No J does not support the JOBC ODBC bridge since it doesn t implement the
46. CellEditorListener CellEditorListener defines the interface for an object that listens to changes in a CellEditor ChangeListener Defines an object which listens for ChangeEvents DocumentEvent Interface for document change notifications DocumentEvent ElementChange Describes changes made to a specific element DocumentListener Interface for an observer to register to receive notifications of changes to a text document HyperlinkListener HyperlinkListener InternalFrameListener The listener interface for receiving internal frame events ListDataListener ListDataListener ListSelectionListener The listener that s notified when a lists selection value changes MenuDragMouseListener Defines a menu mouse drag listener MenuKeyListener MenuKeyListener MenuListener Defines a listener for menu events MouselInputListener A listener implementing all the methods in both the MouseListener and MouseMotionListener interfaces PopupMenuListener A popup menu listener TableColumnModelListener TableColumnModelListener defines the interface for an object that listens to changes in a TableColumnModel TableModelListener TableModelListener defines the interface for an object that listens to changes in a TableModel TreeExpansionListener The listener that s notified when a tree expands or collapses a node TreeModelListener O lan D Chivers email ian chivers Okcl ac uk 203 Events Chapter 13 TreeChangeListener defines the interfa
47. Character Set A new standard is becoming increasingly popular where multiple language support is re quired This is called Unicode This is a sixteen bit character set C offers support for 16 bit characters but does not demand suppport of Unicode Characters in Java are Unicode based Given that the web is international you can see why Java uses the Unicode standard It enables everyone in the world to take advantage of Java using their own character sets There are two major character sets in computing These are ASCII a 7 bit character standard and ISO Latin 1 an 8 bit character standard commonly called Latin 1 Look at the differences between ASCII DOS character set Windows character set DEC character set Apple character set ISO Latin 1 in the additional notes I have provided When running a Java applet in a web browser you may not see the characters as they were originally developed as your browser may not be able to support rendering of that character set We will look into the whole area of characters character sets and strings in much greater depth in a later chapter 3 14 Summary Don t be put off by the syntax of Java It doesn t take long to get on top of that syntax You wouldn t expect natural languages to have identical syntax and semantics so why expect it from programming languages 3 15 Bibliography I ve broken down this into three areas It is essential to get hold of additional sources in the first tw
48. Chivers email ian chivers Okcl ac uk Swing A man should keep his brain attic stacked with all the furniture he is likely to use and the rest he can put away in the lumber room of his library where he can get at it if he wants Sir Arthur Conan Doyle Five Orange Pips Aims The aims of this chapter are to look at Swing Chapter 14 Swing 214 14 Swing It should be obvious by now that graphics programming requires some effort It was real ised that the AWT was not adequate and if Java was to succeed in the graphics area then this had to be addressed The AWT were tied to the local platform The Java Foundation Classes or JFC were created to ease the design and implementation of the user interface These include things that people take for granted with windows based software e g menus dialog boxes etc There is a coverage of each of them in this chapter We will first look at the history of the JFC and Swing 14 1 History The original JDK release that these examples were based on was 1 0 2 As you have seen during the course some of the examples generate warning messages when compiled This is due to the evolution that is taking place with Java One of the major drawbacks of the early releases was the platform specific behaviour of many program Hardly write once and run anywhere JDK 1 1 fixed some of the problems The new event model was a massive step forward but the AWT was still platform specific Now we had an event subscrib
49. Composes an AffineTransform object with the Transform in this Graphics2D ac cording to the rule last specified first applied abstract void translate double tx double ty Concatenates the current Graphics2D Transform with a translation transform abstract void translate int x int y Translates the origin of the Graphics2D context to the point x y in the current coordinate system Methods inherited from class java awt Graphics include clearRect clipRect copyArea cre ate create dispose drawArc drawBytes drawChars drawImage drawImage drawImage drawImage drawlImage drawlImage drawLine drawOval drawPolygon drawPolygon drawPolyline drawRect drawRoundRect fillArc fillOval fillPolygon fillPolygon fillRect fillRoundRect finalize getClip getClipBounds getClipBounds getClipRect getColor getFont getFontMetrics getFontMetrics hitClip setClip setClip setColor setFont setPaintMode setXORMode toString email ian chivers Q kcl ac uk O Ian D Chivers Chapter 11 Introduction to Graphics Programming 168 11 25Package java awt geom JDK 1 2 Provides the Java 2D classes for defining and performing operations on objects related to two dimensional geometry Some important features of the package include classes for ma nipulating geometry such as AffineTransform and the PathlIterator interface which is imple mented by all Shape objects classes that implement the Shape interface such as CubicCurve2D Ellipse2D
50. DAY HOUR and so on 25 1 2 10 Collections This class consists exclusively of static methods that operate on or return collections 25 1 2 11 Date The class Date represents a specific instant in time with millisecond precision 25 1 2 12 Dictionary The Dictionary class is the abstract parent of any class such as Hashtable which maps keys to values 25 1 2 13 EventObject The Event class is the abstract root class from which all event state objects shall be derived 25 1 2 14 GregorianCalendar GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar used by most of the world 25 1 2 15 HashMap Hash table based implementation of the Map interface email ian chivers kcl ac uk Ian D Chivers Chapter 25 Package java util 288 25 1 2 16 HashSet This class implements the Set interface backed by a hash table actually a HashMap in stance 25 1 2 17 Hashtable This class implements a hashtable which maps keys to values 25 1 2 18 LinkedList Linked list implementation of the List interface 25 1 2 19 ListResourceBundle ListResourceBundle is a abstract subclass of ResourceBundle that manages resources for a locale in a convenient and easy to use list 25 1 2 20 Locale A Locale object represents a specific geographical political or cultural region 25 1 2 21 Observable This class represents an observable object or data in the model view paradigm 25 1 2 22 Properties The Pr
51. DropTarget The DropTarget is associated with a Component when that Component wishes to accept drops during Drag and Drop operations 26 1 2 10 DropTarget DropTargetAutoScroller this protected nested class implements autoscrolling 26 1 2 11 DropTargetContext A DropTargetContext is created whenever the logical cursor associated with a Drag and Drop operation coincides with the visible geometry of a Component associated with a DropTarget 26 1 2 12 DropTargetDragEvent The DropTargetDragEvent is delivered to a DropTargetListener via its dragEnter and dragOver methods 26 1 2 133 DropTargetDropEvent The DropTargetDropEvent is delivered via the DropTargetListener drop method 26 1 2 14 DropTargetEvent The DropTargetEvent is the base class for both the DropTargetDragEvent and the DropTargetDropEvent 26 1 2 15 MouseDragGestureRecognizer This abstract subclass of DragGestureRecognizer defines a DragGestureRecognizer for mouse based gestures 26 1 3 Exception Summary 26 1 3 1 InvalidDnDOperationException This exception is thrown by various methods in the java awt dnd package A typical Drag and Drop operation can be decomposed into the following states not en tirely sequentially A DragSource comes into existence associated with some presentation element Component in the GUI to initiate a Drag and Drop of some potentially Trans ferable data 1 or more DropTarget s come into go out of existence associated with pres
52. EUT IR ss dic 270 22 5 3 1 BatchUpdateException JDBC 2 0 seen 270 22 5 3 2 DataTr ncation ea eaeque qt gr i ae 270 22 5 3 3 SOLBXCepLOD mear sette etico et beris s e eb i ede seite osado 270 22 5 3 4 SODEWatrnIlIig oer elton ee a e aah i Ee E T len 270 A O O A A is quud isnt a nde actus iui tue a dee o ai 270 22 6 1 Interface Summar nein ee bene 270 22 6 1 1 ConnectionEventL IS esti E e E A e ee Ee E E 270 22 6 1 2 Connectio PoolData SOUT Sisareni tenens norii een ea ean ian esi 270 22 6 1 3 Data OU a ieee AEAT 270 22 6 1 4 Poole d Conectate EE Hee eee dee cede AE 270 22 6 1 5 O 270 22 6 1 6 RowsSetInternal ette tite eones a aE iE a E eaaa Eae aee 270 22 6 1 7 RowSetListehet ie etre eee REM NS eis ee eh 270 22 6 1 8 RowSetMetaDat eei eerte tete rete be ee hse ve date ene e ede eee EPI E HH Ee gun 270 22 6 1 9 RowsctReaders 6 oet ae 271 22 6 1 10 ROWSeUWTFILT RN 271 22 6 1 11 XAConnectlon ii onte ahh iodo aaa 271 22 6 1 12 NA ICE EO Em 271 22 6 2 Class TII 271 22 6 2 1 ConMeCHONE cnm E 271 22 6 2 2 RowSetEVent idd neq ideado tae gaps 271 PME S CD RT H 271 pr Muta 271 2S BIOS aserra nte i tava teadus va a E sty iM ET 271 23 SOL VICUS ii E P 274 Doak Getting c E 274 23 1 1 IN OLE S ie ce eset e e etica eue al 278 23 1 1 1 E O E IN 278 23 1 1 2 Start the A NR 278 23 1 1 3 Compiled class files concisa 279 23 1 1 4 Incorrect example Ika a et 279 23 1 1 5 Complete Source Ode iii tere
53. I choose it to mean neither more nor less The question is said Alice whether you can make words mean so many different things Lewis Carroll Through the Looking Glass and What Alice found there Aims The aims are to introduce some of facilities provided within the Abstract Windows Toolkit for Windows programming The examples are based on the early 1 0 x jdk There is a coverage of buttons labels buttons and lables scrollbars checkboxes checkboxgroups list items text fields passwords text fields on multiple lines layout managers flowlayout gridlayout gridbag layout with constraints Chapter 12 AWT Based Windows Programming 190 12 AWT Based Windows Programming Java provides a range of methods for writing and developing window based programs This chapter looks at what was available in the earliest releases and provides a simple example of each Note that complete examples that actually do something useful are given after we have covered events The later chapter on Swing looks at the more powerful and easier to use facilties provided in later versions There is a quick coverage of some of the common graphuical user interface components 12 1 Button import java awt public class c1110 extends java applet Applet public void init Font f new Font Arial Font PLAIN 20 setFont f add new Button QPR add new Button Arsenal add new Button Spurs
54. Image image01 BufferedImage bimage01 public void init public class ianll extends javax swing JApplet image01 getImage getCodeBase ian01 jpg public void displayimage int w int h Graphics2D g2d int iw int ih BufferedImage bi BufferedImage createlmag w h Graphics2D big bi createGraphics iw imageOl getWidth this ih image01 getHeight this big drawImage image01 10 10 iw ih this g2d drawImage bi 0 0 this public void paint Graphics g Graphics2D g2d Graphics2D g Dimension d getSize displayimage d width d height g2d public static void main String argv final ianll ill new ian11 ill init JFrame jf new JFrame Java 2d version jf addWindowListener new WindowAdapter public void windowClosing WindowEvent e System exit 0 Ian D Chivers email ian chivers kcl ac uk 179 Introduction to Graphics Programming Chapter 11 Differences include We are now working with buffered images paint creates a Graphics2D context from a Graphics context We pick up the size We call dispalyimage with the current Graphics2d context and size displayimage creates a buffered image and graphics 2d context based on the size from the calling routine We get the height and width of the jpg file associated image Draw the image Force the display with g2
55. Impe rial College before I came to King s in 1986 They are the first people to use the concept of a class Algol 60 based Stroustrup got many of his ideas from Simula 2 20 03 Smalltalk 1978 The text I recommend is Smalltalk 80 The Language and its Implementation Goldberg and Robson They worked at the Xerox Palo Alto Research Centre Xerox Parc Learning Re search Group Ideas are drawn from Simula and the vision of Alan Kay Steve Jobs was heavily influenced by and the Apple Macintosh owes a big debt to the Xerox Parc people We take windowing systems for granted these days on many of the systems we work with from the pc with Windows to Unix workstations with their X windows interfaces and of course the first to bring them to the mass market the Apple Mac Regarded as a pure OO system by most people with everything an object Wirth has spent a number of periods at Xerox Parc and that is reflected in Oberon 2 220 5 C In Stroustrup s words C is a general purpose programming language its core applica tion domain is systems programming in the broadest sense It is of course also used in a wide range of other application domains notable graphics pro gramming It is enormously popular and there are a very large number of jobs advertised for people with C skills You are unlikely to be out of work if you get to be a good C programmer C supports inheritance through class derivation Dynamic binding is provided by
56. It reflects the authors age and experi ence CDC Cray IBM ICL Fujitsu DEC Compaq Gateway Sun Silicon Graphics Hewlett Packard Data General Honeywell Elliot Mostek National Semiconductors Intel Zilog Motorola Signetics Amdahl Texas Instruments Cyrix Some of the operating systems include Ian D Chivers email ian chivers kcl ac uk 297 IEEE Arithmetic Chapter 27 NOS NOS BE Kronos Unix VMS Dos Windows MVS VM CP M and again the list is not exhaustive or definitive The intention is to provide with some idea of wide range of hardware computer manufacturers and operating systems that have existed in the last 50 years To help with the anarchy that existed in this area Doctor Robert Stewart acting on behalf of the IEEE convened a meeting which led to the birth of IEEE 754 The first draft was prepared by Willam Kahan Jerome Coonen and Harold Stone called the KCS draft and eventually adopted as IEEE 754 A fascinating account of the development of this standard can be found in An Interview with the Old Man of Floating Point and the bibliography provides a web address of this interview Kahan went on to get the ACM Tu ring Award in 1989 for his work in this area This has become a de facto standard amongst arithmetic units in modern hardware Note that it is not possibe to precisely describe the answers a program will give and the authors of the standard knew this This goal is virtually impossi
57. Java Applets 4 Control structures 1 5 Control structures 2 6 Methods email an chiversO kcl ac uk O Ian D Chivers Chapter 1 Overview 7 Arrays 8 Object based programming 9 Object oriented programming 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 295 Eckstein R Loy M Wood D Java Swing O R Reilly Straings and characters Graphics and Java2D Basic GUI components Advanced Gui Exception handling Multihtreading Multimedia animation audio video Files and streams JDBC Servlets RMI Networking Data structures Utilities Collections JavaBeans 20 There are a number of books on Swing and this one looks to be one of the better ones with a coverage of most of the features I was interested in The following are the chapters 1 Introducing Swing 2 Jump starting a Swing application 3 Swing component basics 4 Labels and Icons 5 Buttons 6 Bounded range components 7 Lists and Combo boxes 8 Swing containers 9 Internal frames 10 Swing dialogs 11 Speciality panes and layout managers 12 Chooser dialogs 13 Borders 14 Menus and toolbars 15 Tables 16 Advanced table examples 17 Trees O Ian D Chivers email ian chivers Okcl ac uk 21 Overview Chapter 1 18 Undo 19 Text 20 Document models and events 21 Styled documents and Jtextpane 22 Carets highlighters and keymaps 23 text views 24 editorkits and text actions 25 Programming with accessibi
58. Java Native Interface JNI Any all Java JDBC driver should work with J however 22 3 3 IBM DB2 would imply using OS 2 as your data source and Visual Age for Java 22 4 JDBC API The JDBCTM API provides universal data access from the JavaTM programming language Using the JDBC 2 0 API you can access virtually any data source from relational data bases to spreadsheets and flat files JDBC technology also provides a common base on which tools and alternate interfaces can be built The JDBC 2 0 API includes two packages the java sql package known as the JDBC 2 0 core API and the javax sql package known as the JDBC Standard Extension The JavaTM 2 SDK Standard Edition includes the JDBC 2 0 core API and the JDBC ODBC Bridge The JavaTM 2 SDK Enterprise Edition includes the JDBC 2 0 core API and also the JDBC 2 0 Standard Extension If you do not need everything that is included in the Enter prise Edition you can download the JDBC Standard Extension separately Note that if the javax sql package is bundled with your JDBC 2 0 technology driver you will not need to download it email ian chivers kcl ac uk Ian D Chivers Chapter 22 Web Data Access 268 JDBC Technology Drivers To use the JDBC API with a particular database management system you need a JDBC technology based driver to mediate between JDBC technology and the database Depending on various factors a driver might be written purely in the Java programming lang
59. O NT CN 9M pn ee ME 112 8 4 2 Catch iip DRE eidem vd e MS Rv SEE HER eh 112 8 4 3 PCI 112 8 5 Airay SUCH PL BEEODSS ooo ete ede cepta Dota E E 112 8 6 Anticipated Errors vs Unanticipated Errors esee 112 8 7 Complete Example File copy DFOPEGEIDS 2 td o dpa se Seay 112 8 8 Java Errors and BXeeptoHls uo escam Pe tto oe ortu sisse DX SERE ERRORES Du TE MIRO EINE 117 8 9 Jaya On line DocamentaltOn poto da ie tero p dat a datur e Grates Qiu s SG 117 DEUS SUTIEADY S ded A SL LES EOI 117 SUME Problems TN E a 117 bi A O REPERI 120 9 1 Class vs Interface 45 duced pede reete a taa 121 92 Javado Databuput Mera c oce igo A 121 9 2 1 OA 121 9 Javalo Datalnputsucam Class caida ii A qid tocadas 122 9 4 javado DataOutput interface ia eco assesses isa pta sudendeetecceatlsapeneseusnceate 122 9 javado DataOutputStredm class arnold caen have ue dtu 123 9 6 javajo PrintStream class ise rene ese beta nee et ose nae EY PER Se seabdouaessustaewsanscaas 123 9 6 1 Synchronized A epe ete erect e ee den e Moe Eg opa dee ee Ue R reed cetus 123 9 7 lo cun labs 124 9 8 TOD TIS a ino ooh O NN 128 IU Threads aiii qedku de odian 130 10 1 Example T extends Thread A p tecto e aote es 130 10 2 Example 2 Extends Thread e Ao p veau Se E paid pedites 131 10 3 Example 3 implements Runnable eerte Doe ede eee enean 132 10 4 Example 4 Implements Rumnable bi pat
60. Programming Language Addison Wesley e Written by the people who designed and implemented the language A definitive source on the language A bit expensive at just under thirty uk pounds Ian D Chivers email ian chivers kcl ac uk 41 An Introduction to Programming Languages Chapter 2 and Object Oriented Programming Barnes J Programming in Ada 95 Addison Wesley e A recent update of his previous Ada book Comprehensive coverage of Ada 95 Not for the beginner Birtwistle G M Dahl O J Myhrhaug B Nygaard K SIMULA BEGIN Chartwell Bratt Ltd e A number of chapters in the book will be of interest to programmers unfamiliar with some of the ideas involved in a variety of areas including systems and mod els simulation and co routines Also has some sound practical advice on prob lem solving Booch G Object Oriented Design with Applications Benjamin Cummings 24 Eq 1994 e I ve not been able to get hold of a copy of this yet One is on order at Dillons Don t buy or bother with the first edition as there are bound to be major ad vances in this edition due to his experience between editions Still not available at this time Brinch Hansen P The Programming Language Concurrent Pascal IEEE Transactions on Software Engineering June 1975 199 207 e Looks at the extensions to Pascal necessary to support concurrent processes Cannan S Otten G SOL The Standard Handbook McGraw Hill e Very thorough coverag
61. Run ning off the college web server with Netscape on the pc has the same trail behaviour 11 18Examle 4 Bouncing Balls with integer arithmetic and double buffering import java awt simple bouncing ball this example uses an off screen area to do the update this technique is common in graph t s and is called int buffering the other technique that this example show is that of so called selectiv rasure This is an other common programming technique in the graphics area rather than repaint the whole screen only the part that has to change is redrawn again worth looking at the sleep times the example has one small snag the selectiv ras doesn t work correctly arithmetic now made integer throughout again look at the sleep time and the speed or the bouncing ball public class graphic04 extends java applet Applet implements Runnable int x y deltax deltay oldx oldy int x1 300 int yl 300 email ian chivers Q kcl ac uk O Ian D Chivers Chapter 11 Introduction to Graphics Programming 146 Thread ball Image bgi Graphics bgg public void init setBackground Color white deltax 3 deltay 3 x int Math random x1 y int Math random yl1 bgi createImage this size width this size height bgg bgi getGraphics public void start if ball null1 ball new Thread this
62. Something we take for granted numeric i o has become seemingly unreasonably com plex This is the syntax of Java This is what you have to adapt to if you want to become profi cient in Java Learning a second natural language is difficult at first 3 11 Some Java Rules and Terminology Case is significant in Java Long names using mixed case will almost invariably end up causing compilation errors due to typing mistakes Class names and file names must match Programs in Java always have the same initial statement public static void main String args Applets in Java always have the same syntax public class yourname extends java applet Applet The file at the operating system level has to be called yourname Java keywords are given below 3 12 Good Programming Guidelines Every language has its own style It is advisable to adopt a style that one is comfortable with that draws on ones experience of other languages and also is similar to the notational style used by Java texts It is inevitable that one will end up working with algorithms and programs already written in Java and thus one has to be familiar with the conventional Java style of writing programs I prefer to match the and at the same indentation level I find the style adopted in some of the Java books difficult to work with I also prefer lowercase O Ian D Chivers email ian chivers Okcl ac uk 57 An Introduction to Java Chapter 3 3 13 Java
63. URL loc this must be executed in a broswer such as Netscape getAppletContext showDocument loc class Site extends Button private String title Ian D Chivers email ian chivers kcl ac uk 263 Simple Networking private URL location Chapter 21 public Site String siteTitle String siteLocation publ title siteTitle try A location new URL siteLocation catch MalformedURLException e System err println Invalid URL siteLocation publ ic URL lic String getTitle return title getLocation return location 21 2 Reading a file on a web server import import import import public java java java java awt Met ke ko dogs applet Applet class network02 extends Applet URL fileURL TextArea contents Datal public void InputStream input InputStream datalnput init contents add try new TextArea Connecting 400 400 contents fileURL new URL http www kcl ac uk kis sup port cc staff ian html catch MalformedURLException e showStatus Exception e toString email ian chivers kcl ac uk Ian D Chivers Chapter 21 Simple Networking 264 public void start String text try input fileURL openStream dataInput new D
64. ac uk Ian D Chivers Chapter 4 Arithmetic and Expressions in Java 76 static float min float a float b Returns the smaller of two float values static int min int a int b Returns the smaller of two int values static long min long a long b Returns the smaller of two long values static double pow double a double b Returns of value of the first argument raised to the power of the second argument static double random Returns a random number greater than or equal to 0 0 and less than 1 0 static double rint double a returns the closest integer to the argument static long round double a Returns the closest long to the argument static int round float a Returns the closest int to the argument static double sin double a Returns the trigonometric sine of an angle static double sqrt double a Returns the square root of a double value static double tan double a Returns the trigonometric tangent of an angle static double toDegrees double angrad Converts an angle measured in radians to the equivalent angle measured in degrees static double toRadians double angdeg Converts an angle measured in degrees to the equivalent angle measured in radians 4 14 2 15 Number The abstract class Number is the superclass of classes Byte Double Float Integer Long and Short 4 14 2 16 Object Class Object is the root of the class hierarchy 4 14 2 17 Package Package objects contain version information about the implementation and specificati
65. all is neces sary However for most applications you will only require a good knowledge of a small subset of them 4 1 Basic numeric types Java supports the two numeric data types we are familiar with from other programming lan guages 1 e integer and real 4 2 Integer Numeric Type The standard requires four types of integers byte short int and long and these correspond to byte 8 bit signed two s complement integer 128 through 127 short 16 bit signed two s complement integer 32768 through 32767 int 32 bit signed two s complement integer long 64 bit signed two s complement integer They obey the laws of arithmetic modulo 2 where n is the number of bits in the imple mentation Integer arithmetic never overflows or underflows it wraps Add 1 to a byte in teger of value 127 and it becomes 128 This is not an error Try running the following program on the system you use Run the program by piping the output through more i e type java c0401 more What do you think will happen class c0401 public static void main String args byte ib byte 1 short i s short 1 int i 1 long i_l 1 system out System oul print i b System out print El t print i s System out print System out print i System out print System out print i 1 System out printin for int count 1 count lt 33 count ib
66. als 132 10 5 Example 5 static variable in a thread oi tad rl 133 10 67 Example 6 synchronized ates a e to a aei aeiiae 134 10 7 Example 7 Syield pcciiscciiaacssdetrntiainustsansgtsaatsee niet a a Ni 135 10 8 Examples thread Priority 2 5 dano Ao ais AR ART Eo a 135 10 9 Problems uode A A AAA NA id 136 10 107 Babli era sarta bio oia oli erigi 136 11 Introduction to Graphics Programming ccccccccsssssssscscsssssssccssssssssseees 138 IT CMector vs Raster Graphics iia 138 LA PIRES M E 138 115 BTC maps iT YS Pi A e erbe quud ii 138 ULA Sereen resolution icto A m ua dites 138 11 4 1 Interlaced vs non interlaced essere eene enne enne 138 ES Colour Models 2 eee eoi e eat i ees 138 TA 622111 11 09 Saree ea pM ET v RE 139 DIS EOorinate SPACES nt oe ae tena 139 A A A AN 139 11 9 AAA A eon eve tues covant aes 139 1110 DESARME O eve 139 A A edo usto eed ie ote Laeta tesi de aedi uscire 139 1T 12 Rendering A iut ere cased cda tieu etude 139 LTS Putting at all together eee dedu a c qoa ie dep ep ts 139 1114 Pisto PR sdants 140 11 15 Example l Bouncing Balls iei dead ep RN ens UC ainia 140 11 16 Example 2 Bouncing Balls with integer arithmetic oooooconnocccinocccinonaconnncnnnncnonns 141 11 17 Example 3 Bouncing Balls with double buffering eee 143 11 18 Examle 4 Bouncing Balls with integer arithme
67. as Sun 27 2 4 Accuracy requirements Remainder and compare must be exact The rest should return the exact result if possible If not there are well defined rounding rules to apply 27 25 Base conversion i e when converting between decimal and binary floating point formats and vice versa These results should be exact if possible if not the results must differ by tolerances that de pend on rounding mode 27 2 0 Exception handling It must be possible to signal to the user the occurence of the following conditions or excep tions Divide by zero Overflow Underflow Invalid operation Inexact The ability to detect the above is a big step forward in our ability to write robust and porta ble code These operations do occur in calculations and it is essential to have user program mer control over what action to take 27 2 7 Rounding directions Four rounding directions are available nearest the default down up chop Access to directed rounding can be used to implement interval arithmetic for example 27 2 8 Rounding precisions The only mandatory part here is that machines that computations in extended mode let the programmer control the precision via a control word This means that if software is being developed on machines that support extended modes they can be switched to a mode that would enable the software to run on a system that didn t support extended mode This area looks like a can of worms Look at the Kaha
68. as a slow witted human being I have a very small head and I had better learn to live with it and to respect my limitations and give them full credit rather than try to ignore them for the latter vain effort will be punished by failure Edsger W Dijkstra Structured Programming Aims The aims of this chapter are to introduce selection between various courses of action as part of the problem solution the concepts and statements in Java needed to support the above In particu lar logical expressions logical operators a block of statements several blocks of statements the if expression statement the if expression statement else statement to introduce the switch statement with examples iterative statements while expression statement do statement while expression the for statement the break continue and goto statement Chapter 7 Control Structures 98 7 Control Structures There are a reasonable range of control structures in Java We need to review a number of other concepts before looking at them in depth 7 1 Compound Statement or Block A compound statement or block of statements is a sequence of statements enclosed in A compound statement is treated as a single item and may appear anywhere that a single state ment may occur 7 2 Expression An expression is made up of one or more operations They in turn are a mixture of operands and operators The evaluation of an expression typically means that on
69. available on line but obviously more difficult to use Covers the core of the language Out of date as soon as I bought it Not recommended Persevere and use the on line material instead Gosling Yellin and the Java Team The Java API Volume 2 Window Toolkit and Applets Addison Wesley The second api text Not recommended Use the on line material instead Flanagan Java in a Nutshell O Reilly amp Associates For people familiar with the Nutshell series this book is what one would expect It offers an introduction to Java programming with the Java api a language reference and api quick reference If you had to buy one book then this is one to consider email ian chivers kcl ac uk Ian D Chivers Chapter 1 Overview 22 Cowell Essential Visual J fast Springer Verlag One of the new series by Springer Tries to put a quart into a pint pot and does very well If you want a quick introduction to what Microsoft J can offer then this is one to consider What you get depends on your background what access you have to a printer and the in ternet A lot of material is available from the web Look at the above books and think about your background and experience in programming and programming languages algorithms data structures object oriented programming windows programming and also what you want to do The on line FAQ is ok Not as good as the C one O lan D Chivers email ian chivers Okcl ac uk 2 Introduction
70. by a server This net server middleware is able to connect all of its Java technology based clients to many different databases The specific protocol used depends on the vendor In general this is the most flexible JDBC API alterna tive It is likely that all vendors of this solution will provide roducts suitable for Intranet use In order for these products to also support Internet access they must handle the additional requirements for security access through firewalls etc that the Web imposes Several vendors are adding JDBC technology based driv ers to their existing database middleware products 4 A native protocol fully Java technology enabled driver converts JDBC tech nology calls into the network protcol used by DBMSs directly This allows a di rect call from the client machine to the DBMS server and is a practical solution for Intranet access Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver Several database vendors have these in progress 22 5 Package java sql JDK 1 1 Provides the JDBC package JDBC is a standard API for executing SQL statements It con tains classes and interfaces for creating SQL statements and retrieving the results of execut ing those statements against relational databases JDBC has a framework whereby different drivers can be installed dynamically to access different databases O Ian D Chivers email ian chivers kcl
71. can drap and drop visual compo nents Well VisualAge for Java takes things one step further The workbench and components are object based rather than file based You need to think in terms of projects packages classes interfaces methods and the hierarchy associated with these will provide a structure I am used to working with directories when programming and typically organise my work into f90 fortran 90 code f95 fortran 95 code java java code cxx C code O Ian D Chivers email ian chivers Okcl ac uk 251 IBM VisualAge for Java Chapter 19 This no longer works very well when working with a development environment You can use the above but you have to add directories below the above to keep related work files This is true when working with Compaq Dec Fortran 95 under Microsoft Visual Studio Microsoft Visual C under Visual Studio Microsoft Visual J IBM VisualA ge for Java Don t point one of the Java programming environments at your Java directory It will try reading everything in and compiling it 19 6 Starting up Visual Age for Java The following is the opening screen 1 Opening Screen As you can see we have a similar layout to Visual Basic which we looked at in an earlier chapter The key things to note are the left hand side has the tools in this case Beans the middle is where we can lay things out there are a variety of toolbars menus etc to enable us to work with the environ ment a
72. chivers kcl ac uk Ian D Chivers Chapter 15 JavaBeans 230 Beans can be programmed as well as handled by visual tools In the simple case you need only add a pair of methods to an existing class definition in or der to make it a Bean This can be done either by modifying the source for an existing class or by extending the behavior of an existing class by subclassing it 15 1 Package java beans JDK 1 1 Contains classes related to Java Beans development A few of the classes are used by beans while they run in an application For example the event classes are used by beans that fire property and vetoable change events see PropertyChangeEvent However most of the classes in this package are meant to be used by a bean editor that is a development envi ronment for customizing and putting together beans to create an application In particular these classes help the bean editor create a user interface that the user can use to customize the bean For example a bean may contain a property of a special type that a bean editor may not know how to handle By using the PropertyEditor interface a bean developer can provide an editor for this special type To minimize the resources used by a bean the classes used by bean editors are loaded only when the bean is being edited They are not needed while the bean is running in an application and therefore not loaded This informa tion is kept in what s called a bean info 15 2 Package java be
73. computing tech niques using the supercomputers at the San Diego Supercomputer Center SDSC http www mathcom com nafaq index html FAQ Numerical Analysis and Associated Fielda Resource Guide A summary of Internet resources for a number of fields related to numercial analysis Ian D Chivers email ian chivers kcl ac uk 303 IEEE Arithmetic Chapter 27 http www math psu edu dna disasters ariadne html The Explosion of the Ariane 5 A 64 bit floating point number relating to the horizontal ve locity of the rocket with respect to the platform was converted to a 16 bit signed integer The number was larger than 32 768 the largest integer storeable in a 16 bit signed integer and thus the conversion failed 27 5 2 Hardware Sources Osbourne A Kane G 4 and 8 Bit Microprocessor Handbook Osbourne McGraw Hill Good source of information on 4 and 8 bit microprocessors Osbourne A Kane G 16 Bit Microprocessor Handbook Osbourne McGraw Hill Ditto 16 bit microprocessors Intel 386 DX Microprocessor Hardware Reference Manual Intel The first Intel offering with 32 bit addressing Intel 80386 System Software Writer s Guide Intel Developer s Guide to the above http www intel com Intel s home page http developer intel com design pentiumiii Details of the Pentium III processor http www cyrix com Cyrix home page Bhandarkar D P Alpha Implementations and Architceure Complete Reference and Guide Digital Pres
74. e getSource loopSound currentSound loop e getSource stopSound currentSound stop email ian chivers Okcl ac uk 257 Multimedia Chapter 20 J RCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCk ACkckck ck ck ck k ck ck kk C Copyright 1999 by Deitel amp Associates Inc and Prentice Hall a All Rights Reserved DISCLAIMER The authors and publisher of this book have used their best efforts in preparing the book These efforts include the development research and testing of the theories and programs iS to determine their effectiveness The authors and pub lisher make no warranty of any kind expressed or implied with re gard to these programs or to the documentation contained in these books The authors and publisher shall not be liable in any event for inci dental or i consequential damages in connection with or arising out of the furnishing performance or use of these programs Ck CC C CC C CK CC CC CC CK CK CC CC CK CK CK CK CK KC CS S C S S A S KG Kk A Kk KR A KK X ko ko Ckckck ck ck kx x x x x f Try it out Obviously you will need a sound card and speakers to hear anything There are two sound file format files used in this example wav au If you have a pc try dir s p wav from the root of your c drive to see what wav files you have
75. f new Font Courier Font BOLD 30 first true public void paint Graphics g Ian D Chivers email ian chivers kcl ac uk 201 Events Chapter 13 g setFont f lf C frrst g drawString letter 50 50 public boolean keyDown Event e int key showStatus key down the char key was pressed letter String valueOf char key first false repaint return true public boolean keyUp Event e int key showStatus key up the char key was released TE return true 13 2 Swing Event Handling As of JDK 1 2 2 I have included a brief coverage of all that exist at this release Consult the on line docu mentation for more details We now look at the concept of an event listener and an event handler There are two places to look at java awt event and javax swing event and some of the event clases are interfaces equivalent to a C abstract class and hence you must provide the code to do the event handling With the advent of Swing there came several new event types We will look at complete examples that illustrate the above in the Swing chapter 13 2 1 Interface Summary AncestorListener AncestorListener Interface to support notification when changes occur to a JComponent or one of its ancestors CaretListener Listener for changes in the caret position of a text component email ian chivers kcl ac uk Ian D Chivers Chapter 13 Events 202
76. for Connection objects 22 6 4 PooledConnection A PooledConnection object is a connection object that provides hooks for connection pool management 22 6 1 5 RowSet The RowSet interface adds support to the JDBC API for the JavaBeans TM component model 22 6 1 6 RowSetInternal A rowset object presents itself to a reader or writer as an instance of RowSetInternal 22 6 1 7 RowSetListener The RowSetListener interface is implemented by a component that wants to be notified when a significant event happens in the life of a RowSet 22 6 1 8 RowSetMetaData The RowSetMetaData interface extends ResultSetMetaData with methods that allow a metadata object to be initialized O Ian D Chivers email ian chivers Okcl ac uk 271 Web Data Access Chapter 22 22 6 1 9 RowSetReader An object implementing the RowSetReader interface may be registered with a RowSet ob ject that supports the reader writer paradigm 22 6 1 10 RowSetWriter An object that implements the RowSetWriter interface may be registered with a RowSet ob ject that supports the reader writer paradigm 22 6 1 11 XAConnection An XAConnection object provides support for distributed transactions 22 6 1 12 XADataSource A factory for XAConnection objects 22 6 2 Class Summary 22 6 2 1 ConnectionEvent The ConnectionEvent class provides information about the source of a connection related event 22 6 2 2 RowSetEvent A RowSetEvent is generated when something i
77. ideas in this area Parnas D L On the Criteria to be Used in Decomposing Systems into Modules Communi cations of the ACM 15 12 1972 e One of the earliest papers to look at information hiding Sammett J Programming Languages History and Fundamentals Prentice Hall e Possibly the most comprehensive introduction to the history of program language development ends unfortunately before the 1980 s Reiser M Wirth N Programming in Oberon Steps Beyond Pascal and Modula Addison Wesley e Good introduction to Oberon Revealing history of the developments behind Oberon Reiser M The Oberon System User Guide and Programmer s Manual Addison Wesley e How to use the Oberon system rather than the language Rumbaugh J Blaha M Premerlani W Eddy F Lorenson W Object Oriented Modelling and Design Prentice Hall e like this book a lot Having been involved in the relational area for over 10 years the book struck an immediate chord Seed G An Introduction to OOP in C Springer e Comprehensive introduction to C and OOP Examples drawn from the com puter graphics area Young S J An Introduction to Ada pna Edition Ellis Horwood e A readable introduction to Ada Greater clarity than the first edition Dated in terms of the recent developments with Ada 95 Wexelblat History of Programming Languages HOPL I ACM Monograph Series Aca demic Press e Very thorough coverage of the development of programming languages
78. in March 2000 I use these as a last resort If you get stuck then have a look to see if there is an example that does some or all of what you are trying to do Redoing the earlier examples Ian D Chivers email ian chivers kcl ac uk 173 Introduction to Graphics Programming Chapter 11 We will now look at redoing some of the earlier examples to use the newer preferred meth ods 11 30Simple bouncing ball import java awt import java awt event import java awt geom import java awt image import javax swing public class graphicll extends java applet Applet implements Runnable a double x y deltax deltay double x1 300 double y12300 Thread ball public void init setBackground Color white deltax Math random deltay Math random x Math random xl y Math random yl public void start if ball nu11 ball new Thread this ball start public void stop if ball 2null ball stop ball null public void run for x deltax email ian chivers Q kcl ac uk O Ian D Chivers Chapter 11 Introduction to Graphics Programming 174 yt deltay if x gt x1 x lt 0 deltax deltax if y gt y1 y lt 0 deltay deltay repaint try Thread sleep 1 catch InterruptedException e public void paint Graphics g Gr
79. is a numeric variable of type float It is given an initial value of 1 0 note the f extension on the initial value All numeric variables are of type double by default in Java Float F new Float f F is an object of type Float There is the concept in Java of fundamental data types and ob jects For each fundamental data type there is a corresponding object so float and Float are two very different concepts This object is given an inital value by the new Float f state ment System out println Type in a number This prints a text prompt on the screen email ian chivers kcl ac uk Ian D Chivers Chapter 3 An Introduction to Java 56 Line in readLine This reads in the text that the user types into Line All interaction is done using String ob jects F Float valueOf Line This statement extracts the numeric value from the text typed in Note that line is of type String and hence is an object and we are extracting an object of type Float from this text string f F floatValue This converts from a Float object to the build in float data type System out printin f This statement echos the numeric value back to the user catch IOException e In the event of an i o error control passes to this statement System out println Exceptions raised e In the event of an error the above message appears on the screen As you have all programmed using other languages the above appears very long winded
80. listener object using the extended class and then register it with a Window using the window s addWindowListener method When the window s status changes by virtue of being opened closed activated or deactivated iconified or deiconified the relevant method in the listener object is invoked and the WindowEvent is passed to it Experiment with the sleep time We will look into the above in more detail in later chapters 11 31 Bouncing balls with selective erase ke import java awt import java awt event import java awt geom import java awt image import javax swing public class graphicl2 extends java applet Applet implements Runnable email ian chivers Q kcl ac uk O Ian D Chivers Chapter 11 Introduction to Graphics Programming 176 double x y deltax deltay oldx oldy double x1 300 double y12300 Thread ball BufferedImage bgi Graphics bgg public void init setBackground Color white deltax Math random deltay Math random x Math random x1 y Math random yl bgi BufferedImage createlmage this size width this size height bgg bgi getGraphics public void start if ball nu11 ball new Thread this ball start public void stop if ball 2null ball stop ball null public void paint Graphics g Graphics2D g2d Graphics2D g bgg setC
81. merical values or components The ColorSpace class contains methods for converting be tween the color space and two standard color spaces CI EXYZ and RGB email ian chivers Q kcl ac uk O Ian D Chivers Chapter 11 Introduction to Graphics Programming 172 A Color is a fixed color defined in terms of its components in a particular ColorSpace To draw a Shape in a color such as red you pass a Color object representing that color to the Graphics2D cont ext Color is defined in the java awt package A ColorModel describes a particular way that pixel values are mapped to colors A ColorModel is typically associated with an Image or BufferedImage and provides the infor mation necessary to correctly interpret the pixel values ColorModel is defined in the java awt image package 11 29 11 ColorModels and Color Data and the BufferedImage Class In addition to the Raster object for managing image data the BufferedImage class includes a ColorModel for interpreting that data as color pixel values The abstract ColorModel class defines methods for turning an image s pixel data into a color value in its associated ColorSpace The java awt image package provides four types of color models PackedColorModel An abstract ColorModel that represents pixel values that have color components embedded directly in the bits of an integer pixel A DirectColorModel is a subclass of PackedColorModel DirectColorModel a ColorModel that represents pixel valu
82. name File destination file new File dest name FileInputStream source null FileOutputStream destination null byte buffer int bytes reag e e try First make sure the specified source file exists is a file and is readable if source_file exists source_file isFile throw new FileCopyException FileCopy no such source file source_name if source file canRead throw new FileCopyException FileCopy source file 4 is unreadable source name If the destination exists make sure it is a writeable file and ask before overwriting it If the destination doesn t exist make sure the directory exists and is writeable if destination file exists if destination file isFile DatalnputStream in new DatalnputStream System in String response email ian chivers kcl ac uk Ian D Chivers Chapter 8 Exceptions 114 if destination file canWrite throw new FileCopyException FileCopy destination file is unwriteable dest name System out print File System out print dest name System out print already exists Overwrite d Y N System out flush response in readLine if response equals yY amp amp response equals y throw new FileCopyException FileCopy copy cancelled else thro
83. new File source name File destination file new File dest name FileInputStream source null FileOutputStream destination null byte buffer int bytes reag e e try 1 First make sure the specified source file exists is a file and is readable if source file exists source file isFile throw new convertException convert no such source files cr Source name if source file canRead throw new convertException convert source file is unreadable source name If the destination exists make sure it is a writeable file and ask before overwriting it If the destination doesn t exist make sure the directory exists and is writeable if destination file exists if destination file isFile DatalnputStream in new DatalnputStream Sys tem in String response if destination file canWrite throw new convertException convert des tination file is unwriteable dest name System out print File dest name already exists Overwrite Y N TN System out flush response in readLine if response equals Y amp amp re sponse equals y email ian chivers Q kcl ac uk O Ian D Chivers Chapter 9 i o 126 throw new convertException convert copy cancelled else throw new convertException convert destina tion is not a file
84. new JButton Arsenal add new JButton Spurs add new JButton Chelsea add new JButton West Ham add new JButton Crystal Palace 14 11 3 GridLayout Not available at this time 14 11 4 Gridlayout with size Not available at this time 14 11 5 GridBagLayout Not available at this time 14 11 6 CardLayout Not available at this time 14 11 7 Simple Graph Plotting AWT Based This example shows how to plot a sine curve and it does so using an AWT based ap proach import java awt import java lang Math public class c1180 extends java applet Applet public void init setBackground Color white email ian chivers Okcl ac uk O lan D Chivers Chapter 14 Swing 222 public void paint Graphics g int x 0 y 180 ct ct int int angled double angler g setColor Color blue for angled 0 angled lt 361 angled X angleg g drawLine x y X y angler angled 2 Math P1 360 Y 180 int 180 Math sin angler Things to note include The origin at the top left causes a few problems We are forced to shift the y values down and in this exam ple I have chosen 180 I have also scaled the values returned by the sine function We are forced to qualify both PI and the sine function with Math This is a little verbose 14 11 8 Simple Graph Plotting Swing Based This is the same example but now we use the new Swing w
85. out print j if 3 gt 10 break goto2 if j gt 5 amp j lt 7 break gotol else System out printin in the else clause continue System out printin When will we get here Study the program to see if you can predict what the output will be Now type the program in and compile and run it Were you correct 7 11 Summary Java has a decent set of control structures They provide us with most of the functionality we require 7 12 Problems 1 Write a program to print out the 12 times table Output should be roughly of the form 1 12 12 2 12 24 2 Write a program that produces a conversion table from litres to pints and vice versa One litre is approximately 1 3 4 pints The output should comprise three columns The middle column should be an integer and the columns to the left and right should be the correspond ing pints and litre values This enables the middle column to be scanned quickly and the corresponding equivalent in litres or pints read easily email ian chivers kcl ac uk Ian D Chivers Chapter 7 Control Structures 104 3 Rewrite the program for the period of a pendulum The new program should print out the length of the pendulum and period for lengths of the pendulum from 0 to 100 cm in steps of 0 5 cm The physical world has many examples where processes require some threshold to be over come before they begin operation critical mass in nuclear reactions a given s
86. properties The Component object on which to draw A translation origin for rendering and clipping coordinates The current clip The current color The current font The current logical pixel operation function XOR or Paint O lan D Chivers email ian chivers kcl ac uk 161 Introduction to Graphics Programming Chapter 11 The current XOR alternation color see setXORMode java awt Color Coordinates are infinitely thin and lie between the pixels of the output device Operations that draw the outline of a figure operate by traversing an infinitely thin path between pixels with a pixel sized pen that hangs down and to the right of the anchor point on the path This means If you draw a figure that covers a given rectangle that figure occupies one extra row of pixels on the right and bottom edges as compared to filling a figure that 1s bounded by that same rectangle If you draw a horizontal line along the same y coordinate as the baseline of a line of text that line is drawn entirely below the text except for any descenders Operations that fill a figure operate by filling the interior of that infinitely thin path Opera tions that render horizontal text render the ascending portion of character glyphs entirely above the baseline coordinate All coordinates that appear as arguments to the methods of this Graphics object are consid ered relative to the translation origin of this Graphics object prior to the invocation of the
87. reete etri e e ener due certe tegere Date 171 1129 10 O O 171 11 29 11 ColorModels and Color Data and the BufferedImage Class esses 172 11 29 12 Printing ren eei tede ep qute e tee Pee ien 172 11 30 Simple bouncing disc asas du tb ees AREE eb RN addu 173 11 30 1 InitialisatiOni sss ica a eade dig edi repleri eate 175 11 30 2 JEAN C RE 175 11 30 3 add Window Listeners citroen eie adn i ERE EE Le e cv P dices 175 11 30 4 Class Window Adapter cil eru oe ret ea ea tbe Iii tee Hoe ib aepo oe bee ohne 175 11 31 Bouncing balls with selective erase 4 ettet eterna ee eed et da ree ones 175 11 32 Simple pea displasia Il ee el de eeu eth aS 178 11 33 Simple hine drawing iaa iones celia 179 1134 Summa y e eree aasa Nim Ea suae leta aie E loea bus ao de Stas E O a a aE neasi 179 11 39 Problems tenisean a CIR AA AN E A A ANE 180 O 186 12 AWT Based Windows Programming ccccccccccsssssssccccssssssccssssssscscssesssees 190 MID Bl a ai 190 22 A E E E E 190 12 3 Button and Label arial ia taa 190 IZA Scroll aa O E E ct 191 12 5 Scrollbar with size information ius ecce diciendo a calla 191 12 07 CHeCEDONX A Ras sedan Masa a m een titu D Dial a desees auge iE 191 12 7 MCHC CK DOR with OTOU Ing 5595 8 aessodtoteddac a Codi uos 191 Contents 9 ET MADE AO 192 12 91 A TEISES 192 12 10 Pass WO Srita 192 E MA A A tential cocvenadaat tated a A ten tye E ae 193 1212 Eros cH 193 12 12 1 Panels 22s NO AN 19
88. roll gameStatus LOST point setText clear point text field break default remember point gameStatus CONTINUE myPoint sumOfDice point setText Integer toString myPoint firstRoll false break else sumOfDice rollDice if sumOfDice myPoint win by making point gameStatus WON else if sumOfDice 7 lose by roll ing 7 gameStatus LOST if gameStatus CONTINUE showStatus Roll again else O Ian D Chivers email ian chivers Okcl ac uk 211 Events Chapter 13 if gameStatus WON showStatus Player wins Click Roll Dice to play again else showStatus Player loses Click Roll Dice to play again firstRoll true roll the dice public int rollDice int diel die2 workSum diel 1 int Math random 6 die2 1 int Math random 6 workSum diel die2 firstDie setText Integer toString diel secondDie setText Integer toString die2 sum setText Integer toString workSum return workSum J RCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKCKC AECkck ck ck ck ck k ck k kk C Copyright 1999 by Deitel amp Associates Inc and Prentice Hall a All Rights Reserved DISCLAIMER The authors and publisher of this
89. rotate double theta Ian D Chivers email ian chivers kcl ac uk 167 Introduction to Graphics Programming Chapter 11 Concatenates the current Graphics2D Transform with a rotation transform abstract void rotate double theta double x double y Concatenates the current Graphics2D Transform with a translated rotation trans form abstract void scale double sx double sy Concatenates the current Graphics2D Transform with a scaling transformation Subsequent rendering is resized according to the specified scaling factors relative to the previous scaling abstract void setBackground Color color Sets the background color for the Graphics2D context abstract void setComposite Composite comp Sets the Composite for the Graphics2D context abstract void setPaint Paint paint Sets the Paint attribute for the Graphics2D context abstract void setRenderingHint RenderingHints Key hintKey Object hintValue Sets the value of a single preference for the rendering algorithms abstract void setRenderingHints Map hints Replaces the values of all preferences for the rendering algorithms with the spec ified hints abstract void setStroke Stroke s Sets the Stroke for the Graphics2D context abstract void setTransform AffineTransform Tx Sets the Transform in the Graphics2D context abstract void shear double shx double shy Concatenates the current Graphics2D Transform with a shearing transform abstract void transform AffineTransform Tx
90. servlet 276 ml Servlets Apr 2 1999 index html Apr 2 1999 regheaders html Apr 2 1999 reqinfo html Apr 2 1999 reqparams ht Apr 2 1999 sessions html 12920 Apr 27 1999 GenericServlet java 234 Apr 27 1999 LocalStrings properties 4634 Apr 27 1999 RequestDispatcher java 6846 Apr 27 1999 Servlet java 3147 Apr 27 1999 ServletConfig java 16714 Apr 27 1999 ServletContext java 3957 Apr 27 1999 ServletException java 3169 Apr 27 1999 ServletInputStream java 8939 Apr 27 1999 ServletOutputStream java 12239 Apr 27 1999 ServletRequest java 6269 Apr 27 1999 ServletResponse java T213 Apr 27 1999 SingleThreadModel java 5802 Apr 27 1999 UnavailableException java src javax servlet http 15649 Apr 27 1999 Cookie java 32100 Apr 27 1999 HttpServlet java 14856 Apr 27 1999 HttpServletRequest java 18425 Apr 27 1999 HttpServletResponse java 10584 Apr 27 1999 HttpSession java 2950 Apr 27 1999 HttpSessionBindingEvent java 1966 Apr 27 1999 HttpSessionBindingListener java 1895 Apr 27 1999 HttpSessionContext java 8826 Apr 27 1999 HttpUtils java 720 Apr 27 1999 LocalStrings properties src javax servlet jsp 622 Apr 27 1999 HttpJspPage java 660 Apr 27 1999 JSPPage java tmp tmp 1b6f5a49 tmp 35475a49 webpages 1967 Apr 28 1999 index html O lan D Chivers email ian chivers Okcl ac uk 277 we
91. stepping from 0 360 instead of 180 180 The major advance over C is the built in subscript check ing something which can only be achieved in C through operator overloading 6 8 Problems 1 Type in and run some of the examples in this chapter Modify the program to go outside of the array bound What run time messages do you get 2 Write a program to assign the following data values into a 3 3 array 1 2 3 4 5 6 7 8 9 Produce totals for each row and column It should produce output as shown below 1 2 3 6 4 5 6 15 7 8 9 24 12 15 18 After successfully doing this modify the program to produce averages for each row and col umn as well 3 The data below has been taken from a group of first year undergraduates It is their heights and weights 1 85 85 1 80 76 1 85 85 T70 90 1 55 69 1 64 83 1 55 64 1 63 5 1 79 65 1 48 76 Your body mass index is given by your height in metres squared divided by your weight in kilos Calulate the BMI for each person Use arrays to hold the height and weight infor mation Grades of obesity according to Garrow as follows Grade 0 desirable 20 24 9 Grade 1 overweight 25 29 9 Grade 2 obese 30 40 Grad 3 morbidly obese gt 40 Ideal BMI range Men Range 20 1 to 25 kg m Women Range 18 7 to 23 8 kg m If you know your own height and weight modify the above to calculate your own BMI O Ian D Chivers email ian chivers Okcl ac uk 7 Control Structures Summarising
92. they are given below with examples 11 22 1 Lines g drawline x1 y1 x2 y2 import java awt public class c1140 extends java applet Applet public void init setBackground Color white public void paint Graphics g int x1 0 int yl 0 int x2 100 int y2 200 g setColor Color blue g drawLine x1 y1 x2 y2 11 22 2 Rectangles g drawRect xstart ystart width height g fillRect x y w h import java awt public class c1142 extends Java applet Applet email ian chivers kcl ac uk Ian D Chivers Chapter 11 Introduction to Graphics Programming 150 public void init setBackground Color white public void paint Graphics g g setColor Color blue g drawRect 10 10 100 100 import java awt public class c1143 extends java applet Applet public void init setBackground Color white public void paint Graphics g g setColor Color blue g drawRect 10 10 100 100 g fillRect 20 20 90 90 11 22 3 Rounded Rectangles g drawRoundRect xstart ystart w h xcurve ycurve import java awt public class c1144 extends java applet Applet public void init setBackground Color white public void paint Graphics g g setColor Color blue g drawRoundRect 10 10 100 100 20 20 O lan D Chivers email ian chivers Okcl ac uk 151 Introduction to Graphics Programming Chapter 11
93. to Programming Languages and Object Oriented Programming We have to go to another language in order to think clearly about the problem Samuel R Delany Babel 17 Aims The primary aim of this chapter is to look at some of the languages used in the sci ences There is a look at the developments from a historical view point a compari son of their features and a look at future developments Chapter 2 An Introduction to Programming Languages 24 and Object Oriented Programming 2 An Introduction to Programming Languages and Object Oriented Programming The intention of this chapter is to examine from the viewpoint of languages of use in scien tific problem solving of the background of programming languages and their development It is essential that you develop an understanding of why there are so many programming languages and their strengths and weaknesses No one language is suitable for solving all the problems that you will come across You need to chose the right tool for the job Think about diy around the home If the only tool you have is a hammer then everything seems to be seen as a nail See the bibliography for a broader coverage 2 1 Fortran 66 1966 The original was designed by a team lead by Backus at IBM in the late 50 s It is therefore quite old This is the date of the first standard The language quickly established itself as the language of first choice for numeric programming 2 2 Pascal 1975 ANSI amp B
94. to attempt a reasonable size application in C using OO techniques then you should read this book He clearly highlights some of the major pitfalls He provides both academic and commercial courses on C and Eiffel 2 11 Ada ISO 8652 1995 Latest standard Major changes from the 1987 standard are in the areas of Support for 8 and 16 bit character sets Object oriented programming with run time polymorphism Extension of access types Efficient data oriented synchronisation library units interfacing to other languages There are several so called Specialised Needs Annexes These are Annex C Systems Programming Annex D Real Time Systems Annex E Distributed Systems Annex F Information Systems Ian D Chivers email ian chivers kcl ac uk 27 An Introduction to Programming Languages Chapter 2 and Object Oriented Programming Annex G Numerics Annex H Safety and Security 2 12 Java Bill Joy of Sun fame had by the late 1980 s decided that C was too complicated and that an object oriented environment based upon C would be of use At round about the same time James Gosling mister emacs was starting to get frustrated with the implementa tion of an SGML editor in C Oak was the outcome of Gosling s frustration Sun over the next few years ended up developing Oak for a variety of projects It wasn t un til Sun developed their own web browser Hotjava that Java as a language hit the streets And as the saying go
95. types Note that these are object methods You must convert from the base object to the underlying base Java type A subset is given below public abstract boolean read Boolean throws IOException EOFException public abstract byte readByte throws IOException EOFException public abstract char readChar throws IOException EOFException public abstract double readDouble throws IOException EOFException public abstract float readFloat throws IOException EOFException public abstract int readInt throws IOException EOFException public abstract String readLine throws IOException EOFException public abstract long readLong throws IOException EOFException public abstract short readShort throws IOException EOFException public abstract String readUTF throws IOException EOFException public abstract int readUnsignedByte throws IOException EOFException public abstract int readUnsignedShort throws IOException EOFException 9 2 1 UTE Most text is 7 or 8 bit based Most computer systems support 8 bit characters Whilst Java uses 16 bit characters internally throughout a large part of the ineraction with the real world will be in terms of 8 bit characters email ian chivers Q kcl ac uk O Ian D Chivers Chapter 9 i o 122 To aid here Java supports UTF 8 which is a multibyte coding scheme The standard ASCII characters only occupy 1 byte Thus for text which is essentially ASCII we have a much more compact data representation
96. up to June 1978 Sessions on Fortran Algol Lisp Cobol APT Jovial GPSS Simula JOSS Basic PL I Snobol and APL with speakers involved in the original lan guages Very highly recommended Wiener R Software Development using Eiffel There Can Be Life Other than C Prentice Hall e Well written and the case studies include an ecological simulation a game of strategies and investments and simulated annealing The chapter on object ori ented analysis and design is highly recommended O lan D Chivers email ian chivers kcl ac uk 45 An Introduction to Programming Languages Chapter 2 and Object Oriented Programming Wiener R Software Development Using Eiffel There Can be Life After C Prentice Hall e Very well written I d really recommend getting hold of this book if you are go ing to seriously program in C using oo techniques He teaches both academic and commercial Eiffel and C courses He knows his stuff Winder R Roberts G Developing Java software Wiley e Waiting to get a copy Wirth N An Assessment of the Programming Language Pascal IEEE Transactions on Software Engineering June 1975 192 198 Wirth N Program Development by Stepwise Refinement Communications of the ACM April 1971 e Clear and simple exposition of the ideas of stepwise refinement Wirth N History and Goals of Modula 2 Byte August 1984 145 152 e Straight from the horse s mouth Wirth N On the Design of Programming Langua
97. virtual class functions 2 20 4 Eiffel Object Oriented Software Construction is dated 1988 As stated earlier the first four chap ters address OOP The latter chapters look at Eiffel in some depth The text is a relatively easy read Achieves much of the power and expressiveness of C without the complexity As is has its origins in Ada is is also a language that offers far greater support for error protection and safe code I m informed that the Channel Tunnel software uses Eiffel I am looking at getting hold of an Eiffel compiler at this time but am unsure as to what platform it might be available on 2 20 5 Oberon 2 The language has its origins in a visit that Gutnecht and Wirth made to Xerox PARC in 1985 They decided to design and implement a new operating system In their words the ultimate goal was to create a system for personal workstations that was not only powerful and convenient for practical use but also describable and explicable in a convincing way They had originally decided to use Modula 2 but made the decision to strip out some of the email ian chivers kcl ac uk Ian D Chivers Chapter 2 An Introduction to Programming Languages 34 and Object Oriented Programming features of that language and add a very small number of features The outcome was Oberon The language was defined in 1986 The object code size of the outer core of the Oberon system is 200K and comprises a kernel a dynamic loader and garba
98. void fillRect int x int y int width int height Fills the specified rectangle abstract void fillRoundRect int x int y int width int height int arcWidth int arcHeight Fills the specified rounded corner rectangle with the current color void finalize Disposes of this graphics context once it is no longer referenced abstract Shape getClip Gets the current clipping area abstract Rectangle getClipBounds Returns the bounding rectangle of the current clipping area Rectangle getClipBounds Rectangle r Returns the bounding rectangle of the current clipping area Rectangle getClipRect Deprecated As of JDK version 1 1 replaced by getClipBounds abstract Color getColor Gets this graphics context s current color email ian chivers kcl ac uk Ian D Chivers Chapter 11 Introduction to Graphics Programming 164 abstract Font getFont Gets the current font FontMetrics getFontMetrics Gets the font metrics of the current font abstract FontMetrics getFontMetrics Font f Gets the font metrics for the specified font boolean hitClip int x int y int width int height Returns true 1f the specified rectangular area intersects the bounding rectangle of the current clipping area abstract void setClip int x int y int width int height Sets the current clip to the rectangle specified by the given coordinates abstract void setClip Shape clip Sets the current clipping area to an arbitrary clip shape abstract void se
99. your code itself We have the following two class hierarchies Object Throwable Exception and Object Throwable Error and the actual errors and exception methods are at the next level down in the tree 8 9 Java On line Documentation Rather than cluuter up the notes with a complete list of all of the exceptions and errors that can arise in Java have a look at the documentation that comes with the Java 1 1 develop ment kit I ve put this up on the College web server and you can download and install this file on a system that runs both Netscape and supports long file names This provides a very good on line source of information regarding Java I will try to get it installed on the Sun that we are using for the course also 8 10 Summary There are a number of examples that cover this area in more depth later in the course as it is best to see exception handling done in a realistic context to appreciate the power and ex pressiveness that the concepts provide 8 11 Problems 1 Try writing a Java version of the linked list examples in this chapter There are a number of catches here 2 Try running the example program in this chapter I ve put it up on the Web server Base url is http www kcl ac uk support cc fortran home html This method can easily be incorporated into any program that requires it very easily email ian chivers Q kcl ac uk O Ian D Chivers Winnie the Pooh read the two notices very carefully first f
100. 0302 public static void main String args try InputStream i System in DatalnputStream in new DatalnputStream i String Line System out printlin Type in a line of text Line in readLine System out println Line catch IOException e System out println Exceptions raised e If there is an error getting a line of input from the user within the body of the try block con trol will pass to the catch statement and in this case an informative message is issued about the error The readLine method can throw an IOException We will come back to look at the above example after we have covered i o in more depth The general syntax is try email ian chivers kcl ac uk Ian D Chivers Chapter 8 Exceptions 112 catch Exception 1 e catch Exception_2 e finally 8 4 1 try The try block can have zero or more catch clauses An abnormal exit is one of break continue return exception propagation 8 4 2 catch These are the exception handlers They actually carry out thw work of handling the excep tion that was raised in the try block The argument of the catch must be of type Throwable or subclass We will look into this in more depth in the complete file copy program in this chapter 8 4 3 finally This part is executed after normal termination of the try block after an exception handled in a catch clause after an ex
101. 1 abstract void drawPolyline int xPoints int yPoints int nPoints Draws a sequence of connected lines defined by arrays of x and y coordinates void drawRect int x int y int width int height Draws the outline of the specified rectangle abstract void drawRoundRect int x int y int width int height int arcWidth int arcHeight Draws an outlined round cornered rectangle using this graphics context s current color abstract void drawString AttributedCharacterlterator iterator int x int y Draws the text given by the specified iterator using this graphics context s cur rent color abstract void drawString String str int x int y Draws the text given by the specified string using this graphics context s current font and color void fill3DRect int x int y int width int height boolean raised Paints a 3 D highlighted rectangle filled with the current color abstract void fillArc int x int y int width int height int startAngle int arcAngle Fills a circular or elliptical arc covering the specified rectangle abstract void fillOval int x int y int width int height Fills an oval bounded by the specified rectangle with the current color abstract void fillPolygon int xPoints int yPoints int nPoints Fills a closed polygon defined by arrays of x and y coordinates void fillPolygon Polygon p Fills the polygon defined by the specified Polygon object with the graphics con text s current color abstract
102. 1 2 1 DnDConstants c etre reete tere ate degere eee to cene eda 292 26 1 2 2 DragGestureByvent urere eene tg itp De pe PEE Ue Seg ea Een beca 292 26 1 2 3 DragGestureReCcognizer ice ient IH LH rtt jasa TO BER R nae cete eve ends 292 26 1 2 4 Drap OU di bs 292 14 Contents 26 1 2 5 DragSourceC ontext iii lili 293 26 1 2 6 Drag Source Drag Event ius lin ente acces 293 26 1 2 7 DragSouiceDtropEVent 5 2 S gti ERE e EUR EXER ned sbi gines diia 293 26 1 2 8 DtragSoutrceByvent iniciara teet iios lage e ete edet NEEE 293 26 1 2 9 Drop Target sane ec eee ees 293 26 1 2 10 DropTarget DropTargetAutoScroller eene 293 26 1 2 11 DropT atgetCOontext eee Repo heiter i Dee EDI ER Re een wen ER 293 26 1 2 12 Drop TargetDragE Vente nacio e dee ette cse p bere taber Re aget oe iot idees 293 26 1 2 13 DropTargetDropEvent A teet enter err a enin 293 26 1 2 14 DroptargetEyvent 2 Ue e RR epu ie RAI oe 293 26 1 2 15 MouseDragGestureRecognizer eese nennen nennen nennen 293 26 1 3 Exception Surminary oil es Siete dele Ge dev cadens Ig o sdb Ue Oe ge ce pa peces ee Ege ea 293 26 1 3 1 InvalidDnDOperationException eese nennen nennen nnne 293 26 Bibhopraphy tn eee te e i qoot esie dest ees ct E ule de 294 27 TICE APH mei asin iii 296 A O rr A E E 296 21 2 ABEE 754 PECAR its 297 27 2 1 Single precision floating point format 0 0 0 0 ce eese eren nre 298 27 2 2 Double precision floating po
103. 14 7 1 Model TN 216 14 7 2 MIe Wing tp HEU PU e esque regit e io Eds 216 14 7 3 Controller iaa etie reete eee Di e eoi ch atten aede deterret depo 216 148 Multithr adin a ei A Sed ense esed me L 216 2 0 Compolletibi sexus A E e eS 216 1410 2S mpleBXATmples E A E cpi E 217 14 10 1 A O RAN 217 14 10 2 JL bel etenim eee he Hd d e cil 217 10 Contents 14 10 3 Button and Label acean iii 218 14 10 4 ISC E TENES 218 14 10 5 JScrollBar with size information esses ener nennen ettet enne nns 218 14 10 6 aucune 219 14 10 7 CheckBox with Grouping ia oe deed ede deudas 219 14 10 8 Ec m E EY 219 14 10 9 TextField ae s 220 1410 105 Passwords x eec oe iaeiae Gere iia isos 220 TA TOIT gt NCC 220 PAA ToAVOUU A O E 220 14 11 1 A E 221 14 11 2 FlowLayout enna a A ohn epe n A en atin A dS 221 14 11 3 GrdLbayouts a meierei Ot terre ree stan dove dan cts 221 14 11 4 Gridlay out with SIZE A Ria 221 14 11 5 Grd Baslay Out 2 relie dt eset ee rece e lect ete dta soe reote eiue 221 14 11 6 inibi A 221 14 11 7 Simple Graph Plotting AWT Based eese nennen nen 221 14 11 8 Simple Graph Plotting Swing Based eese 222 14212 Inhieritence ReEVISHIOQ ceo secat ode 223 I MEE d mu rS 223 14 14 Swing Containers and JComponent essere nennen 224 LAN Examples e D eo DUE 225 14 16 Problems c
104. 199 Events Chapter 13 l new TextArea 5 10 l setText s CE ut t2 new TextArea 5 20 b new Button copy text gt setLayout new FlowLayout FlowLayout LEFT 5 5 add t1 add b add t2 public boolean action Event e Object o if e target b t2 setText tl getSelectedText return true return false 13 1 4 Example 2 Simple mouse tracking import import java applet Applet java awt Im CT public class c1402 extends Applet public boolean mouseMove Event int x int y showStatus Mouse at x y return true 13 1 5 Example 3 Mouse with drag import import java applet Applet java awt public class c1403 extends Applet private int x y private boolean firsttime public void init email ian chivers kcl ac uk Ian D Chivers Chapter 13 Events 200 firsttime true public void paint Graphics g if firsttime g fillOval x y 4 4 public void update Graphics g paint 9 public boolean mouseDrag Event e int xx int yy X XX VY Y 5 firsttime false repaint showStatus Event mouse drag return true 13 1 6 Example 4 Key up and key down import import java applet Applet java awt ct ct public class c1404 extends Applet private Font f private String letter private boolean first public void init
105. 2 2 20 Object Oriented Lana E east lade aston de edes ae 33 2 20 1 simula 90 ita du dee o EE Ute ARAE RENE E RE edo 33 2 20 2 Smalltalk 1978 anion o qe HC E teen said 33 2 20 3 O 33 2 20 4 A EM 33 4 Contents 2 20 5 Oberon a il 33 2 20 6 Ad o o al Besitos po tects do de Ob cito cto sae DU leg oe le 34 2 20 7 OS 34 221 Other LAM SU E 35 2 21 1 Fortran 90 and Fortran 95 cete nene Lee HR Ee er oso nai Se Ye cese RM ire ole dn 35 2 21 2 hype 35 2 22 Ihe OO Approach eee Dec Le E RR OU axi esas s Ue E pen ERU RINT SERA ades cadens 35 2 22 1 Meyers Apptoacb thai iie ete e ra te o er ai eer tee talado eed oo 35 2 22 2 Rumbaugh et al rene rte Re rete rede ter inttr 36 2 22 3 Practical Steps emet eiecit ae beet 36 2 23 Simple Example ec riada SEE E Be rai RU Te 37 2 24 Other Developing 38 2 24 1 Development EnViIronmMe tS aseeni nn aatinaa oa a ie e tden 38 2 24 2 Graphical Development Tools esee eene rennen nennen 38 2 24 3 Software Components duration eei o eH nce iE eeu Ea 38 2 24 3 1 COM OLE AGCUV6X 2 atin tii 39 2 24 3 2 A EE 39 A So RC Er 39 2 20 TO 40 2521 O O 45 3 An Introduction to Java e seessesssossoossossoosseossoossoessossoossoossosssosssosssossoessossooossosss 48 3 1 luco acing dense E 48 3 2 dava Program cae ed otio Sequin ie eoo e goss bevy a th IUE eu i deep Oed ow pco ev Peg anea 48 3 3 JAVA Applets vainas E E A E T A EE E ES 48 3 4 Hello Worl
106. 3 12 12 2 POW Lay A A 193 12 12 3 Gay Ultra AA dd IAT al des 194 12 12 4 Gridlay out With S1Z6 se aene A ee I etes 194 12 12 5 Gr dBagLayout einer e e ede ae a edere Dae ge e dre ft 195 12 12 6 CardLayout ettet IR c ee deiecit Ente ERG ere Haee E teet ae cede eda 195 12 13 Putting it all TOPE DOE rt ida 196 1214 Problems P 196 I3 ENQHfs coena ani va Pv ER EE QU clio 198 V3 Lig o HP O 198 13 1 1 Mouse Eves ierre eae valida iii ed Ee Erie pe EHE aaa E Re In tad 198 13 1 2 Keyboard events utilidades dois 198 13 1 3 Example 1 Cut and paste text edades eere eae repete 198 13 1 4 Example 2 Simple mouse tracking eese 199 13 1 5 Example 3 Mouse with drag ipee eee ERE LER CREER 199 13 1 6 Example 4 Key up and key down eese 200 13 2 Swing Event Handling As of JDK 1 2 2 seeseeeeeeeeeeneeeneeennnnen 201 13 2 1 Interface S mimiay 1 n orto tre d the Pe bietet een Lets Feo Haee a eee et tetti di pgs 201 13 2 2 Class Summaty E eI EO EE eade 203 13 2 3 Package Javax SWing eVent c uio aee tete itte tee opt Ure Cep Pee dae ote ende Dente Ee toe ote o e De e doe Dono 204 13 5 O raen ae Quat orem UV ee boda Usine Gelman besote hin idu 204 1374 ACUM oia 205 13 5 Example Vision dit latencia 205 13 5 1 TAMOS C edito DE E it di a iia ts 208 13 5 2 super Constructor Chaining sonene eren
107. 33 means repeat the loop whilst count is less than 33 count means increment count by 1 each time round the loop ib byte 1_b 2 In this example we are forced to cast the expression 1_b 2 from its default type of int back to byte This is because an integer literal a number has a default type of int Hence the 2 forces the expression i_b 2 to be promoted to be of type int This is the Java syntax for casting is short i_s 2 In this example we are forced to cast the expression 1_s 2 from int to short i 1 2 Familiar arithmetic expression and assignment et sp unie Familiar arithmetic expression and assignment In this case 2 is promoted to type long by Java automatically email ian chivers Q kcl ac uk O Ian D Chivers Chapter 4 Arithmetic and Expressions in Java 62 i b System out print my i s System out print ys i System out print ui i 1 System out printlin System out prin System out prin System out prin System out prin cl El El El El Print out the values The for loop will terminate when count reaches 32 4 3 Real Numeric Type Java uses the IEEE 754 1985 standard as a basis for floating point data types and arithemtic Two types are required to be supported and these are float and double Within this standard there are the concepts of overflow to infinity underflow to zero NAN or Not a Number for invalid expressions For floating point calc
108. 6 4 8 2 23 lt less than or equal expr lt expr isini iienaa ine nono conan conc eie r 66 4 8 2 24 2 greater than expr XP iaa e hd idees 66 4 8 2 25 gt greater than or equal expr gt exPirat nono non ene 66 4 8 2 26 equal expr expr ee dene a e e ete 66 4 8 2 27 not equal expr SOX pee 5 nre eite rita odds 66 4 8 2 28 amp bitwise AND expr amp expr cocococccocococononcnannnnnonnnonononnnonncnnn non nennen enne 66 4 8 2 29 bitwise exclusive OR expr OXPP cee eeeeeseeeseeeseceseceeeeneseneeeaeesaecnseesseeeneesaes 67 4 8 2 30 bitwise inclusive OR expr expr oo cee eeeesecneecneceeeceeeeeseecaaeceaeceeeeseeeseeeaaesnaees 67 4 8 2 31 amp amp logical AND expr amp amp expr sese 67 4 8 2 32 Il logical inclusive OR expr ll expr oo cece eee eene 67 4 8 2 33 conditional expression expr expr expr cocococonoccnncconnconnconnnnnnconnconncnnanananaconnnoos 67 4 8 2 34 conventional assignment expr EXPlecoconoccnoconoconocnnonononoconanonnnnn nono non rennen 67 4 8 2 35 multiply and assign expr expr ssseseseeeeeenren rennen enne 67 4 8 2 36 divide and assign expr expr sseeeeeenereneenn eene 67 4 8 2 37 modulo and assign Expr P EXPL eseeseeeneenren rennen 67 4 8 2 38 add and assign expr EXPE ninnisin e nono a eiae eea EE ei 67 4 8 2 39 subtract and assign expr expr ssesseeesseeeeee
109. 7 1 4 3 1 2 x aky Java 2 5 tuve pet HR E ERE UE STR Lee ER eS MER Hes 17 1 5 Development plat oS 21 4 saco oie qe te e ite E o e EEES EAEra A iS 17 1 6 Development kits and Standards deo erret ee ede Deis da 18 1 7 Miscellanea a es MS E G 18 1 8 Course Timetable idiot oeste o on lens ii a 19 1 9 ou MEL oO et ROT AT ie De a no OE CCP DENTE Pet nO A N A ENN OP Err POPE SET Ae 19 1 10 iuc CE 19 2 An Introduction to Programming Languages and Object Oriented Pro AMM IM OP RN Rum DE e etos UPC soda 24 2 1 Portranm 66 19060 tecti ea ehe et detinet ce treiber eet Nets eite etestte gts eres e 24 2 2 Pascal 1975 ANSI amp BSI 1982 ISO 1983 Extended Pascal 1991 24 2 3 Porttan 74 19185 tet atest ti ita 25 24 C K amp R 1978 Standard 1989 iei dsd 25 2 5 M o d l 2 1982 Standard 1996 sssini neitsist erei aces 25 2 6 Ada TSO 8652 1987 via a lt 25 2 7 C 1986 Standard November 1997 wii cessent nete eene nnns 25 2 8 Oberon 2 Late 980 s early T9090 a etit tisedue tied sed aaa 26 2 9 Fortran 90 LIV Lata het Bel ete redeo estet Rite teet ee er ede ute Bes 26 RI NE Eiffel 1988 Xr 26 2 110 Ada 150 8052 OOD ii A gut le quel gode ti dete SS 26 2 02 Jayda esca A de e ec ti tcd eei 27 ZAS Visual IB SNC eC I 27 2 14 Jansudee Comparisons opinan 27 25 Eanguage Pe3tutes oia id A A AE ASA 29 2 15 1 Independent Compilar lid io ode nu 29 2 15 2 Separate Compilation it etate re exe SOR DESEE NER LS SE
110. 99 package summary html 6360 Apr 21 1999 package tree html 7362 Apr 21 1999 package use html webpages docs api javax servlet http class use 6737 Apr 21 1999 Cookie html 4338 Apr 21 1999 HttpServlet html 11913 Apr 21 1999 HttpServletRequest html 10684 Apr 21 1999 HttpServletResponse html 8635 Apr 21 1999 HttpSession html 6799 Apr 21 1999 HttpSessionBindingEvent html 4451 Apr 2 1999 HttpSessionBindinglistener html 6137 Apr 21 1999 HttpSessionContext html 4324 Apr 21 1999 HttpUtils html 23 1 1 Notes 23 1 1 1 Jar files Copy the server jar and servlet jar files in the root directory into F jdk1 2 2 jre lib ext This is the JDK extensions directory You can t compile and run servlets without doing this 23 1 1 2 Start the server You must start the server This is done by running the Ian D Chivers email ian chivers kcl ac uk 279 Servlets Chapter 23 startserver bat file which is in the following directory f jdk1 2 2 jsdk2 1 on my system I get variable results with this Error messages include Can t set up server admin java rmi server ExportException Listen failed on port 1109 nested exception is java net SocketException Descriptor not a socket listen failed 23 1 1 3 Compiled class files You must copy all servlet class files to F jdk1 2 2 jsdk2 1 webpages WEB INF servlets to get them to ru
111. An Introduction to the Java Programming Language Abstract The primary aim of the notes are to provide an introduction to the Java programing lan guage It is assumed that you know one programming language moderately well There is a brief coverage of most of the features of the language and the emphasis is on breadth be fore depth The material in these notes evolves as Java evolves Author lan D Chivers Email ian chivers kcl ac uk Version 3 4 15 June 2001 Ian D Chivers Permission to copy all or part of this work is granted provided that the copies are not made or distributed for resale except a nominal copy fee may be charged and provided that the Author Copyright amp No Warranty sections are retained verbatim and are displayed conspicuously If anyone needs other permissions that aren t covered by the above please contact the author No Warranty this work is provided on an as is basis The author provides no warranty whatsoever either express or implied regarding the work including warranties with respect to its merchantability or fitness for any particular purpose All comments welcome Contents 3 Table of Contents Y O 16 1 1 A teas pita add and tic aac odes mie 16 1 2 JAsSUmptlODS A a a 16 1 3 Course Material and Recommended Sources eeeee 16 1 4 Java Versions Bits of History 4e eese ennt eot te tans ege ede Y nee Kg ende osito 17 1 4 1 B cR 17 1 4 2 MEE 1
112. Class Summary AlphaComposite This AlphaComposite class implements the basic alpha compositing rules for combining source and destination pixels to achieve blending and transparency ef fects with graphics and images AWTEvent The root event class for all AWT events AWTEventMulticaster A class which implements efficient and thread safe multi cast event dispatching for the AWT events defined in the java awt event package AWTPermission This class is for AWT permissions BasicStroke The BasicStroke class defines a basic set of rendering attributes for the outlines of graphics primitives BorderLayout A border layout lays out a container arranging and resizing its components to fit in five regions north south east west and center Button This class creates a labeled button Canvas A Canvas component represents a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user CardLayout A CardLayout object is a layout manager for a container Checkbox A check box is a graphical component that can be in either an on true or off false state CheckboxGroup The CheckboxGroup class is used to group together a set of Checkbox buttons CheckboxMenultem This class represents a check box that can be included in a menu Choice The Choice class presents a pop up menu of choices Color A class to encapsulate colors in the default sRGB color
113. DN Library the following documentation sets can be found Java Package Manager ActiveX Data Objects ADO Remote Data Service RDS Database Designer Query Designer VBScript JScript Active Server Pages ASP and server script Microsoft Transaction Server 18 5 Getting Started with Visual J 6 0 Microsoft Visual J is an integrated Windows hosted development tool for Java program ming If you have used Visual Basic then you will feel quite comfortable with the develop ment environment Visual J 6 0 introduces the Windows Foundation Classes for Java WEC This new application framework accesses the Microsoft Windows API enabling you to write full featured Windows applications with the Java programming language WFC also wraps the Dynamic HTML object model implemented in Internet Explorer 4 0 which allows you to dynamically manipulate HTML on both the client and the server 18 5 1 Creating a WFC Application When you create a Windows application with WFC your project contains a form that is the main window of the application You can then add WFC controls to the form to design the graphical user interface Use the Forms Designer to modify your form The RAD features of the Forms Designer al low you to quickly drop controls onto your form configure their properties and add event handlers Use Class Outline and the Text editor to modify your code Class Outline provides a dy namic view of the contents and structure of your Java c
114. EEs 29 2 15 3 Concrete Data iL ypes i 1 Lesbo Het er een ue ee eee rice terree Ee Heat NEEE ie 29 2 15 4 Abstract Data Vy pes sad ios ge dete Ee belt e ise 29 2 15 5 DINAMICA State 29 2 15 6 Numeric and General Polymorphism esee eene 29 2 15 7 Modules ert retient re dieat iet tertio Hte tiere RFT er i ER E IR PEDE 30 2 15 8 Pointers and References ss 5 2 eese erige OP e RR GR FG aR RE EET peda 30 2 15 9 Procedure Variables A 30 2 15 10 nostre ET 30 2 15 11 Dynamic Binding NO 30 2 15 12 Operator Overloading deem ede eer et nte Ire aho eder erect E e ROI EOM 30 2 15 13 Threads Multitasking inge e e ee Redde 30 2 15 14 Exception Handling td Hee eer decet dee FIG ee oe Pre edita 31 2 16 Some Important Milestones in Program Language Development 31 2 16 1 Structured Programming unte e aa i EE EEE A E Ep edere 31 2 16 2 Stepwis Refimemient e e ETE A eves aon se A A ET nent e 31 2 16 3 Data Structuring Concrete vs Abstract Data TyYP8S oooonocononcnonococnnonnnocnnnononnccnaconannnannnos 31 2 16 4 Information Hiding Modules seen enne 31 2 17 Terminology of Object Oriented Programming esee 31 ZaLs Parallel Developments e ld AA BG a dices 31 2 18 1 Parallel Fortran Fortran 95 Fortran 2000 SMP MPI HPF eese 32 2 18 2 Parallel CE or eger poene be D A RR 32 2 19 Object Oriented Programming a rs 3
115. Label pointlabel TextField firstDie secondDie sum point Button roll Ey CC setup graphical user interface components public void init Container c getContentPane c setLayout new FlowLayout dielLabel new JLabel Die 1 c add diellabel firstDie new JTextField 10 firstDie setEditable false c add firstDie die2Label new JLabel Die 2 c add die2Label secondDie new JTextField 10 secondDie setEditable false c add secondDie sumLabel new JLabel Sum is c add sumLabel sum new JTextField 10 sum setEditable false c add sum pointLabel new JLabel Point is c add pointLabel point new JTextField 10 point setEditable false c add point roll new JButton Roll Dice roll addActionListener this c add roll email ian chivers kcl ac uk Ian D Chivers Chapter 13 Events 210 call method play when button is pressed public void actionPerformed ActionEvent e play process one roll of the dice public void play if firstRoll first roll of the dice sumOfDice rollDice switch sumOfDice case 7 case 11 win on first roll gameStatus WON point setText clear point text field break case 2 case 3 case 12 lose on first
116. Line2D Rectangle2D and GeneralShape the Area class which provides mechanisms for add union subtract intersect and exclusiveOR operations on other Shape objects Provides the Java 2D classes for defining and performing operations on objects related to two dimensional geometry 11 26Package java awt im JDK 1 2 Provides classes and an interface for the input method framework This framework enables all text editing components to receive Japanese Chinese or Korean text input through input methods An input method lets users enter thousands of different characters using keyboards with far fewer keys Typically a sequence of several characters needs to be typed and then converted to create one or more characters Text editing components can use this package and related classes in java awt event to support the on the spot input style 11 27Package java awt image renderable JDK 1 2 Provides classes and interfaces for producing rendering independent images 11 28Package java awt print JDK 1 2 Provides classes and interfaces for a general printing API The API includes such features as the ability to specify document types mechanisms for control of page setup and page formats the ability to manage job control dialogs We will now look at rewriting our earlier examples to use the 1 2 x offerings in the graph ics area We need to cover a number of concepts first 11 29Java 2D API Overview The Java 2DTM API enhances the graphics
117. Of int ch public int indexOf String str public int lastindexOf int ch email ian chivers Q kcl ac uk O Ian D Chivers Chapter 5 Strings 82 public int lastIndexOf String str public int length public String replace char old char new public String substring int 1 public String toLowerCase public String toString public String toUpperCase public String trim The first set of methods are constructors that enable us to create objects of String types The second set of methods are class methods A static method doesn t act on specific instances of a class Remember that with object oriented programming we have to bring objects into existance so called instantiation Finally we have instance methods these actually act or work with String objects Note that we have several functions with the same name but different signatures This is called overloading It enables us to provide one name for what we want carried out and is a good example of abstraction The fact that there are several functions with the same name doesn t matter Note also that we have to have methods that convert between the base types and objects and vice versa 5 2 1 1 String Example 1 replace class c0503 public static void main String args String sl ababcadaeafa System out printin sl System out println sl replace a e System out printin sl The original String s1 is untouched
118. P di ii ONE u ee i ie aan Ee E cda 268 22 5 1 Interface Summary 1er tette pe c eS Ue UP iet ee ries ae eia Dor He eee 269 22 5 1 1 Airay JDBC 2 0 aiios tinet tr ae HP ey ete oe EHE Dee AI but 269 22 5 1 2 Blob IDB C2 eA eterne tentis Ree Pret te Fio ee PE PR REPRE YEN 269 22 5 1 3 CallableStateiment 3 ingentem ERREUR a ee ER Eti teta 269 22 5 1 4 Clob JDBC 2 reet eee etie ere lr tette eter er nr 269 22 5 1 5 Connector iee r E ET A A T E T dit 269 22 5 1 6 Dat baseMetaData 4 eoan eiee a oe Hee cete teet ec ene ede 269 22 5 1 7 Diver sanno is i N 269 22 5 1 8 PreparedStatemi nt ctn a E e a a to cepe ate 269 22 5 1 9 Ref JDBC 2 O 1 erre A ea eae 269 22 5 1 10 ResultSet cinean AE 269 22 5 1 11 ResultSetMetaData e aget eue eh ene A i er Re teet i teta 269 22 5 1 12 SQLData JDBG 2O casita triada tege eher p rtp 269 22 5 1 13 SOLInput JIDBC2 Di ii 269 22 5 1 14 SOLOutp t JDBC 2 0 ie ete esere tete etes rented ule inet pin 269 22 5 1 15 Statement 2 de gae ae ite qe aid 269 22 5 1 16 Struct IDBE 2 05 e o eei esee io cese cele Cone oeste ine P Ere DEEP a 269 22 5 2 A A Ne 269 22 5 2 1 Dieu 269 22 5 22 DrverManaget 5 og adds eee a its 269 22 5 2 3 DriverProperty lito tiara as 269 22 5 2 4 PUIG ici E 270 12 Contents 22 5 2 5 Timestamp catala aia id ia 270 22 5 2 6 Hu cl NR 270 22 5 3 Exception Summary roe ete idee Sea cok ns pP E Ene PE He a Saa EEE ERR T EHE
119. SI 1982 ISO 1983 Extended Pascal 1991 Very successful attempt at a teaching language Note that it precedes both C and Fortran 77 Pascal still is the most widely taught programming language in computer science de partments as the introductory programming language The following summarises the survey done by Dick Reid taken from a number of editions Language 20 18 15h 130 Pascal 140 144 151 157 C 101 100 87 34 Ada 82 82 74 73 C 58 56 51 39 Scheme 50 49 51 50 Modula 32 32 32 35 Java 15 Modula 2 14 15 15 13 Fortran 9 9 9 8 SML 8 7 6 6 Turing 4 4 3 6 Miranda 4 4 4 3 Smalltalk 4 4 4 1 Eiffel 3 3 3 3 Oberon 3 3 2 2 ISETL 2 2 2 2 ML 2 2 2 1 Modula 3 2 2 2 2 ObjPascal 2 2 2 1 Ada95 2 Haskel 2 1 1 1 Beta 1 1 1 1 Oberon 2 1 1 1 Orwell 1 1 1 1 Prolog 1 1 1 it Ian D Chivers email ian chivers kcl ac uk 25 An Introduction to Programming Languages Chapter 2 and Object Oriented Programming Simula 1 1 1 1 Blue 1 The first edition was May 1990 New editions come out about every six months He doesn t keep past editions I ve put up the complete survey which includes the institutions at http www kcl ac uk kis support cc fortran dickreid20 txt What is interesting is the following http www kcl ac uk kis support cc fortran sdickreid20 txt which is a sorted list by language Where is your institution 2 3 Fortran 77 1978 Modest attempt to update the langu
120. Support VariableInfo We will look at java server pages in more depth in the next chapter In this chapter we will concentrate on some simple examples looking at 23 6 Bibliography Probably the best place to start is http java sun com products servlet index html Follow the links email ian chivers kcl ac uk Ian D Chivers Chapter 23 Servlets 282 The following provides on line documentation http java sun com products servlet 2 2 javadoc index html The following is a white paper on servlets http java sun com products servlet whitepaper html Also try http java sun com docs books tutorial servlets TOC html for an on line tutorial Ian D Chivers email ian chivers kcl ac uk 24 JavaServer Pages Aims The aims of this chapter are to provide a coverage of the package java util Chapter 24 JavaServer Pages 284 24 JavaServer Pages JavaServer pages JSP are Sun s response to Microsoft s Active Server Pages Both are de signed to create dynamic web pages ASP is restricted to the Microsoft platform ASP are found on Microsoft Internet Information Server IIS and work under Windows NT Server The following url http mountain ash cnit kcl ac uk will be the system we will be using for some of the following examples JSP is Sun s platform independent variant of ASP JSP technology uses XML like tags and scriptlets written in the Java programming language to encapsulate the logic that generates the co
121. a is looked at too and obviously companies like Oracle and IBM have of ferings in this area 1 6 Development kits and Standards I ve tried to adhere to the Sun definition Work is underway to get a formal standard Other implementations are available and there are differences The lack of a standard and the differences between the various implementations makes learning Java more difficult than other formally standardised languages e g Fortran Pascal C C has caused problems in this area but things are improving now with the publication of the C standard in November 1997 1 7 Miscellanea We will be using a Sun unix system to learn Java You will have to learn about X Windows access to the system using Vista Exceed the file manager terminal window access and the unix operating system the editor O Ian D Chivers email ian chivers Okcl ac uk 19 Overview Chapter 1 html netscape and other browsers Coverage of these is provided in separate notes and within the body of the notes 1 8 Course Timetable The following is a rough guideline to the ten week course It is flexible Overview of program language development and why Java is the way it is Basic introduction to the Java language and its usage Conventional programming language features arithmetic expressions data types Strings Arrays control structures Additional Java syntax and semantics e g exception handling threads i o and streams graphics inheri
122. ac uk 269 Web Data Access Chapter 22 22 5 1 Interface Summary 22 5 1 1 Array JDBC 2 0 22 5 1 2 Blob JDBC 2 0 22 5 1 3 CallableStatement The interface used to execute SQL stored procedures 22 5 1 4 Clob JDBC 2 0 The mapping in the JavaTM programming language for the SQL CLOB type 22 5 1 5 Connection A connection session with a specific database 22 5 1 6 DatabaseMetaData Comprehensive information about the database as a whole 22 5 1 7 Driver The interface that every driver class must implement 22 5 1 8 PreparedStatement An object that represents a precompiled SQL statement 22 5 1 9 Ref JDBC 2 0 A reference to an SQL structured type value in the database 22 5 1 10 ResultSet A ResultSet provides access to a table of data 22 5 1 11 ResultSetMetaData An object that can be used to find out about the types and properties of the columns in a ResultSet 22 5 1 12 SQLData JDBC 2 0 The interface used for the custom mapping of SQL user defined types 22 5 1 13 SQLInput JDBC 2 0 A input stream that contains a stream of values representing an instance of an SQL struc tured or distinct type 22 5 1 14 SQLOutput JDBC 2 0 The output stream for writing the attributes of a user defined type back to the database 22 5 1 15 Statement The object used for executing a static SQL statement and obtaining the results produced by it 22 5 1 16 Struct JDBC 2 0 22 5 2 Class Summary 22 5 2 1 Date A thin wra
123. age Still largely Fortran 66 Added BLOCK IF better array subscripting and corresponding do looping Given the knowledge of the time a very conservative update to the language 2 4 C K amp R 1978 Standard 1989 C was developed by Kernighan and Ritchie at Bell Labs Bell Labs was the research labora tory of the Bell Telephone company in the US It was originally written for a PDP 11 under UNIX It is based on the cpl bcpl b family of languages and these are typeless languages It was designed as a systems implementation language and was used to rewrite some 9596 of the UNIX operating system Only 596 or so ended up being written in assembler The UNIX tools are written in C and are a very good example of what C is best at the construc tion of sharp small tools There are little or no facilities in the language for the construction of larger code suites Given the date of the publication of K amp R there was the opportunity to have tidied the language up somewhat Look at the features of some of the other languages covered here and the dates to see what is meant by this statement The X library is written in C is over 15 years old and still leaks memory 2 5 Modula 2 1982 Standard 1996 Wirth s next language after Algol W and Pascal Attempt to produce a professional pro grammers Pascal Very many good features Let down by the delay in getting standardised Introduced modules hence the name got rid of some of the idiosyncratic synta
124. al jonas MEER PUR FOR TUM Min ERE Eq VR EUR Ve dR CE 232 A TIO 254 20 1 Plagio A dio C DS id e odo a aa ia 254 2027 Javaapplet sit create at Pet O O 254 20 2 1 Interface AudioClip Since JDK1 0 eese 254 20 2 2 Method Summary cote e Eb eot trio hie ubi ok ER een IEEE 254 20 2 3 Method Detalle nilo pots bici 254 20 3 Examples AUTO A Santee ait eae A AA TAE Et At 255 20 4 Problemas X 257 21 Simple Networking eiie er baee e Yn e ova e Ee Wage YER HAE VR E EFE ERAN V YEPRER SER Ve YET HU Pede 260 21i Paekage javamet Since JOR LO artis ota dosis 260 21 1 1 Interface Summary AA EE 260 21 1 2 Class SUMA EE 260 21 1 3 Exception Summary A dene sche te eee Per Eee pe eB RUP e Pa ESTER EER DET edd 261 2 1 2 NA 261 21 2 1 Manipulating Urls cc ciao 261 21 2 2 Reading a file on a web server ocoooncccnoccnocononococonononnncnononnn cnn no no nono ncn nenne 263 OS 264 22 Web Data Acces iii is io 266 22 A edau quei uR sudo dcos ae hi i ride 266 22 1 1 The Visual Development Environment eese nenne 266 22 1 2 The Wep HMM Mr 266 MENTI M C P NER 266 22 3 e D t SourceS ecu E 266 22 3 1 Oraclen ramita adi s adaptada ada 266 22 3 2 A E 267 22 3 2 Some entries from the FAQ sse nennen ennt enne enne enne 267 22 3 3 IBM noie Det bep ti e eres te be erui te e t reae 267 224 JDBC API uini a a 267 22 3 Package java Sql JD
125. al values are for month 20 month lt rainfall length month rainfall month month 1 System out println rainfall month sum sum rainfall month average sum 12 System out print Average is System out println average The first difference occurs with the array declaration and creation of an array object In the first example we had an implicit new using the assignment operator and to give initial values to the array float rainfall new float 12 has the same declaration syntax but a completely different syntax for the array object cre ation The array is an object so we use new to create it It is of type float and we want it to hold 12 values so we use float 12 In this example we use and to bracket the statement under the control of the for loop This enables us to repeatedly execute more than one statement Now we include the initial email ian chivers kcl ac uk Ian D Chivers Chapter 6 Arrays In Java 94 isation printing out of the values and the actual calculation of the sum Note that the array index goes from 0 through 11 not 1 through 12 We also make use of a new another feature of arrays in Java their length attribute for month 20 month lt rainfall length month So in this case we can terminate the loop when we have reached the length of the array This is a simple example of the treatment of arrays as objects 6 3 Example 3 two dime
126. aling import import java awt Graphics java awt Image public class jane extends java applet Applet email ian chivers kcl ac uk Ian D Chivers Chapter 11 Introduction to Graphics Programming 148 Image janeimg public void init janeimg get Image getCodeBase janet gif public void paint Graphics g iwidth janeimg getWidth this iheight janeimg getHeight this int in int xpos 10 25 g drawImage janeimg xpos 10 iwidth 4 iheight 4 this 30 xpos iwidth 4 10 g drawImage janeimg xpos 10 iwidth 2 iheight 2 this 100 xpos iwidth 2 10 g drawImage janeimg xpos 10 this 11 21 Example 8 Moving image Graphics Image java aw java aw import import Ct et ct ct public class joan02 extends java applet Applet Image img public void init img get Image getCodeBase joan01 gif O lan D Chivers email ian chivers Okcl ac uk 149 Introduction to Graphics Programming Chapter 11 public void paint Graphics g int iwidth img getWidth this int iheight img getHeight this int xpos int ypos 10 for xpos 10 xpos lt 400 xpos 50 g drawImage img xpos ypos this ypos 50 try Thread sleep 100 catch InterruptedException e 11 22Basic Drawing Methods There are a number of basic drawing methods and
127. am to replace the images with your own Look at the images with Netscape and look at the size information that Netscape provides The width and height variables contain details of the expected sizes SW Copyright c 1994 1995 Sun Microsystems Inc All Rights Reserved oo oo E Permission to use copy modify and distribute this software O Ian D Chivers email ian chivers Okcl ac uk 181 Introduction to Graphics Programming Chapter 11 and its documentation for NON COMMERCIAL or COMMERCIAL purposes and without fee is hereby granted Please refer to the file http java sun com copy trade marks html for further important copyright and trademark information and to http java sun com licensing html for further important licensing information for the Java tm Technology SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE EITHER EXPRESS OR IMPLIED NCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE OR NON INFRINGEMENT SUN SHALL NOT BE LIA BLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING MOD IFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON LINE CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL SAFE PERFORMANCE SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES AIRCRAFT
128. and the de stroy method to kill them The implementation of this method provided by the Applet class does nothing 11 30 2 JFrame public class JFrame extends Frame implements WindowConstants Accessible RootPaneContainer An extended version of java awt Frame that adds support for interposing input and painting behavior in front of the frame s children see glassPane support for special children that are managed by a LayeredPane see rootPane and for Swing MenuBars The JFrame class is slightly incompatible with java awt Frame JFrame contains a JRootPane as it s only child The contentPane should be the parent of any children of the JFrame 11 30 3 addWindowListener public void addWindowListener WindowListener 1 Adds the specified window listener to receive window events from this window If is null no exception is thrown and no action is performed 11 30 4 Class WindowAdapter public abstract class WindowAdapter extends Object implements WindowListener An abstract adapter class for receiving window events The methods in this class are empty This class exists as convenience for creating listener objects Extend this class to create a WindowEvent listener and override the methods for the events of interest If you implement the WindowrListener interface you have to define all of the methods in it This abstract class defines null methods for them all so you can only have to define methods for events you care about Create a
129. angle abstract boolean drawImage Image img int x int y int width int height ImageObserver observer Draws as much of the specified image as has already been scaled to fit inside the specified rectangle abstract boolean drawImage Image img int dx1 int dyl int dx2 int dy2 int sx1 int syl int sx2 int sy2 Color bgcolor ImageObserver observer Draws as much of the specified area of the specified image as is currently avail able scaling it on the fly to fit inside the specified area of the destination drawable surface abstract boolean drawImage Image img int dx1 int dyl int dx2 int dy2 int sx1 int syl int sx2 int sy2 ImageObserver observer Draws as much of the specified area of the specified image as is currently avail able scaling it on the fly to fit inside the specified area of the destination drawable surface abstract void drawLine int x1 int yl int x2 int y2 Draws a line using the current color between the points x1 y1 and x2 y2 in this graphics context s coordinate system abstract void drawOval int x int y int width int height Draws the outline of an oval abstract void drawPolygon int xPoints int yPoints int nPoints Draws a closed polygon defined by arrays of x and y coordinates void drawPolygon Polygon p Draws the outline of a polygon defined by the specified Polygon object O Ian D Chivers email ian chivers Okcl ac uk 163 Introduction to Graphics Programming Chapter 1
130. ans beancontext Provides classes and interfaces relating to bean context A bean context is a container for beans and defines the execution environment for the beans it contains There can be several beans in a single bean context and a bean context can be nested within another bean con text This package also contains events and listener interface for beans being added and re moved from a bean context 15 3 Example 1 This example is a complete reworking of the earlier example of a moving graphics image Rather than use AWT I ve moved over to the swing way of doing things I have also used the networking component to use a url to locate the image package jbean01 import java awt import java awt event import java io import java net import javax swing public class bean01 extends JPanel implements ActionListener Serializable protected Imagelcon img public bean01 img new ImageIcon URL url Ian D Chivers email ian chivers kcl ac uk 231 JavaBeans Chapter 15 url getClass getResource joan01 gif img new Imagelcon url public void paintComponent Graphics g super paintComponent 9g int xpos int ypos 10 if img getImageLoadStatus MediaTracker COMPLETE for xpos 10 xpos lt 400 xpos 50 img paintIcon this g xpos ypos ypos 50 try Thread sleep 50 catch In
131. aphics object based on this Graphics object but with a new translation and clip area abstract void dispose Disposes of this graphics context and releases any system resources that it is us ing email ian chivers kcl ac uk Ian D Chivers Chapter 11 Introduction to Graphics Programming 162 void draw3DRect int x int y int width int height boolean raised Draws a 3 D highlighted outline of the specified rectangle abstract void drawArc int x int y int width int height int startAngle int arcAngle Draws the outline of a circular or elliptical arc covering the specified rectangle void drawBytes byte data int offset int length int x int y Draws the text given by the specified byte array using this graphics context s current font and color void drawChars char data int offset int length int x int y Draws the text given by the specified character array using this graphics con text s current font and color abstract boolean drawImage Image img int x int y Color bgcolor ImageObserver ob server Draws as much of the specified image as is currently available abstract boolean drawImage Image img int x int y ImageObserver observer Draws as much of the specified image as is currently available abstract boolean drawImage Image img int x int y int width int height Color bgcolor ImageObserver observer Draws as much of the specified image as has already been scaled to fit inside the specified rect
132. aphics object is displayed on the current area Some of the object will be outside the clip region and will not be displayed See Foley et al for a coverage of this subject 11 12Rendering Rendering is the production of the actual output on a graphics device 11 13Putting it all togethor A Java graphics context enables drawing on the screen A Graphics object manages a graphics context by controlling how things are drawn The applets so far have have used generally used the Graphics object g which is the argument to paint Things have changed in this area What follows is based on the early 1 0 x jdk We will come back to this whole area in later chapters email ian chivers Q kcl ac uk O Ian D Chivers Chapter 11 Introduction to Graphics Programming 140 11 14History Things are more complicated than they need be in this area due to the way that Java has evolved As you know we have had three major release of the Java jdk jdk 1 0 x jdk 1 1 x jdk 1 2 x and Sun have announced jdk 1 3 on February 15th There have also been several release of Swing As problems are discovered with the current versions Sun try and fix the problems This makes working out the best way of doing some thing quite difficult in the graphics and windows programming area If you look at the books and examples that exist you will see several ways of achieving what appears to be the same end result This chapter starts by looking at ways of doing things u
133. aphics2D g2d Graphics2D g g2d setColor Color blue g2d filloOval int x int y 20 20 public static void main String argv final graphicll gll new graphicll gll xncc C JFrame jf new JFrame Using Graphics2D jf addWindowListener new WindowAdapter public void windowClosing WindowEvent e System exit 0 In this example we add imports for the new event handling and we are also using compo nents from Swing The first difference is that we use objects of ype Graphics2D now rather than the original Graphics The examples Sun make available still callpaint with an object of type Graphics and then explicitly cast within paint to Graphics2D The second difference is the addition of the main routine at the end Within this routine we create a variable of type graphic11 initialise the variable create a JFrame variable register the JFrame as a window listener override windowClosing Ian D Chivers email ian chivers kcl ac uk 175 Introduction to Graphics Programming Chapter 11 11 30 1 Initialisation public void init Called by the browser or applet viewer to inform this applet that it has been loaded into the system It is always called before the first time that the start method is called A subclass of Applet should override this method if it has initialization to perform For ex ample an applet with threads would use the init method to create the threads
134. ariable in a Java program you actually see a reference to an object We will look into the concept of references in much greater detail throughout the course 2 15 9 Procedure Variables An elegant way of extending the expressive power of a language Quite old 2 15 10 Inheritance The first of the two major step towards OO programming Allows the user to extend an ex isting type without having to know what is going on 2 15 11 Dynamic Binding The second of the two major features of OO programming Provided in a limited sense via procedure variables in older languages 2 15 12 Operator Overloading Syntactic sugar in many ways and over valued Very useful to people with numeric prob lems Given that C has 47 operators it poses problems of readability and comprehensibil ity with most other areas The restrictions that C has in this area will be looked at later 2 15 43 Threads Multitasking Multitasking and or threads are needed in a programming language when solving problems in the areas of real time systems equipment interfacing embedded systems and parallel programming Ian D Chivers email ian chivers kcl ac uk 31 An Introduction to Programming Languages Chapter 2 and Object Oriented Programming 2 15 14 Exception Handling Exception handling is needed in a programming language when solving problems in the ar eas of real time systems equipment interfacing embedded systems parallel programming and robust systems 2
135. aring programming languages and looking at the development of programming languages hes Against the spirit of object oriented programming des Replaced by references O Ian D Chivers email ian chivers Okcl ac uk 29 An Introduction to Programming Languages Chapter 2 and Object Oriented Programming Dates Fortran The dates are the dates of the standards Pascal Preliminary version 1968 Major development and first operational compiler 1970 1973 publication of first revised report User Manual and Report 1975 Modula Defined experimentally 1975 Lilith research project 1977 First implementation of Modula 2 1979 Technical report March 1980 First distributed compiler March 1981 Pro gramming in Modula 2 1982 Oberon 2 1988 N Wirth The Programming Language Oberon Software Practice and Ex perience 1991 Mossenbeck and Wirth The Programming Language Oberon 2 1991 Reisser The Oberon System User Guide and Programmer s Manual 1993 Mossenbeck Object Oriented Programming in Oberon 2 C 1969 M Richards BCPL A Tool for Compiler Writing and Systems Programming 1970 Ken Thompson B 1978 K and R The C Programming Language 1989 ANSI C Stan dard C C with classes 1979 1983 From C with Classes to C 1982 1985 Release 2 0 1985 1988 Stroustrup The C Programming Language p edition 1986 Stroustrup The C Programming Language 2nd edition 1991 Standard 1997 Ada 1980 original definition Standard 1987 La
136. as heir to more than one class and more than once to the same class The second edition dated 1997 is a new book rather than an update of the first edition Chapters 1 and 2 are an introduction and overview Chapters 3 through 6 provide coverage of the road to object orientation Chapters 7 through 18 are the technical core of the book looking at object oriented techniques There is a coverage of classes objects memory management email ian chivers kcl ac uk Ian D Chivers Chapter 2 An Introduction to Programming Languages 36 and Object Oriented Programming genericity design by contract exception handling supporting mechanisms inheritance multiple inheritance inheritance techniques typing global obects and constants Programming is an engineering activity and has evolved considerably since the first pro gramming languages of the 1950 s The changes between the first and second editions re flect the developments that have taken place over nearly 10 years This book is essential reading if you are seriously interested in objected oriented programming 2 22 2 Rumbaugh et al This book concentrates on OO modelling rather than using a particular programming lan guage for OO programming If you have a background in the relational database area then much of the coverage should be quite familiar They present a methodology for object ori ented development the Object Modelling Technique or OMT They identify four stages
137. ass c0406 public static void main String args H 5 ll H H H 353535 peeoctoct ct cf ll Se OO ooo e Ru H ll Se H L T I e n O lan D Chivers email ian chivers Okcl ac uk 69 Arithmetic and Expressions in Java Chapter 4 System out printin i System out printlin j System out println k System out printlin 1 What do you think will be the output of this program Do we need four ways of achieving the same thing in a programming language This example is taken from the Fortran 90 text It is a direct translation class c0407 static final float light year float 9 46 10E12 public static void main String args float light_minute float distance float elapse int minute int second light_minute light_year float 365 25 24 0 60 0 distance float 150 0 10E6 elapse distance light_minute minute int elapse second int elapse minute float 60 System out print Light takes System out print minute System out print minutes System out print System out print second System out println seconds Let us look at each line in turn class c0407 Standard class definiton static final float light year float 9 46 10E12 This is the way that you define light year to be a constant or parameter T
138. at presented time based media The JMF 2 0 API extends the framework to provide support for captur ing storing and broadcasting media data using custom codecs and manipulating media data before it is rendered The JMF 2 0 API was developed by Sun Microsystems Inc and IBM The JMF 1 0 API was developed by Sun Microsystems Inc Silicon Graphics Inc and Intel Corporation JMF 2 0 supports a wide array of media types including protocols FILE HTTP FTP RTP audio AIFF AU AVL GSM MIDI MP2 MP3 QT RMF WAV video AVI MPEG 1 QT other Flash 2 HotMedia 20 1 Playing Audio Clips This chapter only looks at audio clips at the moment 20 2 java applet 20 2 1 Interface AudioClip Since JDK1 0 public interface AudioClip The AudioClip interface is a simple abstraction for playing a sound clip Multiple AudioClip items can be playing at the same time and the resulting sound is mixed together to produce a composite 20 2 2 Method Summary void loop Starts playing this audio clip in a loop void play Starts playing this audio clip void stop Stops playing this audio clip 20 2 3 Method Detail play public void play Starts playing this audio clip Each time this method is called the clip is re started from the beginning loop public void loop Ian D Chivers email ian chivers kcl ac uk 255 Multimedia Chapter 20 Starts playing this audio clip in a loop stop public void stop Stops playing this au
139. ata type supported in Java Values are eithor true or false 4 12 Example Programs Here are a small number of complete Java programs illustrating some of the material in this chapter 4 12 4 Example Program Simple character and boolean output class c0410 public static void main String args boolean ok true char c a System out System out ct ct 4 12 2 Example Program Unicode character output class c0411 public static void main String args char c u0b87 System out printin c 4 12 3 Example Program Bitwise operators amp and class c0412 public static void main String args H Hi ct ct ct System out println k System out printlin 1 System out println m O Ian D Chivers email ian chivers Okcl ac uk 73 Arithmetic and Expressions in Java Chapter 4 4 13 Summary There are the following primitive data types in Java boolean true or false char 16 bit Unicode character byte 8 bit signed integer short 16 bit signed integer int 32 bit signed integer long 64 bit signed integer float 32 bit real IEEE 754 1985 double 64 bit real IEEE 754 1985 Integer constants in expressions are of type int Casting is required when doing integer arithmetic using the other integer types Real constants are of type double Casting is required when doing real arithmetic using float
140. atalInputStream input contents setText Replace with your ego trip n while text dataInput readLine null contents appendText text An dataInput close catch IOException e showStatus Exception e toString What do you notice about the output The original source file is on the college web server Save the file and have a look at it in an editor 21 3 Problems Try out the examples in this chapter Try them out on Gum and your own pc They are also on the College web server Run them from there using Netscape Ian D Chivers email ian chivers kcl ac uk 22 Web Data Access Aims The aims of this chapter are to provide a brief coverage of web data access Chapter 22 Web Data Access 266 22 Web Data Access 22 1 Background I ve done this in the past using a product called Tango This is freely available on the Internet and can be installed on your own machine I recommend an NT server The company that sells Tango can be found at http www pervasive com and their download offerings are to be found at http www pervasive com products download The product is made up of a number of components 22 1 1 The Visual Development Environment If you are familiar with Visual Basic then you will appreciate the ease of use that Tango of fers You drag the items you want from a toolbox on the left and drop them onto a form in the middle You then have the database c
141. ate static File parent File f String dirname f getParent if dirname null f if f isAbsolute return new File File separator else return new File System getProperty user dir return new File dirname public static void main String args if args length 2 System err println Usage java convert lt source file gt lt destination file gt else try eopylargs 0 args 1 catch IOException e Sys tem err println e getMessage class convertException extends IOException public convertException String msg super msg The key code is int i 0 Variable to count how many characters we have on a line We have to break the lines somewhere byte carriage_return 13 byte line_feed 10 Variables for carriage return and line feed email ian chivers kcl ac uk Ian D Chivers Chapter 9 i o 128 char c Variable to hold the character to be written int byte_read Read returns integers while true byte_read source read if byte_read 1 break Read returns 1 at end of file itt Increment the character count if byte read 32 byte read 127 byte read 232 Convert non printing characters to blank if i gt 60 amp amp byte read 232 c char carriage return destination write c Q 0 tination write c S c char line_feed i 0 Spli
142. atement Conventional while statement i e statement may never be executed This example high lights both the if else statement and the while statement It is a direct translation of the For tran 90 example 7 7 1 import import Example 1 java io java lang Integer class c0705 public static void main String args i i i n n In n t counter 0 t mark 99 teger t a 1 2 3 4 5 6 7 8 9 10 0 Mark new Integer mark String Line try InputStream i System in DatalnputStream I new DatalnputStream i System out println Type in value to look for Line I readLine Mark Integer valueOf Line mark Mark intValue ala length 1 mark while mark a counter counter if counter a length 1 System out printin Number not found else System out printin Number found at position System out println counter catch IOException e O lan D Chivers email ian chivers Okcl ac uk 101 Control Structures Chapter 7 System out printin Exceptions raised e We will look at the use of a sentinel in a later example 7 8 do statement while expression Equivalent to repeat until statement i e the loop is always executed at least once as the test is at the end of the loop This example is the e function taken from the Fortran 90 course 7 8 1 Example 1 import import
143. ating using another approach For more information see the references in the bibliography 27 2 2 Double precision floating point format This is a 64 bit quantity made up of a sign bit 11 bit biased exponent and 52 bit mantissa As with single precision the standard specifies that certain of the bit patterns are set aside and do not represent normal numbers This means we have valid numbers in the range 1 7976931348623157E308 to 2 2250738585072014E 308 and precsion between 15 and 17 digits depending on the numbers As with single precision there are bit patterns set aside for the same special conditions Note that his does not mean that the hardware has to handle the manipulation of this 64 bit quantity in an identical fashion The Sparc and Intel family handle the above as two 32 bit quantities but the order of the 2 component parts is reversed so called big endian and little endian email ian chivers Q kcl ac uk O Ian D Chivers Chapter 27 IEEE Arithmetic 300 27 2 3 Two classes of extended floating point formats These formats are not mandatory A number of variants of double extended exist including Sun 4 32 bit words one sign bit 15 bit biased exponent and 112 bit mantissa numbers in the range 3 362E 4932 to 1 189E4932 33 to 36 digits of significance Intel 10 bytes one sign bit 15 bit biased exponent 63 bit mantissa numbers in the range 3 362E 4932 to 1 189E4932 18 21 digits of significance PowerPC
144. ator and a bit array 25 1 1 Interface Summary 25 1 1 1 Collection The root interface in the collection hierarchy 25 1 1 2 Comparator A comparison function which imposes a total ordering on some collection of objects 25 1 1 3 Enumeration An object that implements the Enumeration interface generates a series of elements one at a time 25 1 1 4 EventListener A tagging interface that all event listener interfaces must extend 25 1 1 5 Iterator An iterator over a collection 25 1 1 6 List An ordered collection also known as a sequence 25 1 1 7 Listlterator An iterator for lists that allows the programmer to traverse the list in either direction and modify the list during iteration 25 1 1 8 Map An object that maps keys to values 25 1 1 9 Map Entry A map entry key value pair 25 1 1 10 Observer A class can implement the Observer interface when it wants to be informed of changes in observable objects 25 1 1 11 Set A collection that contains no duplicate elements 25 1 1 12 SortedMap A map that further guarantees that it will be in ascending key order sorted according to the natural ordering of its keys see the Comparable interface or by a comparator provided at sorted map creation time 25 1 1 13 SortedSet A set that further guarantees that its iterator will traverse the set in ascending element order sorted according to the natural ordering of its elements see Comparable or by a Compara tor pro
145. ave to offer 14 5 Pluggable Look and Feel There are a number of gui interfaces around and they include Apple Mac PC and Windows Unix and Motif The aim of Plaf is to provide the user with the choice of which look and feel they want The default look and feel is called metal 14 6 Lightweight Components One meaning of the term lightweight component is that the component has the ability to render itself onto the screen This allows developers to draw the look and feel of the appli cation at run time instead of the host operating system 14 7 Model View Controller MVC Architecture Swing uses the MVC architecture as the basis of the design of the components 14 71 Model The state data for the component There are several models here depending on the compo nent A menu is different to a scrollbar 14 7 3 View The way it looks on the screen 14 7 3 Controller How the components interact via events mouse clicks gaining or losing focus keyboard etc 14 8 Multithreading You have already seen some of the problems that can occur with threads in an earlier chap ter A swing component paints itself based on the state of the component If the state changes during the paint process what should happen Incorrectly painting itself is obvi ously not acceptable To handle this there is an event dispatch queue This is a system thread that handles the communication of evenets to other components 14 9 Components There a number of Swing com
146. ay of doing things import java awt import javax swing JApplet import java lang Math public class c1184 extends javax swing JApplet public void init setBackground Color white public void paint Graphics g O lan D Chivers email ian chivers kcl ac uk 223 Swing Chapter 14 int x 0 y 180 ct ct int int angled double angler g setColor Color blue for angled 0 angled lt 361 angled x angled g drawLine x y X y angler angled 2 Math P1 360 Y 180 int 180 Math sin angler Things to note include This example will not run under Netscape 4 5 It generates a class not found error for Javax Swing JApplet It will run under the Appletviewer that comes with the 1 2 2 JDK We are now using the enhanaced functionality provided by JApplet over the original Applet This is done using import javax swing JApplet We extend JApplet using public class c1184 extends javax swing JApplet The rest of the code is identical 14 12Inheritence Revisited You have now seen the power of OO programming and the benefits it has to offer We have been able to accept the default behaviour of most of the classes we have used and rely on the fact that a lot of complexity is hidden from us You have also seen that there is more than one way to acheive something within Java in a lot of cases Part of this is due to the fact that Sun released Java as an incomplete languag
147. ber of techniques for handling floating point exceptions in nu meric code One of the conclusions is for better structured support for floating point excep tion handling in new programming languages or of course later standards of existing lan guages IEEE IEEE Standard for Binary Floating Point Arithmetic ANSI IEEE Std 754 1985 Insti tute of Electrical and Electronic Engineers Inc The formal definition of IEEE 754 email ian chivers kcl ac uk Ian D Chivers Chapter 27 IEEE Arithmetic 302 Knuth D Seminumerical Algorithms Addison Wesley There is a coverage of floating point arithmetic multiple precision arithmetic radix conver sion and rational arithmetic Sun Numerical Computation Guide SunPro Very good coverage of the numeric formats for IEEE Standard 754 for Binary Floating Point Arithmetic All SunPro compiler products support the features of the IEEE 754 standard 27 5 1 Web based sources http validgh com goldberg addendum html Differences Among IEEE 754 Implementations The material in this paper will eventually be included in the Sun Numerical Computation Guide as an addendum to Appendix D David Goldberg s What Every Computer Scientist Should Know about Floating Point Arithmetic http docs sun com Follow the links to the Floating Point and Common Tools AnswerBook The Numerical Computation Guide can be browsed on line or downloaded as a pdf file The last time we checked it was about 260 pages Good s
148. ble to achieve when one considers floating point arithmetic Reasons for this include The conversions of numbers between decimal and binary formats The use of elementary library functions Results of calculations may be in hardware inaccessible to the programmer Intermediate results in subexpressions or arguments to procedures The bibliography contains details of a paper that addresses this issue in much greater depth Differences Among IEEE 754 Implementions Fortran is one of a small number of languages to provide access to IEEE arithmetic and it achives this via TR1880 which will become an integral part of Fortran 2000 The C stan dard C9X addresses this issue and Java offers limited IEEE arithmetic support More in formation can be found in the references at the end of the chapter 27 2 IEEE 754 Specifications The standard specifies a number of things including Single precision floating point format Double precision floating point format Two classes of extended floating point formats Accuracy requirements on the following floating point operations Add email ian chivers Q kcl ac uk O Ian D Chivers Chapter 27 IEEE Arithmetic 298 Subtract Multiply Divide Square root Remainder Round numbers in floating point format to integer values Convert between different floating point formats Convert between floating point and integer format Compare Base conversion i e when converting between decimal an
149. book have used their A best efforts in preparing the book These efforts include the development research and testing of the theories and programs iS to determine their effectiveness The authors and pub lisher make no warranty of any kind expressed or implied with re gard to these programs or to the documentation contained in these books The authors and publisher shall not be liable in any event for inci dental or i email ian chivers kcl ac uk Ian D Chivers Chapter 13 Events 212 consequential damages in connection with or arising out of the furnishing performance or use of these programs KKKKKKKKKKKK CC CC CC CC CC CK C CK CC CC CK CC KC CK Sk C S S S KU KG KK AG k KR A ko X ko o HK KK ck k x x x x x Things to note we now extend JApplet we in turn implement ActionListener compare this with the previous example set up some variables set up the graphical components within init over ride actionPerformed this calls play play actually plays the game roll the dice this updates the text atrea These examples show two of the different ways that we can program event handling using actionListener We will come back to this area in more depth in later chapters 13 7 Summary Event driven programming takes a while to get used to We will look at how this all works in later chapters 13 8 Problems Try the examples out to see what happens O Ian D
150. bpages WEB INF 235 Apr 27 2138 Apr 27 300 Apr 27 324 Apr 27 Servlets Chapter 23 1999 mappings properties 1999 mime properties 1999 servlets properties 1999 webapp properties webpages WEB INF servlets 1047 Jul 11 5293 Apr 21 13 16 HTTPGetServlet class 1999 SnoopServlet class 4898 Apr 27 webpages docs webpages docs api 2506 Apr 2 1999 SnoopServlet java 1999 allclasses frame html 10258 Apr 7789 Apr 1999 deprecated list html 1999 help doc html 1999 index all html 83183 Apr 756 Apr 1999 index html 1999 overview frame html 942 Apr 4289 Apr 1999 overview summary html 7247 Apr 1999 overview tree html 33 Apr 618 Apr 7183 Apr Eq 1999 package list 1999 packages html 1999 serialized form html S oM ga gg r 1240 Apr 1999 stylesheet css webpages docs api javax webpages docs api javax servlet 27030 Apr 2 1999 GenericServlet html 12099 Apr 21 1999 RequestDispatcher html 15433 Apr 2 1999 Servlet html 10447 Apr 2 1999 ServletConfig html 33416 Apr 2 1999 ServletContext html 12917 Apr 2 1999 ServletException html 10649 Apr 2 1999 ServletInputStream html 22170 Apr 2 1999 ServletOutputStream html 27468 Apr 21 1999 ServletRequest html 15027 Apr 21 1999 Servle
151. byte i_b 2 i s short i_s 2 i i 2 i_l i_l 2 System out print i_b System out print System out print i s System out print System out print i System out print System out print i 1 System out printin O Ian D Chivers email ian chivers Okcl ac uk 61 Arithmetic and Expressions in Java Chapter 4 Let us look at this program in some detail class c0401 Class name public static void main String args Standard program header byte ib 1 Variable declaration and initialisation short i s 1 Variable declaration and initialisation int i 1 Variable declaration and initialisation long c Sd Variable declaration and initialisation System out print i b System out print Standard mechanism to print to the screen The print method can only take one argument There are several print methods one for each built in type This makes i o seem a little verbose compared to more conventional programming languages System out print i s System out print nes Print short System out print i System out print ms Print int System out print i 1 System out println Print long for int count 1 count lt 33 count Java and C syntax of a for loop We are allowed to declare and initialise variables with a for statement In this case we introduce a new variable count and initialise to 1 The is a statment terminator count lt
152. c uk Ian D Chivers Chapter 2 An Introduction to Programming Languages 40 and Object Oriented Programming lems with pointer aliasing and array handling For many applications they offer quite signif icant advantages over other languages Graphical based systems are invariably written in C Object oriented programming is often done in C The maintenance problems C poses are considerable The steep learning curve that C has poses problems for succes sive generations of would be C programmers Look at the Computational Science Education paper for an comparison of C Fortran 77 Fortran 90 and C This is on the college web server Whither Java Java seems to be a language that will survive How widely used it will be come depends obviously on the success of the internet and local intranets Whither Visual Basic VB will survive Many people need to be able to develop easy to use programs and systems Windows programs offer the possibility of solving this problem No one language is appropriate for solving every problem Many factors come into play in real life Learning a variety of languages is a good idea Learning Fortran 90 C Java and Visual Basic provides you with a range of very useful skills for work in the academic scientific engineering and commercial worlds I ve included references to a couple of other languages that you might like to look at and these are Icon Snobol Prolog and SQL Icon and Snobol are very good stri
153. casting required in some languages means that they are not widely used for numeric programming At the next level the ability to call in built functions with numeric data of one or more types This has been in Fortran from a very early stage Finally the ability to create one s own functions that accept numeric data of a variety of nu meric types Languages that support OOP have to offer the last kind of polymorphism General Polymorphism OO programming languages have to offer this functionality 2 15 7 Modules The primary purpose of modules is to provide the ability to group related functions and pro cedures This is a powerful program decomposition tool They normally have a well con trolled mechanism for making visible what the external calling routine needs to have access to Terminology varies with programming languages and so does the exact functionality that these different languages support Classes and packages are two terms also used 2 15 8 Pointers and References Pointers in a programming language extend the range of problems that can be solved con siderably Multi dimensional structures are easily programmed using pointers e g linked lists queues trees quad trees oct trees etc The major problem is that the user is provided with very little help if they are programmed incorrectly It is assumed that you know what you are doing In Java all objects are accessed via an object reference When you see an object v
154. cation in x y coordinate space specified in integer precision Polygon The Polygon class encapsulates a description of a closed two dimensional re gion within a coordinate space PopupMenu A class that implements a menu which can be dynamically popped up at a speci fied position within a component PrintJob An abstract class which initiates and executes a print job Rectangle A Rectangle specifies an area in a coordinate space that is enclosed by the Rect angle object s top left point x y in the coordinate space its width and its height RenderingHints The RenderingHints class contains rendering hints that can be used by the Graphics2D class and classes that implement BufferedImageOp and Raster RenderingHints Key Defines the base type of all keys used to control various aspects of the rendering and imaging pipelines Scrollbar The Scrollbar class embodies a scroll bar a familiar user interface object ScrollPane A container class which implements automatic horizontal and or vertical scroll ing for a single child component SystemColor A class to encapsulate symbolic colors representing the color of GUI objects on a system email ian chivers kcl ac uk Ian D Chivers Chapter 11 Introduction to Graphics Programming 160 TextArea A TextArea object is a multi line region that displays text TextComponent The TextComponent class is the superclass of any component that allows the ed iting of some text
155. ce for an object that listens to changes in a TreeModel TreeSelectionListener The listener that s notified when the selection in a TreeSelectionModel changes Tree WillExpandListener The listener that s notified when a tree expands or collapses a node UndoableEditListener Interface implemented by a class interested in hearing about undoable opera tions 13 2 2 Class Summary AncestorEvent An event reported to a child component that originated from an ancestor in the component hierarchy CaretEvent CaretEvent is used to notify interested parties that the text caret has changed in the event source ChangeEvent ChangeEvent is used to notify interested parties that state has changed in the event source DocumentEvent EventType Enumeration for document event types EventListenerList A class which holds a list of EventListeners HyperlinkEvent HyperlinkEvent is used to notify interested parties that something has happened with respect to a hypertext link HyperlinkEvent EventType Defines the ENTERED EXITED and ACTIVATED event types along with their string representations returned by toString InternalFrameAdapter An abstract adapter class for receiving internal frame events InternalFrameEvent InternalFrameEvent an AWTEvent which adds support for JInternalFrame ob jects as the event source ListDataEvent Defines an event that encapsulates changes to a list ListSelectionEvent An event that characterizes a c
156. ception that has no catch clause after a break continue or return statement We will look into this in more depth in the complete file copy program in this chapter 8 5 Array Subscript Errors Array subscript checking is always on in Java and any attempt to go out of the bounds of an array will raise an exception 8 6 Anticipated Errors vs Unanticipated Errors These are errors that one might reasonably expect to happen End of file and an incorrectly typed file name are two obvious ones that spring to mind Unanticipated errors are ones that you don t think of You can trap both kinds of errors with exception handling 8 7 Complete Example File copy program The following program illustrates the power of exception handling It also illustrates most of the syntax of how to use exception handling It is taken directly from the Nutshell book by David Flanagan This example is from the book O Ian D Chivers email ian chivers Okcl ac uk 113 Exceptions Chapter 8 _Java in a Nutshell_ by David Flanagan Written by David Flanagan Copyright c 1996 O Reilly amp Associates You may study use modify and distribute this example for any purpose This example is provided WITHOUT WARRANTY either expressed or implied import java io public class FileCopy public static void copy String source_name String dest_name throws IOException File source file new File source
157. chivers kcl ac uk Ian D Chivers Chapter 22 Web Data Access 272 This is the relational database management system I recommend on the pc It is SQL level 2 conformant and when used in conjunction with Tango provides a very good web database development solution Sales in the UK handled by As pen Software Requires an NT server O lan D Chivers email ian chivers Okcl ac uk 23 Servlets Aims The aims of this chapter are to provide a coverage of servlets Chapter 23 Servlets 274 23 Servlets The basic idea of a servlet is that of a program that runs on a web server and provides a service to other programs that make requests to it They are written in Java and have access to the Java API This obviously includes the JDBC API to access databases and Sun saw their initial use to provide secure web based access to data which is presented using HTML web pages interactively viewing or modify ing that data using dynamic web page generation techniques Sun also see servlets as a popular choice for building interactive web applications Third party Servlet containers are available for Apache Web Server Planet Web Server formerly Netscape Enterprise Server Microsoft IIS and others Servlet containers can also be integrated with web enabled application servers such as BEA WebLogic Application Server IBM WebSphere Netscape Application Server and others 23 1 Getting started You will need to download and install a number of thing
158. clude The on line jdk documentation This is essential The information you need will be there but digging it out may take a long time Deitel and Deitel Java How to Program Prentice Hall various versions Very good general coverage of the whole of the Java lan guage The two chapters on graphical user interface pro gramming are enough to get you started Eckstein Loy Wood Java Swing O Reilly Really good coverage of Swing Much deeper coverage than the first Foley van Dam Feiner Hughes Computer Graphics Addison Wesley Java now offers very good functionality in the graphics area I d get hold of a copy to fill in the missing gaps email ian chivers kcl ac uk Ian D Chivers 15 JavaBeans Common sense is the best distributed commodity in the world for every man is con vinced that he is well supplied with it Descartes Aims The aims of this chapter are look at JavaBeans Chapter 15 JavaBeans 228 15 JavaBeans When we look at programming with older langauges Fortran 66 and Fortran 77 C the original Pascal they support so called procedural programming Fortran 90 adds object based programming and C adds object oriented programming Java is completely object based With the addition of Java Beans we have added one more programming paradigm reusabe software components They enable us to construct solutions based on using building blocks JavaBeans can be used to create applications or appl
159. ctic sugar of Pascal had the idea of separate definition and implementation Rivals Ada without much of the complexity of Ada for real time applications Numeric work in Modula 2 isn t very attractive Explicit type casts are required in mathe matical expressions The proposed standard alleviates some of the problems in this area 2 6 Ada ISO 8652 1987 Attempt to produce a powerful and expressive language by the American Department of Defence Given the very large defence spending budget even a 1 gain from the adoption of a better programming language will be repaid Gaining ground from a slow start See also Ada 95 later First draft report was 1980 2 7 C 1986 Standard November 1997 Attempt by Stroustrup to produce an object oriented version of C He had been exposed to Simula early on and realised the benefits of a language like that Simula is a product of the 1960 s The first version of Simula was available in 1967 Object oriented programming is not new Simula was widely used for discrete event simulation email ian chivers kcl ac uk O Ian D Chivers Chapter 2 An Introduction to Programming Languages 26 and Object Oriented Programming 2 8 Oberon 2 Late 1980 s early 1990 s Very clean and simple OOP language Partly driven by the visit of Wirth and Gutnecht to Xerox PARC and Wirth having to take over the operating system course at ETH Name arises from the Voyager probe taking pictures of Uranus Oberon is the larg
160. d Jaya PEOR ii iia 48 3 5 Hello World Java Applets daba 49 3 6 Hello World JApplet irice i r Shes a O ida 52 3 7 Hello World JApplet alternate syntax nennen 52 3 8 Hello World COMPONEN Ei AA THE SR a OUS Dra SOR a ES Ge 53 3 9 Program for Ine VO t 53 3 10 Program for Umere MO 54 3 11 Some Java Rules and Termos is 56 3 12 Good Programming Cuide Mes id ie 56 3415 Jaya Character Setoa ood ertet e a cme ced ede A ade ped needs 57 SPARS ASIA a CET 57 E 57 3 15 1 A E NN 57 3 15 2 TAT T EEA E E S E E A TE ETE TE E 57 3 15 3 Character soda 58 3 16 PROBLEMS ae een oa i settee ues aes Ces deed 58 4 Arithmetic and Expressions in Java eee e e eee e eere ee eee eee rene eee ee tnaue 60 4 1 Basic TUTHOHIC LY PES uti ia 60 AD Integer Numeric Py pe ioaesete rise TN 60 4 3 Real Numeric T Ves oodd oci diat lion ePi Daci ed ues uitae ati 62 AA IEEE 754 1985 decere eid Doe net ede E tesi eres is se EO t edt EU ce s edel Re 63 4 5 Numero Type Conviasa 63 40 Whither complex miii nr liinda EN 63 4 7 Constants r Parameter Siseseinte a et ie cutee suut 63 4 8 Operators and Expression Evaluation essen nennen 63 4 8 1 Expression Evaluation 2 IRURE de pete etre e o erede 63 4 8 2 Operators Precedence and Associativity eese 64 4 8 2 1 member selection object member sess 65 4 8 2 2 subscripting pointer expr esee 65 4 8 2 3 Q funct
161. d binary floating point formats and vice versa Exception handling for Divide by zero Overflow Underflow Invalid operation Inexact Rounding directions Rounding precisions and we will look briefly at each of these requirements 27 2 1 Single precision floating point format This is a 32 bit quantity made up of a sign bit 8 bit baised exponent and 23 bit mantissa The standard also specifies that certain of the bit patterns are set aside and do not represent normal numbers This means that valid numbers are in the range 3 40282347E 38 to 1 17549435E 38 and the precision is between 6 and 9 digits depending on the numbers The special bit patterns provide the following 0 0 subnormal numbers in the range 1 17549421E 38 to 1 40129846 45 infinity infinity quiet NaN Not a Number signalling NaN One of the first systems that the authors worked with that had special bits patterns set aside were the CDC 6000 range of computers that had negative indefinite and infinity The ideas are not new therefore as this was in the late 1970s The support of positive and negative zero means that certain problems can be handled cor rectly including The evaluation of the log function which has a discontinuity at zero O lan D Chivers email ian chivers Okcl ac uk 299 IEEE Arithmetic Chapter 27 The equation VY y can be solved when z 1 See also the Kahan paper Branch Cuts for Complex Elementary Functions or Much Ado Abo
162. d car In this case a car has a engine define the interfaces to the classes Inheritance commits you to much more than becoming a client As a client you are pro tected against future changes in the implementation of a class When you inherit you gain access to the implementation and all that goes with it The above have to be done before any code is written Programming is an iterative process and it is inevitable that you will need to cycle through the design and implementation stages as you write code i e it will be obvious that you will need to go back and redesign and reimplement base classes in the light of experience 2 23 Simple Example Consider putting together a graphical drawing system We are interested in shapes and the concepts of moving and drawing We can do this in a very straightforward way using an OO approach Firstly we have a base abstract class shape with two associated procedures one to move and one to draw shape x y move shape s draw shape s Secondly we then derive other shapes from them We provide two derived classes with two associated procedures square shape side move shape s draw shape s rectangle shape length breadth move shape s draw shape s Consider the following pseudo code segment square s 50 50 10 rectangle r 100 100 10 20 move s draw s move r draw r return 0 email ian chivers kcl ac uk O Ian D Chivers Chapter 2 An Introduction to Program
163. d documentation provided by IBM s Object Connection program members It is provided solely for evaluation purposes much of it is in trial version form 19 2 2 MindQ Introduction to VisualAge for Java This is produced by MindQ Publishing It is a multimedia CD A little confusing at first 19 2 3 AlphaWorks Home url is http www alphaworks ibm com 19 2 3 1 alphaWorks History The Launch I quote IBM alphaWorks began its life in 1996 in Armonk NY spear headed by John Pat rick IBM Vice President Internet Division Patrick s vision was to create a Web site that surfaced IBM s hottest Internet technologies from research and established a cutting edge Web presence for IBM Three college supplementals and five IBM ers built the alphaWorks Web site in 30 days The alphaWorks Web site launched on August 26 1996 with press coverage and attention attracting curious developers to download alpha code technolo gies from IBM alphaWorks was even featured in IBM Chairman Louis V Gerstner s key note address at Fall Internet World in October 1996 John Patrick then decided to move the team closer to the epicenter of technology and Internet innovation Silicon Valley Ian D Chivers email ian chivers kcl ac uk 249 IBM VisualA ge for Java Chapter 19 alphaWorks moved into the IBM Almaden Research Center in January 1997 and relocated once more to the IBM Center for Java Technology in Cupertino CA 19 2 4 Other Offerings A beta vers
164. d drawImage The main method is identical to the last two examples in this section 11 33Simple line drawing import java awt public class c11401 extends java applet Applet public void init setBackground Color white public void paint Graphics g Graphics2D g2d Graphics2D g int x1 0 int yl 0 int x2 100 int y2 200 g2d setColor Color blue g2d drawLine x1 y1 x2 y2 Very simple example Minimal changes have been made in this case 11 34Summary There is a lot to this subject I have only provided a very brief coverage It is essential to get a background to the field of computer graphics if you are going to use Java for graphi cal output email ian chivers kcl ac uk Ian D Chivers Chapter 11 Introduction to Graphics Programming 180 11 35Problems Try the examples out in this chapter I would also have a look at the examples that come with the Sun JDK These came with an early AWT based version ArcTest BarChart Blink BouncingHeads CardTest DitherTest DrawTest Fractal GraphLayout GraphicsTest ImageMap ImageTest JumpingBox MoleculeViewer NervousText ScrollingImages SimpleGraph SpreadSheet TicTacToe TumblingDuke UnderConstruction WireFrame They can all be found on the College web server in the demo directory under the Java home page The following is the source of the bouncing heads example Taking this as a basis modify the progr
165. d integral promotions are performed 4 8 2 20 gt gt shift right expr gt gt expr Shift right Sign extend The operands must be of integral type and integral promotions are performed 4 8 2 21 gt gt gt sihift right expr gt gt gt expr Shift right Zero fill 4 8 2 22 lt less than expr lt expr Conventional relational operator 4 8 2 23 lt less than or equal expr lt expr Conventional relational operator 4 8 2 24 gt greater than expr gt expr Conventional relational operator 4 8 2 25 gt greater than or equal expr gt expr Conventional relational operator 4 8 2 26 equal expr expr Conventional relational operator 4 8 2 27 not equal expr expr Conventional relational operator 4 8 2 28 amp bitwise AND expr amp expr The usual arithemic conversions are performed the result is the bitwise and function of the operands The operator applies only to integral operands If both bits are set the result is 1 otherwise 0 Ian D Chivers email ian chivers kcl ac uk 67 Arithmetic and Expressions in Java Chapter 4 4 8 2 29 bitwise exclusive OR expr expr The usual arithemic conversions are performed the result is the bitwise exclusive or func tion of the operands The operator applies only to integral operands If either but not both bits are set the result is 1 otherwise 0 4 8 2 30 bitwise inclusive OR expr expr The usual arithemic conversions are perform
166. d its Applications Prentice Hall e A good introduction to Prolog for people with some programming background Good bibliography Looks at a variety of versions of Prolog Marcus C Prolog Programming Applications for Database Systems Expert Systems and Natural Language Systems Addison Wesley e Coverage of the use of Prolog in the above areas As with the previous book aimed mainly at programmers and hence not suitable as an introduction to Prolog as only two chapters are devoted to introducing Prolog Metcalf M and Reid J Fortran 90 Explained Oxford Science Publications OUP e A clear compact coverage of the main features of Fortran 8x Reid was secretary of the X3J3 committee Meyer B Object Oriented Software Construction Prentice Hall e I m just got the second edition The first edition is dated 1988 Whilst obviously Eiffel based well worth a read Also looks at other languages This comparision is not as good as it could be email ian chivers kcl ac uk Ian D Chivers Chapter 2 An Introduction to Programming Languages 44 and Object Oriented Programming Mossenbeck H Object Oriented Programming in Oberon 2 Springer Verlag e A very good and simple introduction to OOP Uses Oberon 2 as the implementa tion language Highly recommended Papert S Mindstorms Children Computers and Powerful Ideas Harvester Press e Very personal vision of the uses of computers by children It challenges many conventional
167. ddWindowListener new BasicWindowMonitor JPanel works much like Panel does so we ll use it JPanel toolbar new JPanel toolbar setLayout new FlowLayout FlowLayout LEFT CCPHandler handler new CCPHandler cutButton new JButton new Imagelcon cut gif cutButton setActionCommand CCPHandler CUT cutButton addActionListener handler toolbar add cutButton copyButton new JButton new Imagelcon copy gif copyButton setActionCommand CCPHandler COPY copyButton addActionListener handler toolbar add copyButton pasteButton new JButton new Imagelcon paste gif pasteButton setActionCommand CCPHandler PASTE pasteButton addActionListener handler toolbar add pasteButton add toolbar BorderLayout NORTH Add the look and feel controls JPanel lnfPanel new JPanel email ian chivers kcl ac uk Ian D Chivers Chapter 13 Events 208 LnFListener lnfListener new LnFlListener this javaButton new JButton Metal javaButton addActionListener ilnfListener infPanel add javaButton motifButton new JButton Motif motifButton addActionListener lnfListener lnfPanel add motifButton winButton new JButton Windows winButton addActionListener lnfListener lnfPanel add winButton add lnfPanel BorderLayout SOUTH
168. de support for high performance programming on a wide variety of machines including massively parallel SIMD and MIMD systems and vector processors From its very beginning HPFF included most vendors delivering parallel machines a number of government laboratories and many university research groups Public input was encouraged to the greatest possible extent A number of suppliers now provide HPF Fortran extensions and these are generally based on Fortran 90 rather than Fortran 77 Fortran 95 and 2000 offer support for parallelisation SMP and MPI are two other developments in this area 2 18 2 Parallel C Similar developments are in the pipeline for C 2 19 Object Oriented Programming Object oriented programming is characterised by two main concepts inheritance dynamic binding The major thing we need to consider is how to extend the functionality of an existing pro gram To make sense of the benefits of OOP we need to have a good understanding of the strengths and weaknesses of the traditional programming paradigm We need to look at the way our appreciation of how to use programming languages developed and what we needed from them as the problems we tackled became more complex To quote Friedman Object oriented programming makes good on the promise of structured program ming It implements in a very practical way the principles of program decomposi tion data abstraction and information hiding It ties together and provid
169. dering java awt java awt Graphics java awt Graphics2D The imaging models supported by the Java 2D API The original producer consumer model The immediate model introduced in the Java 2 JDK The pipeline model in the Java Advanced Imaging API Chapter 11 Introduction to Graphics Programming 138 11 Introduction to Graphics Programming This chapter looks first at a small number of concepts that are essential for successful use of computer generated graphics We start with a coverage of what was available in the original 1 0 x release of Java and also the developments that have taken place since Java has moved on a long way from the first offerings in the 1 0 x JDK 11 1 Vector vs Raster Graphics There are two main ways of doing graphics One involves using x y coordinates and then drawing lines between them The second involves actually looking at points and whether or not they are displayed or not Consider a 10 10 display space With vector graphics we could consider drawing a line be tween 1 1 and 9 9 With raster graphics we consider each row of 10 points and whether a point is on or not 11 2 Pixels With each x y point we have the additional feature of a gray scale value or colour value 11 3 Bit maps gif vs jpg These are the two bit map formats currently supported by Java As jpg is smaller I recom mend using this bit map format rather than gif 11 4 Screen resolution Screens come in a number of display sizes T
170. dest name else File parentdir parent destination file if parentdir exists throw new convertException convert destina tion directory doesn t exist dest name if parentdir canWrite throw new convertException convert destina tion directory is unwriteable dest_name If we ve gotten this far then everything is okay we can if copy the file source new FilelnputStream source_file destination new FileOutputStream destination file int 1 0 byte carriage return 13 byte line feed 10 char c int byte read while true byte_read source read if byte read 1 break i if byte_read lt 32 byte_read gt 127 byte_read 32 if i gt 60 amp amp byte_read 32 c char carriage_return destination write c c char line feed destination write c i 0 c char byte_read destination write c Ian D Chivers email ian chivers kcl ac uk 127 i o Chapter 9 No matter what happens always close any streams we ve opened finally if source null try source close catch IOException e if destination null try destination close catch IOException e DEC File getParent can return null when the file is spec ified without a directory or is in the root directory This method handles those cases priv
171. dio clip getAudioClip public AudioClip getAudioClip URL url Returns the AudioClip object specified by the URL argument This method always returns immediately whether or not the audio clip exists When this applet attempts to play the audio clip the data will be loaded Parameters url an absolute URL giving the location of the audio clip Returns the audio clip at the specified URL getAudioClip public AudioClip getAudioClip URL url String name Returns the AudioClip object specified by the URL and name arguments This method always returns immediately whether or not the audio clip exists When this applet attempts to play the audio clip the data will be loaded Parameters url an absolute URL giving the base location of the audio clip name the location of the audio clip relative to the url argument Returns the audio clip at the specified URL newAudioClip public static final AudioClip newAudioClip URL url Get an audio clip from the given URL Parameters url Points to the audio clip 20 3 Example Audio This is example 2 from chapter 16 of the Deitel book Fig 16 2 LoadAudioAndPlay java Load an audio clip and play it import java applet import java awt import java awt event import javax swing public class LoadAudioAndPlay extends JApplet private AudioClip soundl sound2 currentSound private JButton playSound loopSound stopSound private JComboBox chooseSound
172. doing some printing Again there are several pro cesses running Java supports the concepts of threads This means that you as the writer of a Java program can create a program that has several threads running This is useful when retrieving images from another site whilst at the same time still interacting with the user It will therefore be necessary to make certain methods run in a way where they have sole access to an object You don t want several threads modifying the same StringBuffer object for example So we declare a method synchronized to force locking of any objects that they have access to in reality objects that they change The second concept is that of error handling Most of you will be familiar with programs you have written that terminate when you type in unexpected values Situations like this are handled in Java by the ability to throw an exception The error is then handled by an excep tion handler In the example above insert methods may make the StringBuffer object too large In this case an exception is raised and control will pass to the error handler We will look at a couple of example programs to clarify the above 5 3 1 1 StringBuffer Example 1 throwing an exception and catching import java lang class c0507 public static void main String args StringBuffer sl new StringBuffer this is the base string StringBuffer s2 new StringBuffer inse
173. e and it has evolved in response to the demands that people have made on it Java is now be ing used in areas well beyond what it was originally capable of doing We are now going to look at two ways of doing things within Swing The first will inherit from JApplet The second will inherit from JComponent 14 13 JApplet JApplet is well down the Java class hierarchy and this is shown below email ian chivers kcl ac uk Ian D Chivers Chapter 14 Swing 224 java lang Object gt java awt Component gt java awt Container gt java awt Panel gt java applet Applet javax swing JApplet An extended version of java applet Applet that adds support for interposing input and paint ing behavior in front of the applets children see glassPane support for special children that are managed by a LayeredPane see rootPane and for Swing MenuBars The JApplet class is slightly incompatible with java applet Applet JApplet contains a JRootPane as it s only child The contentPane should be the parent of any children of the JApplet This is different than java applet Applet e g to add a child to an an java ap plet Applet you d write applet add child However using JApplet you need to add the child to the JApplet s contentPane instead applet getContentPane add child The same is true for setting LayoutManagers removing components listing children etc All these methods should normally be sent to the contentPane i
174. e 2 if i 0 System out println Entering negative region else if i 0 System out println crossover reached else System out printin Positive region entered Note the semi colons Again will catch the Pascal Modula 2 programmer out 7 6 switch expression statement This is best illustrated with a simple example 7 6 1 Example 1 import import java io java lang Integer class c0704 public static void main String args int 1 0 Integer I new Integer i String Line try InputStream ip System in DatalnputStream inp new DataInputStream ip System out println Type in an integer value Line inp readLine Integer valueOf Line i I intValue switch 1 case 1 System out println one entered break case 2 System out println two entered break case 3 System out println three entered break default System out println number other than 1 2 or 3 entered email ian chivers Q kcl ac uk O Ian D Chivers Chapter 7 Control Structures 100 break catch IOException e System out println Exceptions raised e Note the use of the break statement to exit from the switch statement otherwise execution simply drops through Equivalent to the case statement in other languages 7 7 while expression st
175. e getActionCommand equals Metal lnfName javax swing plaf metal MetalLookAndFeel else if e getActionCommand equals Motif lnfName com sun java swing plaf mo tif MotifLookAndFeel else lnfName com sun java swing plaf win dows WindowsLookAndFeel try d UIManager setLookAndFeel lnfName SwingUtilities updateComponentTreeUl frame catch UnsupportedLookAndFeelException exl System err println Unsupported LookAndFeel lnfName catch ClassNotFoundException ex2 System err println LookAndFeel class not found lnfName catch InstantiationException ex3 System err printin Could not load LookAndFeel lnfName catch IllegalAccessException ex4 System err println Cannot use LookAndFeel lnfName O Ian D Chivers email ian chivers Okcl ac uk 207 Events Chapter 13 This is the third file x ToolbarFrame4 java The Swing ified button example The buttons in this toolbar all carry images but no text ur import java awt import java awt event import javax swing public class ToolbarFrame4 extends Frame This time let s use JButtons Button cutButton copyButton pasteButton Button winButton javaButton motifButton U o public ToolbarFrame4 super Toolbar Example Swing no text setSize 450 250 a
176. e idea is to buy one of the shelf and slot it straight in to our program This is gradually becoming a reality Sun and Microsoft both made developments in this area and we will look at each in turn 2 24 3 1 COM OLE ActiveX First let us define each of the above in turn COM Component Object Model OLE Object Linking and Embedding ActiveX Now called Active Technologies Let is look briefly at each in turn ActiveX is a set of technologies that enables software components to interact with one an other in a networked environment regardless of the language in which they were created ActiveX is build on the Component Object Model OLE or OLE Automatation makes it possible for one application to manipulate objects im plemented in another application or to expose objects so that they can be manipulated A simple example of this would be embedding a spreadsheet of graph from Excel in a Word document Double clicking on the spreadsheets drops you into Excel There are some problems with this when working with a document on a number of computer systems with different versions of the applications concerned The Component Object Model COM is a platform independent distributed object orientded system for creating binary software documents that can interact COM is the foundation technology for OLE and ActiveX 2 24 3 2 JavaBeans JavaBeans is the Java language software component offering JavaBeans extends the Java language write once run ever
177. e methods to compose a draw primitive with the underlying graphics area CompositeContext The CompositeContext interface defines the encapsulated and optimized environ ment for a compositing operation ItemSelectable The interface for objects which contain a set of items for which zero or more can be selected LayoutManager Defines the interface for classes that know how to layout Containers LayoutManager2 Defines an interface for classes that know how to layout Containers based on a layout constraints object MenuContainer The super class of all menu related containers Paint This Paint interface defines how color patterns can be generated for Graphics2D operations PaintContext The PaintContext interface defines the encapsulated and optimized environment to generate color patterns in device space for fill or stroke operations on a Graphics2D PrintGraphics An abstract class which provides a print graphics context for a page Shape The Shape interface provides definitions for objects that represent some form of geometric shape Stroke The Stroke interface allows a Graphics2D object to obtain a Shape that is the decorated outline or stylistic representation of the outline of the specified Shape Transparency The Transparency interface defines the common transparency modes for imple menting classes email ian chivers kcl ac uk Ian D Chivers Chapter 11 Introduction to Graphics Programming 156 11 23 2
178. e of the SQL standard ISO 9075 1992 E Chivers I D and Clark M W History and Future of Fortran Data Processing vol 27 no 1 January February 1985 e Short article on an early draft of the standard around version 90 Chivers I D and Sleightholme J Introducing Fortran 90 Springer Verlag e An introduction to programming using Fortran 90 Aimed at numeric problem solving Chivers I D and Sleightholme J Introducing Fortran 95 Springer Verlag e An introduction to programming using Fortran 95 Aimed at numeric problem solving Updated to reflect the new standard and with coverage of two tecnical updates to the language that will be part of the next standard F2K Computational Science Education Project Fortran 90 and Computational Science e This paper is a comparison of C Fortran 77 C and Fortran 90 using the fol lowing five criteria numerical robustness data parallelisation data abstraction object oriented programming and functional programming A copy is available on the college web server Essential reading if one is involved in programming with one or more of these languages Cowell J Essential Java Fast Springer e Compact introduction to Java Insufficient on its own Dahl O J Dijkstra E W Hoare C A R Structured Programming Academic Press 1972 e The seminal book on structured programming email ian chivers kcl ac uk Ian D Chivers Chapter 2 An Introduction to Programming Lan
179. e or more operations are carried out and a value is returned 7 3 Boolean Remember that within standard Java boolean exists as a built in type with values of true and false 7 4 if expression statement Simple if statement If the expression is true execute the statement that follows Note that have to be used if it is necessary to execute multiple statements 7 4 1 Example 1 if 1 gt 0 System out println Now above 0 If i is greater than O the cout statement is executed Note that you cannot make the classic C and C howler in Java If you are familiar with C and C then you may be surprised to know that the following example won t compile class c0703 public static void main String args int i 0 int 3 10 System out println i System out printlin j if i 1 13997 System out println i System out println 3 7 5 if expression statement else statement Standard extension to the if statement Again have to be used if it is necessary to execute multiple statements O Ian D Chivers email ian chivers kcl ac uk 99 Control Structures Chapter 7 7 5 1 Example 1 if i lt 0 System out println Result not defined for negative val ues else System out printin Calculating for positive i One or other of the cout statements will be executed Note the semi colons If you are fa miliar with Pascal or Ada this will catch you out 7 52 Exampl
180. e paper by Parnas addresses the idea of information hiding and the module concept is one that a number of languages now offer to help in this area 2 17 Terminology of Object Oriented Programming The following provides a link between conventional programming language terminology and that used in object oriented programming Class Extensible abstract data type Object Instance of a class Message Procedure call dynamically bound Method Procedure of a class See Mossenbeck for a good treatment of this We ll come back to the whole area of object oriented programming after a coverage of the basics of C 2 18 Parallel Developments With the increasing availability of computers with multiple processors at ever decreasing costs the importance of languages that support parallel computation increases Two lan guages that offer support in this area are based on Fortran 90 and C A brief coverage is given below email ian chivers kcl ac uk Ian D Chivers Chapter 2 An Introduction to Programming Languages 32 and Object Oriented Programming 2 18 1 Parallel Fortran Fortran 95 Fortran 2000 SMP MPI HPF To quote from the HPF Language Specification version 1 1 November 1994 The High Performance Fortran Forum HPFF was founded as a coalition of industrial and aca demic groups working to suggest a set of standard extensions to Fortran to provide the nec essary information Its intent was to develop extensions to Fortran that provi
181. e presentation elements in the GUI and the facili ties to provide for any subsequent data negotiation and transfer This package defines the classes and interfaces necessary to perform Drag and Drop opera tions in Java It defines classes for the drag source and the drop target as well as events for transferring the data being dragged This package also provides a means for giving visual feedback to the user throughout the duration of the Drag and Drop operation 26 1 1 Interface Summary 26 1 1 1 Autoscroll During DnD operations it is possible that a user may wish to drop the subject of the opera tion on a region of a scrollable GUI control that is not currently visible to the user 26 1 1 2 DragGestureListener This interface is sourced from a DragGestureRecognizer and is invoked when an object of that sub class detects a drag initiating gesture 26 1 1 3 DragSourceListener The DragSourceListener defines the event interface for originators of Drag and Drop opera tions to track the state of the user s gesture and to provide appropriate drag over feedback to the user throughout the Drag and Drop operation 26 1 1 4 DropTargetListener The DropTargetListener interface is the callback interface used by the DropTarget class to provide notification of DnD operations that involve the subject DropTarget 26 1 Class Summary 26 1 2 1 DnDConstants This class contains constant values representing the type of action s to be performed by a D
182. e te ate eR rece reg eterna eene 279 23 1 1 6 Calling Servlets From a Browser esee 279 23 1 1 7 Calling Servlets from an HTML page seen 280 23 2 PACKAGE Java SEL VICE soe dte eite seed nb quta en Qa de 280 23 2 1 Interfaces EROR I HER I eee 280 23 2 2 IERI p EN 280 23 2 3 EXCODUOHS 5 bereits ee ORAT dae Te aio be SPAREN E SPA S eS e PECES ines 280 23 3 Package jaya servlet Http xo deitate oie aE A dM Me DNI ehe tan Aries 280 23 3 1 InterfaCes sd llena ricardo eire eie 280 23 3 2 QUELLE 281 23 4 Package java setyvlet Spu iiie etre et YE eed Y Re NR S ESSERE ee a SUC RAS SYL Fe de Y sedeo Re eda 281 23 4 1 A ERES 281 23 4 2 Classes EE 281 23 4 3 EXCeDLCODS antibioticos dee ee oe ee Ree lee loe RAE aA 281 23 5 Package Java servlet sp tagtext iio aee esci te egt iones dentadas 281 23 5 1 Interfaces M RE 281 23 5 2 MERC EM 281 23 5 A A ra cedet Cols Rate Peale dtu vp us 281 24 JavaServer AA A II ON 284 ES 284 24 1 1 A AA 284 24 1 2 Has 284 24 1 3 AM EEE E A A ii e tire et dee NEEE 284 25 Package Javacutil alice 286 25 Package CHILD EN E 286 25 1 1 Interface Summary oos dial fiat 286 25 1 1 1 Collection entrada liado tito E 286 25 1 1 2 Comparato E 286 25 1 1 3 ISriunis cito 286 Contents 13 25 1 1 4 EventLastener ua sia iria 286 25 115 A Ue 286 25 1 1 6 IB 286 25 1 1 7 IE reo TEES 286 25 1 1 8 Map dpa eee ence qur qe Ee RM EUR cates 286 25 1 1 9 ME E 286 25 1 1 10 ODsetvet decree preso
183. e very considerable benefits to the above syntax Please perservere The additional complexity is worth it in the longer term 3 10 Program for numeric i o The following is a complete program example of numeric i o import java io import java lang Float Ian D Chivers email ian chivers kcl ac uk 55 An Introduction to Java Chapter 3 class c030301 public static void main String args try InputStream i System in DatalnputStream in new DatalnputStream 1 String Line float f 1 0f Float F new Float f System out println Type in a number Line in readLine F Float valueOf Line f F floatValue System out printlin f catch IOException e System out printin Exceptions raised e Let us look at statement in turn class c030301 This is the name of our class Remember that the file name used at the operating system side must be the same public statio void main Stringl args This signifies that this is a Java program This is the standard Java program statement try We are doing i o so we must use try and catch to trap errors InputStream i System in I is a variable or object of type InputStream and it has an inital value of System in DataInputStream in new DatalnputStream i in is an object of type DataInputStream and it is created using new DataInputStream i String Line Line is of type String float f 1 0f f
184. eads running System out println Thread currentThread getName This is the only statement that is in the run procedure It will get the name of the currently executing thread and print it out The output of this program will depend on the system that you run it on 10 2 Example 2 Extends Thread This example is a simple variant of the first public class thread02 extends Thread int delay thread02 int t delay t public static void main String args thread02 tl new thread02 50 thread02 t2 new thread02 100 tl start t2 start public void run try for Sys tem out println Thread currentThread getName sleep delay catch InterruptedException e return email ian chivers Q kcl ac uk O Ian D Chivers Chapter 10 Threads 132 The first thing of interest is the addition of a class variable delay Whenever we create an object of this class we will also create a variable called delay thread02 int t delay t We now supply our own constructor for an object of type thread02 The constructor tales one argument and will be used to provide a value for the class variable delay thread02 tl new thread02 50 thread02 t2 new thread02 100 We now create two thread objects and provide initial values for delay The time is in milli seconds Sys tem out println Thread currentThread getName sleep delay
185. ed the result is the bitwise inclusive or func tion of the operands The operator applies only to integral operands If either bit is set the result is set otherwise 0 4 8 2 31 amp amp logical AND expr amp amp expr The operands must be boolean Left to right evaluation is guaranteed and the second operand is not evaluated if the first is false 4 8 2 32 Il logical inclusive OR expr ll expr The operands must be boolean The result is true 1f either of its operands is true and false otherwise Left to right evaluation is guaranteed and the second operand is not evaluated if the first is true 4 8 2 33 conditional expression expr expr expr The first expression is converted to bool It is evaluated and if it is true the result of the conditional expression is the value of the second expression otherwise that of the third All side effects of the first expression except for destruction of temporaries happen before the second or third expression is evaluated 4 8 2 34 conventional assignment expr expr Conventional assignment 4 8 2 35 multiply and assign expr expr Multiply and assign e g a a expression 4 8 2 36 divide and assign expr expr Divide and assign e g a a expression 4 8 2 37 modulo and assign expr expr Modulo and assign e g a a expression 4 8 2 38 add and assign expr expr Add and assign e g a a expression 4 8 2 39 subtract and assign expr
186. eeSelectionEvent An event that characterizes a change in the current selection UndoableEditEvent An event indicating that an operation which can be undone has occurred 13 2 3 Package javax swing event Provides for events fired by Swing components It contains event classes and corresponding event listener interfaces for events fired by Swing components in addition to those events in the java awt event package 13 3 ActionListener The listener interface for receiving action events The class that is interested in processing an action event implements this interface and the object created with that class is registered with a component using the component s addActionListener method When the action event occurs that object s actionPerformed method is invoked O lan D Chivers email ian chivers Okcl ac uk 205 Events Chapter 13 13 4 ActionEvent A semantic event which indicates that a component defined action occured This high level event is generated by a component such as a Button when the component specific action occurs such as being pressed The event is passed to every every ActionListener object that registered to receive such events using the component s addActionListener method The object that implements the ActionListener interface gets this ActionEvent when the event occurs The listener is therefore spared the details of processing individual mouse movements and mouse clicks and can instead process a meaningful seman
187. eed de re e ETE ER UR E HERES 286 25 1 1 11 NP 286 25 1 1 12 Niue UE TER 286 25 1 1 13 So do ir EUN 286 25 1 2 Class Summary 4 ene re nie eet tret E edu cer ee ta reete 287 25 1 2 1 AbstractCollection eet eye tee be e pere tet TTE 287 25 1 2 2 AJNDSACULEISE iio pere t exte tue Hace e ect dtes eret nere nde 287 25 1 2 3 AbstractMap nianieira e reete ERISQUE Ire b le HER Eee ER ER dd 287 25 1 2 4 AbstractSequentialList occ ec ere rere iet rite edet EO AAE 287 25 1 2 5 ADSITACES OL MD 287 25 1 2 6 JATTAY EASE 742r teet EH eec deseen itt e metit Ho cte ceo aee t ec er A Eds 287 25 1 2 7 ATA MULT 287 25 1 2 8 Bi S et cc dete rete teet ere tee eo etse tere tete urere 287 25 1 2 9 A EE 287 25 1 2 10 Collections C E A EE 287 25 1 2 11 Bir E AEE A E tebe 287 25 1 2 12 DICUON ALY RR ETE 287 25 1 2 13 EventObjJect iit eei ee cde e re SU Ee Eu ER ee Pr een ae 287 25 1 2 14 GreeorranCalendat 5 in tete et testing qe tec cerit loe Pt o e Hoe ues 287 25 1 2 15 HashMap i neg een Ep o e MERE P REED dee 287 25 1 2 16 HashSet aen rito nara so a 288 25 1 2 17 Hashtable E 288 25 1 2 18 In al E E E E E E E 288 25 1 2 19 ListResourceBundle inisesin iia died sido wetter dabas 288 25 1 2 20 A A ER A T 288 25 1 2 21 Observable tette de th Ped AS es 288 25 1 2 22 NA e ER Ee ee espe eet ee egi eee tees oda 288 25 1 2 23 Property Permissions saena eaa ere ener te IAE FG tetro a Teen ATT es 288 25 1 2 24 PropertyResourceBundle
188. eerenren rennen 67 4 8 2 40 lt lt shift left and assign expr lt lt OXPTeccccoccnoccnocnnocnnonononoconananonan crac conc crono cn nannncnnnos 67 4 8 2 41 gt gt shift right and assign Expr gt gt EXPL seen 67 4 8 2 42 amp AND and assign expr amp expr sese eene 67 4 8 2 43 l inclusive OR and assign expr expr eeeerenenen 67 4 8 2 44 exclusive OR and assign expr S OXPlococonoccnoconocnnonoconoconanannnnnnonn non ener 68 4 0 Expression Example festen cst Quodsi denter quio acer RESE EISS 68 ALO GIL dM L eiaseedeane 71 AMD VOL LUC 72 412 Example POSTAS i eto rer ap are Da a eo a orti ee dps uud 72 4 12 1 Example Program Simple character and boolean output eee 72 4 12 2 Example Program Unicode character output eese 72 4 12 3 Example Program Bitwise operators amp and l sese 72 ALO UI S Cou o odds 13 4 package Java l ng coxtossueisoioteDisastei dette bru ei desc E das eb R Ma es E dat us 13 4 14 1 Interface Summary seoran eee Aa E ETE ee te eerte 73 4 14 1 1 Cloneable simi IER epit item pese 73 4 14 1 2 Comparable pirita taa tap rr Haee e iia 73 4 14 1 3 Runnable cial Heg nate dc a o a PR QE d eerie 73 4 14 2 Class SUIBIDALy z aliaron tegis desee sheet eode De e eee Ue oi 73 4 14 2 1 prc 73 4 14 2 2 Byte sie ittis estt hel Hein OE rr rd teur edet ade Fe nte oaen
189. enta tion elements in the GUI Components potentially capable of consuming Trans ferable data types email ian chivers kcl ac uk Ian D Chivers Chapter 26 Package java awt dnd 294 A DragGestureRecognizer is obtained from the DragSource and is associated with a Component in order to track and identify any Drag initiating gesture by the user over the Component A user makes a Drag gesture over the Component which the registered DragGestureRecognizer detects and notifies its DragGestureListener of Note Although this API consistently refers to the stimulus for a drag and drop operation being a physical gesture by a human user this does not preclude a pro grammatically driven DnD operation given the appropriate implementation of a DragSource This package contains the abstract class MouseDragGestureRecognizer for recognizing mouse device gestures Other ab stract subclasses may be provided by the platform to support other input devices or particular Component class semantics The DragGestureListener causes the DragSource to initiate the Drag and Drop operation on behalf of the user perhaps animating the GUI Cursor and or render ing an Image of the item s that are the subject of the operation As the user gestures navigate over Component s in the GUI with associated DropTarget s the DragSource receives notifications in order to provide Drag Over feedback effects and the DropTarget s receive notifications in order to pro
190. eo Mosa o rd Mer sed ca ER Ia 225 1417 Bibltosraphya e na iio EARS 225 EA A N 228 15 1 Package Java beans JDK 1 1 veronica oi sin 230 15 2 Package java Dean DEANCONTEX senti se veo te tsi i R 230 EM Example linia aii ioe dan ordenado HM 230 ISA Summi y ennei EN 232 15 5 Useful addresses ni dd 232 156 Problems tete tl isos 233 16 Overview of Development Environments csssccccsssssssscccssssssccssssssssseees 236 16 1 Edit Compile and RUlisos oce ore E A EA A A A 236 16 2 Workbene Ber IDE 48 haces ne a o tus 236 16 5 Visual Development Tools id ds is 238 LGA A A ae A OS 238 17 Forte for Java iia 240 17 1 Forte Recommended Configurations cooooccnocccnonccconnnnnnonanononcnnnnnnconnnnnnnnncconnnnnnncnnnns 240 17 2 Th DR italia 240 I3 JGCUIBSEDHLOD scssi a mener oat a tia red LN bc fiae Itc circu os 240 18 Microsoft Visual EL TM ratita ainda aer aaa ta 242 sl Ayv ilability and Versions tin esci sus Sd ede idle pe QUE dus a eap ento UC a ide ERIS 242 18 2 The Development Envira ad eras eerte eee A a 242 15 3 WO A mh E dE oem SD ACE EE 243 18 4 1 Doecurmetbdton MODs esent o MODO recu Nen meta itd tertie 243 18 5 Getting Started with Visual J 0 0 auo tido 244 18 5 1 Creating a WEC Application 1rd tereti api 244 18 5 2 Building and Running Your Application eese 244 18 5 3 Debugging Your Application essent nene entrent ene 245 18 5 4 Packaging Your Application
191. er model rather than a chain based model This eliminated a lot of the overhead of event propagation In April 1997 the JFC were announced One of the new components were given the name Swing They JFC comprises Swing We will cover this in this chapter AWT The basic gui Accessibility This package is for people who find access using a keyboard mouse and screen a problem 2D API Package for painting complex shapes fonts etc Drag and Drop This package allows users to implement a visual interface to their code Swing was based on both Netscape s Internet Foundation Classes and input from IBM s Taligent division and Lighthouse Design Swing sits on top of AWT Swing is written entirely in Java and has a consistent look and feel across platforms 14 2 What do I need I would recommend getting hold of the 1 2 JDK as this will have everything you require I would also recommend getting hold of the on line documentation This is up on the Col lege web server The url is http www kcl ac uk kis support cc fortran java dk1 2 2 docs If you program on a pc then I would install this in conjunction with JDK 1 2 Ian D Chivers email ian chivers kcl ac uk 215 Swing Chapter 14 14 3 Swing Packages There is a problem here is that Sun have had more than one resting place for the Swing package It was first released in com sun java swing and has since moved to javax swing The IBM VisualAge version I use e
192. ere Java differs from conventional procedural programming In the first part of this chapter we will look at event handling based on the early 1 0 x jdk 13 1 AWT Events We will look at AWT based event handling first There are two kinds of AWT event handling mechanisms provided in Java one for the key board and the other for handling the mouse We will look at each in turn 13 1 1 Mouse Events public boolean mouseDown Event e int x int y public boolena mouseUp Event e int x int y public boolean mouseMove Event e int x int y public boolena mouseExit Event e int x int y public boolean mouseEnter Event e int x int y public boolena mouseDrag Event e int x int y 13 1 2 Keyboard events public boolean controlDown bublic boolean metaDown public boolean shiftDown public final static int LEFT public final static int RIGHT public final static int END public final static int HOME public final static int PGDN public final static int PGUP public final static int Fx Function keys 1 through 12 13 13 Example 1 Cut and paste text This example illustrates some of the above import impor java applet Applet java awt CT CT public class c1401 extends Applet private TextArea t1 t2 private Button b public void init String s This is some text that spans n several line We use the control n n Character to do this Ian D Chivers email ian chivers kcl ac uk
193. es a frame work for abstraction and structure at all levels data program and control OOP picks up where structured programming methodology leaves off Dijkstra s concept of structured programming Wirth s stepwise refinement and Parnas s infor mation hiding all contribute to a software development milieu that promised to be come increasingly systematic and scientific OOP to a great extent fulfils that promise It takes the concepts of data abstraction modular decomposition and infor mation hiding and refines them in a cohesive world view data objects are active en tities Instead of passing data to procedures the user asks objects to perform opera tions on themselves A complex problem is viewed as a network of objects that communicate with each other The benefits of OOP come with programming in the large If the problems you have don t warrant it you may never need to devote the time and effort to gain complete mastery of a powerful and complex language like C O lan D Chivers email ian chivers Okcl ac uk 33 An Introduction to Programming Languages Chapter 2 and Object Oriented Programming 2 20 Object Oriented Languages The ideas are not new 2 20 1 Simula 1967 The seminal text on OOP is Simula BEGIN Birtwistle Dahl Myhrhaug and Nygaard The book is very well written if a little dated today I d recommend it if you are involved in dis crete event simulation This was what the language was used for whilst I worked at
194. es that have RGB color components embedded directly in the bits of the pixel itself DirectColorModel model is similar to an X11 TrueColor visual ComponentColorModel a ColorModel that can handle an arbitrary ColorSpace and an array of color components to match the ColorSpace IndexColorModel a ColorModel that represents pixel values that are indices into a fixed color map in the sRGB color space ComponentColorModel and PackedColorModel are new in the JavaTM 2 SDK software re lease 11 29 12 Printing The Java Printing API enables applications to Print all AWT and Java 2DTM graphics including composited graphics and im ages Control document composition functions such as soft collating reverse order printing and booklet printing Invoke printer specific functions such as duplex two sided printing and sta pling Print on all platforms including Windows and Solaris This includes printers di rectly attached to the computer as well as those that the platform software is able to access using network printing protocols Not all of these features are supported in the Java 2 SDK Printing API and implementation The API will be extended to support all of these features in future releases For example additional printer controls will be added by augmenting the set of named properties of a print job that the application can control Sun also make available a lot of sample programs This is available at their web site It was about 350 Kb
195. es the rest is history Java is a relatively simple object oriented language Whilst it has its origins in C it has dispensed with most of the dangerous features It is OO throughout Everything is a class It is interpreted and the intermediate byte code will run on any machine that has a Java vir tual machine for it This is portability at the object code level unlike portability at the source code level which is what we expect with most conventional languages It has built in garbage collection no dispose It has no pointers everything is passed by reference It is multithreaded which makes it a delight for many applications It has a extensive windows toolkit the so called AWT that was in the original release of the language and Swing that came in later It achieves much of what Visual Basic offers but within the framework of a far more powerful language Development environments are be coming widely available to aid in this task Finally it is fun Major drawback is the rapid development of the language and the large number of different versions Further compounded by the different virtual machines available 2 13 Visual Basic This language is a development by Microsoft to enable visual user interfaces to be pro grammed easily It has subject to continual development and offers one of the easiest ways of developing a windows style program for a pc running Windows 3 x 95 98 and NT 2 14 Language Comparison The f
196. est moon Oberon was simpler than Modula 2 Oberon 2 tidied up a bit First operational system by the late 1980s Oberon replaced Modula 2 in 1989 for teaching purposes at ETH Ported to a Apple MAC SUN DEC IBM RS6000 and MS DOS by 1991 Free versions available from the ftp server at ETH Let down badly by continual development and lack of a standard It is a research vehicle for Wirth and the CS department at ETH in Zurich Some of the problems here may be reme died in the near future with the progress being made on the standardisation front 2 9 Fortran 90 1991 Modern language Limited OO capability Good information hiding and powerful mathe matical capability The language of first choice for people involved in numeric program ming 2 10 Eiffel 1988 Date is the publication of Object Oriented Software Construction Meyer Prentice Hall Modern object oriented language Meyer is a very keen exponent of the benefits of object oriented programming Meyer s book on object oriented software construction is an ex tremely good introduction to OO programming The second edition is even better Eiffel is an attempt to produce an industrial strength OOP language I hope to be able to make available an Eiffel compiler for the alpha in the near future Another extremely worthwhile acquisition is Software Development Using Eiffel There Can Be Life Other Than C Richard Wiener He highlights some of the weaknesses of C If you are going
197. et Applet This class has a number of methods init start stop destroy Ian D Chivers email ian chivers kcl ac uk 51 An Introduction to Java Chapter 3 but in this example we have not bothered overriding them rather we have relied on default behaviour Within our applet we have one method public void paint Graphics g and the method is public and void The paint method takes one parameter and this is an ob ject g of type Graphics which is one of the data types provided Within this method we have one statement g drawString Hello world 10 20 and this applies the drawString method to the object g The arguments to drawString are Hello world the string we want to appear on the screen 10 the x position in pixels 20 the y position in pixels The character signifies the end of the applet The outcome of all of this is that we now have an applet that we can run within a web browser e g netscape This is not the end of the story however We also need an html file that can be loaded into the browser HyperText Markup Language HTML is a markup lan guage and is based on SGML which is an ISO standard Within HTML terms a document comprises two parts the text and the markup Markup languages are not new and TeX and Runoff are two widely used markup languages HTML is widely used and is the basis for the World Wide Web WWW distributed information system The web was originally de ve
198. ethods are final they cannot be over ridden 9 6 java io PrintStream class The most useful i o stream for displaying text on the screen when running programs For each print method there is a corresponding println method public synchronized void print char s public synchronized void print String s public void print boolean b public void print char c public void print double d public void print float f public void print int 1 public void print long 1 public synchronized void print Object o public synchronized void printIn char s public synchronized void printIn String s public synchronized void printIn boolean b public synchronized void printIn char c public synchronized void printin double d public synchronized void println float f public synchronized void printlIn int 1 public synchronized void printin long 1 Note that when we invoke the println method with an object there is a hidden call to the toString method associated with that object 9 6 1 Synchronized Java supports multiple threads As such it is necessary to be able to indicate that a critical section of code or method must be allowed to complete This is because the code segment or class is modifying the internal state of the class The concepts introduced are not new email ian chivers kcl ac uk O Ian D Chivers Chapter 9 i o 124 and anyone who has done an operating system course or real time programming would be familiar with the ideas
199. ets They can be simple such as a text box or label or they can be complex such as a mail tool or a data inspector Beans typi cally have a set of properties are the attributes exposed by a bean methods are the actions that a bea makes available for use by other beans events the events that the bean makes happen JavaBeans is a component architecture for the Java platform ActiveX is Microsoft s offer ing The following is taken verbatim from the Sun blurb about JavaBeans I couldn t resist THE CHOICE IS CLEAR Write to the JavaBeansTM Component Architecture Throughout the industry JavaBeans component architecture is the architecture of choice More than 1 000 000 developers around the world have already embraced the JavaTM platform And no wonder The Java platform has opened up an entirely new world of opportunities for building fully portable network aware applications Yet many developers are not yet sure how best to take advantage of the capabilities and benefits the Java platform delivers without sacrificing their existing investment in legacy applications The Answer is JavaBeans Component Architecture JavaBeans component architecture is the platform neutral architecture for the Java application environment It s the ideal choice for developing or assembling net work aware solutions for heterogeneous hardware and operating system environ ments within the enterprise or across the Internet In fact it s the only component arch
200. eu eer E 160 11 23 5 1 Constructor SUMMALY ice Suede Cerere Ponce Eee LER Certe DARE D Bop ve ee ete ria 161 11 23 5 2 Method Summiaty a aiti o Hee Det rhe Dent Leer eere leere den edere EEES 161 11 24 Package java awt Graphics2D JDK TD usina rien nade idad 164 11 24 1 Rendering item reete dei le EH EB en e Ce Le degere e be se ebo et be creci 164 11 24 2 Compatability ip edet e seed dentia gp e dee 165 11 24 3 Constructor SUMMA iii lolis 165 11 24 4 UA A O eerie 165 11 25 Package java awt geom JDK 1 2 ii dias 168 11 26 Package Java awt um JDK Lucro anita dos to pee eher ae Nn gine aurei dn 168 11 27 Package java awt image renderable JDK 1 2 eene 168 11 28 Package Javaawt prmt JDK 1 2 eee teet ier sean ee Erde a neo eae e RE Re iana 168 11250 Java 2D ANPIONGEVIQU doeet toties cult uote aestus Da ev S DANOS 168 11 29 1 Enhanced Graphics Text and Imaging eeeeeeeeeeeeeeeen enne 168 11 29 2 Rendering Model ocacion dcir 169 11 29 3 Backward Compatibility and Platform Independence esses 169 11 29 4 Setting Up the Graphics2D Context esee ener nnne 170 11 29 5 Rendering Graphics Primitives tret ipte peret tree eee g i 170 11 29 6 Managing and Manipulating Rasters esee 170 11 29 7 Geometries NEN EE 170 11 29 8 Fonts and Text Layout vacunar pie Heg ti ec HE Ee Rus 171 11 29 9 Imaglng s c i ettet beverages sede
201. expr Subtract and assign e g a a expression 4 8 2 40 lt lt shift left and assign expr lt lt expr Shift left and assign 4 8 2 41 gt gt shift right and assign expr gt gt expr Shift right and assign 4 8 2 42 amp AND and assign expr amp expr AND and assign 4 8 2 43 l inclusive OR and assign expr expr inclusive OR and assign email ian chivers Q kcl ac uk O Ian D Chivers Chapter 4 Arithmetic and Expressions in Java 68 4 8 2 44 z exclusive OR and assign expr expr exclusive OR and assign 4 9 Expression Examples It is not appropriate here to cover each and everyone of the above in great depth We will introduce examples throughout the notes as we progress Note that there is no exponentiation operator The following programs and program extracts cover some of the above class c0404 public statio void main String args int i 0 int 3 0 System out println ti System out println 3 The above example highlights the use of the pre and post increment and decrement opera tors Type the above in and run it class c0405 public static void main String args int 1 9 int 3 2 int k 2 System out printin i j System out printin i k System out printlin i j System out println i k Type this example in and run it Java defines and to obey the following x y y x y x Consider the following example cl
202. following program cycles through the colours in steps of 10 import java awt public class c1160 extends java applet Applet public void init setBackground Color white public void paint Graphics g for int red 0 red lt 256 red red 10 for int green 0 green lt 256 green green 10 for int blue 0 blue lt 256 blue blue 10 Color yeuk new Color red green blue g setColor yeuk g fillOval 10 10 100 100 11 22 9 Texts and Fonts Java provides support for a number of widely available fonts The following table gives names on three platforms Java name X Windows Windows Macintosh Helvetica adobe helvetica arial TimesRoman adobe times times new roman Courier adobe courier courier new Dialog b amp h lucida ms sans serif DialogInput b amp h lucidatypewriter ms sans serif ZapfDingbats itc zapfdingbats windings default misc fixed arial We can also use the fonts in four variations PLAIN email ian chivers Q kcl ac uk O Ian D Chivers Chapter 11 Introduction to Graphics Programming 154 BOLD ITALIC BOLDITALIC The following example prints out some text in some of the above fonts in each of the four variations import java awt public class cl1170 extends java applet Applet String s public void showfont String s Font f new Font s Font PLAIN 20 setFont f add new Label plain f new Font s Font BOLD 20 setFont f add new Label
203. from byte to String and StringBuffer arrays of bytes and you should chose the representation that is most suited to your application 5 7 Problems 1 Firstly try the examples out in this chapter 2 Modify the StringBuffer example to repeatedly increase the size of the string At what point does the program fail i e how big is the string at the time it can t be inceased in size any more 3 Write a Java program to print out 7 1 e print out the character pi to the screen not 3 14 etc email an chiversO kcl ac uk O Ian D Chivers 6 Arrays in Java Where shall I begin your Majesty he asked Begin at the beginning the King said gravely and go on until you come to the end then stop Lewis Carroll Alice s Adventures in Wonderland Aims The aims of this chapter are to look at the basic array syntax in Java look at the associated control structure the for loop look at array element ordering in Java look forward to the use of some of the additional features of Java that enable us to make array handling more understandable and reliable Chapter 6 Arrays In Java 92 6 Arrays In Java In this chapter we will look at the basic features of Java that support arrays The first thing to know is that arrays start at 0 i e an array dimensioned to 12 has indices from O through 11 The second thing to know is that arrays are objects Consider the following example 6 1 Example 1 For people who have attended
204. ge changes and extends Java so that all IEEE 754 features can be expressed and so that new numeric types can be easily created Borneo allows either better hardware use than Java or nearly exact reproducibility while in all cases being predictable Summary Unlike other languages designed to support IEEE 754 features such as Modula 3 C9X and RealJava Borneo does not just add library functions to set and query the floating point state Borneo has scoped language declarations to control the rounding mode sticky flags and trapping status Lexical scoping permits more optimizations and makes reasoning about the program easier One major change to Java not directly related to floating point is Bor neo s addition of operator overloading Besides the ability to overload existing operators as in C Borneo also lets novel user defined operators be defined and overloaded Except for some new keywords Borneo is upwards compatible with Java Given a Java class P compiled to bytecode another Java class cannot determine whether P was compiled under Borneo semantics or Java semantics Borneo semantics disallow some floating point optimizations permitted in Java Also have a look at http math nist gov javanumerics reports jgfnwg 01 html 27 5 Bibliography Hauser J R Handling Floating Point Exceptions in Numeric Programs ACM Transaction on Programming Languages and Systems Vol 18 No 2 March 1996 Pages 139 174 The paper looks at a num
205. ge collector a file system drivers for disk diskette asynchronous and synchronous communication printer and a bit mapped display local network services support for texts and fonts a window subsystem a text editor the Oberon compiler Educational versions of the system are available from the ETH ftp server I d recommend 8Mb of memory and an 80486 with 1024 756 display I ve tried at home on a 20 MHz 80386 with 5 Mb of memory a bit slow Well worth a look at Programming in Oberon Reiser and Wirth is a good introductory text and combined with OOP in Oberon 2 Mossenbeck you have sufficient information to get started There is a lot of documentation that comes with the system and this can be printed The system integrates very well with both Windows on the PC and Apple macs Versions for other platforms are available If your are familiar with Pascal or Modula 2 then I d recommend Oberon very highly to see what OOP has to offer Very low cost in time effort and money 2 20 6 Ada 95 Whilst I do not have access yet to an Ada 95 compiler from what I ve read it looks a very good language The standard is available from a number of ftp servers and there is also a look at the changes from the original version to 95 available on the web A text I d recom mend is Programming in Ada 95 Barnes This is well written Ada 95 is the first language that has been standardised with OOP in mind If you want a job in the defence indus
206. ges Proc IFIP Congress 74 386 393 North Holland Amsterdam Wirth N The Programming Language Pascal Acta Informatica 1 35 63 1971 Wirth N Modula a language for modular multi programming Software Practice and Ex perience 7 3 35 1977 Wirth N Programming in Modula 2 Springer Verlag e The original definition of the language Essential reading for anyone considering programming in Modula 2 on a long term basis Wirth N Type Extensions ACM Trans on Prog Languages and Systems 10 2 April 1988 2004 214 Wirth N From Modula 2 to Oberon Software Practice and Experience 18 7 July 1988 661 670 Wirth N Gutknecht J Project Oberon The Design of an Operating System and Compiler Addison Wesley e Fascinating background to the development of Oberon Highly recommended for anyone involved in large scale program development not only in the areas of programming languages and operating systems but more generally 2 27 Problems What programming languages are available on the system you work with email ian chivers kcl ac uk Ian D Chivers 3 Introduction to Programming in Java Though this be madness yet there is method in t Shakespeare Plenty of practice he went on repeating all the time that Alice was getting him on his feet again plenty of practice The White Knight Through the Looking Glass and What Alice Found There Lewis Carroll Aims The aims of the chapter are to l
207. guages 42 and Object Oriented Programming Date C J A Guide to the SOL Standard Addison Wesley e Date has written extensively on the whole database field and this book looks at the SQL language itself As with many of Dates works quite easy to read Ap pendix F provides a useful SQL bibliography Deitel H M and Deital P J Java How to Program Prentice Hall e A very good introductory Java text One of the best currently available Highly recommended Dupee B A Study of Object Oriented Methods using Fortran 90 MSc Thesis e A look at OO methods in F90 rather than full blown OOP Flanagan D Java in a Nutshell O Reilly and Associates e One of the Nutshell series If you want one book on Java then this is the one I d recommend Four parts are introduction to Java programming with the Java api Java language reference and api quick reference Friedman L W Comparative Programming Languages Prentice Hall e I ve got this on order Geissman L B Separate Compilation in Modula 2 and the structure of the Modula 2 Com piler on the Personal Computer Lilith Dissertation 7286 ETH Zurich Jacobi C Code Generation and the Lilith Architecture Dissertation 7195 ETH Zurich e Fascinating background reading concerning Modula 2 and the Lilith architecture Goldberg A and Robson D Smalltalk 80 The language and its implementation Addison Wesley e Written by some of the Xerox PARC people who have been involved wi
208. hange in the current selection MenuDragMouseEvent email ian chivers kcl ac uk Ian D Chivers Chapter 13 Events 204 MenuDragMouseEvent is used to notify interested parties that the menu element has received a MouseEvent forwarded to it under drag conditions MenuEvent MenuEvent is used to notify interested parties that the menu which is the event source has been posted selected or canceled MenuKeyEvent MenuKeyEvent is used to notify interested parties that the menu element bshas received a KeyEvent forwarded to it in a menu tree MouseInputAdapter The adapter which receives mouse events and mouse motion events PopupMenuEvent PopupMenuEvent only contains the source of the event which is the JPoupMenu sending the event SwingPropertyChangeSupport This subclass of java beans PropertyChangeSupport is identical in functionality it sacrifices thread safety not a Swing concern for reduce memory consump tion which helps performance both big Swing concerns TableColumnModelEvent TableColumnModelEvent is used to notify listeners that a table column model has changed such as a column was added removed or moved TableModelEvent TableModelEvent is used to notify listeners that a table model has changed TreeExpansionEvent An event used to identify a single path in a tree TreeModelEvent Encapsulates information describing changes to a tree model and used to notify tree model listeners of the change Tr
209. hapter 11 Compiling with JDK1 2 2 generates a warning about size and stop Try running this exam ple on more than one platform if possible Also try running within a web browser as well as using the appletviewer 11 16Example 2 Bouncing Balls with integer arithmetic Note that the naming convention doesn t match the example numbering If I get time I will rename and renumber all examples However this involves quite a lot of work on more than one platform import java awt email ian chivers Q kcl ac uk O Ian D Chivers Chapter 11 Introduction to Graphics Programming 142 the thread is put It is worth experimenting with this as the applet will behave first example by using things to look at public class graphic03 extends java applet Applet implements Simple graphics example of a bouncing ball Things to look at are the amount of flicker and the amount of time that to sleep This is in milliseconds differently on different systems this example redoes th integer arithmetic throughout are the differences in the speed of the ball and also looking at varying the sleep time Runnable int x y deltax deltay int x1 300 int yl 300 Thread ball public void init setBackground Color white deltax 3 deltay 3 x int Math random x1 y int Math random yl1 public void start if ball 2null
210. he following are commonly available on the pc 640 480 standard vga 800 600 super vga 1024 768 you need at least a 15 inch monitor 1280 1024 just about ok with a 17 inch but I would consider 19 or 21 inch It is not worth considering the higher screen resolutions unless one has a 15 or 17 inch monitor The text is very difficult to read on smaller monitors 11 4 1 Interlaced vs non interlaced To give a stable display a computer screen must be refreshed within quite short times 1 e the picture must be redrawn completely 60 times a second With monitors with low scan rates it will often only be possible to support higher screen resolutions if the screen is inter laced I had a cheap 14 inch monitor at home and I drove it in 1024 768 mode but I could only do that by doing it in interlaced mode It flickered quite badly In the public rooms the pc s are all driven in 800 600 mode Very clear and legible Most people find little flicker above 70 Hz 11 5 Colour Models There are several colour models Some commnly used ones are RGB red green blue tends to be used with displays additive CMY cyan magenta yellow tends to be used with printers subtractive Ian D Chivers email ian chivers kcl ac uk 139 Introduction to Graphics Programming Chapter 11 If one needs faithful printed colour then one should use software that offers pantone colour support You would typically print out test sheets with the na
211. he two additional keywords are static and final The initial value looks a little strange Remember that real numbers are double by default in Java We thus have to cast the expression 9 46 10E12 to a float Note that we have to use brackets around the numeric expression as we are interested in casting the result of the whole expression public static void main String args Standard start of program float light minute email ian chivers Q kcl ac uk O Ian D Chivers Chapter 4 Arithmetic and Expressions in Java 70 float distance float elapse int minute int second Standard variable declarations light minute light year float 365 25 24 0 60 0 Assign value to light_minute Part of the expression looks a little odd at first We are doing the complete expression as double and then casting the result to float distance float 150 0 10E6 Calculate distance again cast from double to float elapse distance light_minute Simple assignment minute int elapse Assignment with cast second int elapse minute float 60 Assignment with cast Notice the additional brackets to force the cast of the whole expres sion System out print Light takes System out print minute System out print minutes System out print System out print second System out printin seconds Print out the answer The exam
212. ic we want it to be used The copy method is void it does not have a return type It is a subroutine or procedure in Fortran or Modula terminology It takes two arguments the source and destination file names These are of course of type String Lastly the copy method can throw an IOException We will have to provide an error han dler for this later in the code Let look now at the last part of the program class FileCopyException extends IOException public FileCopyException String msg super msg IOException is a built in Java class In this example we extend this class with our own class FileCopyException So when we want to throw an exception we will be throwing a FileCopyException error and control will pass to this error handler Our own FileCopyException procedure takes one argument of type String and then invokes the method within IOException The terms super and sub class are used to indicate where Ian D Chivers email ian chivers kcl ac uk 117 Exceptions Chapter 8 you are in a class hierarchy We will come back to this in more depth when we look for mally at class extension in a later chapter 8 8 Java Errors and Exceptions Java discriminates between errors and exceptions An error is treated as irrecoverable and an exception is something that can be handled by the code writer if they want Note that errors and exceptions can occur both within the interpreter whilst you code is run ning and in
213. ie d E at pet Eeoae 82 3 2 1 2 Sting Example 2 valueOt isa cha c seg aae 82 5 2 1 3 String Example 3 as above but no import statement sese 83 5 9 java lang String Buffer a r TAE EENT 83 5 3 1 String Butler Methods 2 creen lie Pe oce Ep Un eT ede ee e 84 5 3 1 1 StringBuffer Example 1 throwing an exception and catching 85 5 3512 StringBuffer Example 2 throwing an exception and splat ssss 87 D gt Relerencees uie e een ee each ede cose na ee ed desi sese Uu ie eae 87 5 5 EU DIGOGE cios iS otesoedicibec agg cs No ios nee ihe ita cce o Eel etu d elitists iip D 88 5 6 Slut aat 89 5 7 Problem Sesio eot erae tessuto ato nieta sata 89 6 Arrays In Vay a aiuto tired ei Dec it 92 6 1 Example d ee TA A A TAE ee el 92 6 2 Example 2 Variant on 1 using alternate syntax esee 93 6 3 Example 3 two dimensional AS oec a vetet is 94 6 4 Example 4 1 d array with real world 20 to 4 amp 20 seen 94 6 5 Bxample 2u array ALL AMSA OT o qa ica cass ad 95 6 6 Whole Array Manipulation uec irte ordeo est ta PR Nei See dois 95 6 7 SUMA e 96 6 8 Problerise lS xen Matai he ety sarc latte diii oue ducsdt lel od ctun cuoc EU co Sd iut 96 T Control SfEUCDUE S mucosidad ande ci 98 7 1 Compound Statement or Block isidro ani 98 diz r DAUERTE E a E R idas 98 1 3 A i E a a a a aa eel pea
214. in addPoin addPoin addPoin addPoin choot chor cf cF cere 2 O0 0 c c 0c c c cC n 12 C 4 4 3 r2 pi C2 C CQ C Q C C9 g setColor Color blue g drawPolygon octagon 11 22 6 Ovals g drawOval x y w h and g fillOval x y w h Left as an exercise olygon 11 22 7 Arcs g drawArc x y w h start end and g fillArc x y w h s e Left as an exercise 11 22 8 Colour Color The default colour model supported by Java is the RGB model R stands for red g for green and b for blue Each colour can have an integer value in the range O to 255 This gives 16 million colours Your monitor of course may not be able to display that number of colours It is an additive system There are the following predefined colours in Java Colour Color white Color black Color lightgray Color gray Color darkgray Color red Color green Color blue Color yellow Color magenta O Ian D Chivers 255 0 192 128 64 295 0 0 235 255 Red 255 0 192 128 64 0 255 255 Green 255 0 192 128 64 0 0 255 255 Blue email ian chivers Okcl ac uk 153 Introduction to Graphics Programming Chapter 11 Color cyan 0 255 255 Color pink 235 175 175 Color orange 255 200 0 The other supported colour model is the hsb model hue saturation brightness There are additional methods to support this model The
215. in double a Returns the arc sine of an angle in the range of pi 2 through pi 2 static double atan double a Returns the arc tangent of an angle in the range of pi 2 through pi 2 static double atan2 double a double b Converts rectangular coordinates b a to polar r theta static double ceil double a Returns the smallest closest to negative infinity double value that is not less than the argument and is equal to a mathematical in teger static double cos double a Returns the trigonometric cosine of an angle static double exp double a Returns the exponential number e i e 2 718 raised to the power of a double value static double floor double a Returns the largest closest to positive infinity dou ble value that is not greater than the argument and is equal to a mathematical in teger static double IEEEremainder double f1 double f2 Computes the remainder op eration on two arguments as prescribed by the IEEE 754 standard static double log double a Returns the natural logarithm base e of a double value static double max double a double b Returns the greater of two double values static float max float a float b Returns the greater of two float values static int max int a int b Returns the greater of two int values static long max long a long b Returns the greater of two long values static double min double a double b Returns the smaller of two double values email ian chivers kcl
216. ing a java byte code interpreter This interpreter can be a web browser that supports java or an interpreter that runs on whatever platform that you are us ing This means that if one develops java programs as applets that run on a web browser that the java byte codes are effectively platform independent The applets can run on any platform that has a java virtual machine built into the web browser This is probably the major reason for the take up of Java With the increasing importance of the web people require a way to develop portable applications You do not have to reimplement for each platform that you want to support Note also that java compiled code is small Another big plus for web based computing 3 2 Java Programs Java programs have access to the underlying computer system 3 3 Java Applets Java applets do not have access to the native machine on which the web browser runs 3 4 Hello World Java Program The following is a complete Java program class c0301 public static void main String args System out printin Hello world Java programs and applets comprise one or more classes In these notes we will use the convention of c for chapter dd for chapter number and xx for example within that chapter So this is the first example in chapter 03 Ian D Chivers email ian chivers kcl ac uk 49 An Introduction to Java Chapter 3 Within a class we have one or more procedures and data In Java termin
217. ing interface for data output public abstract void writeBoolean throws IOException public abstract void writeByte throws IOException public abstract void writeChar throws IOException public abstract void writeDouble throws IOException public abstract void writeFloat throws IOException public abstract void writeInt throws IOException public abstract void writeLine throws IOException public abstract void writeLong throws IOException public abstract void writeShort throws IOException public abstract void writeUTF throws IOException public abstract void writeUnsignedByte throws IOException public abstract void writeUnsignedShort throws IOException Ian D Chivers email ian chivers kcl ac uk 123 i o Chapter 9 9 5 java io DataOutputStream class Matching class for data output public final void writeBoolean throws IOException public final void writeByte throws IOException public final void writeChar throws IOException public final void writeDouble throws IOException public final void writeFloat throws IOException public final void writeInt throws IOException public final void writeLine throws IOException public final void writeLong throws IOException public final void writeShort throws IOException public final void writeUTF throws IOException public final void writeUnsignedByte throws IOException public final void writeUnsignedShort throws IOException Note that all of these m
218. ing new methods in existing classes extending existing classes and adding new classes and interfaces that don t affect the legacy APIs The Java 2D API functionality is delivered through an expanded graphics context Graphics2D To provide this extended graphics context while maintaining backward com patibility Graphics2D extends the Graphic s class from the JDK 1 1 release The usage model of the graphics context remains unchanged The AWT passes a graphics context to an AWT Component through the following methods paint paintAll update print printAll getGraphics A JDK 1 1 applet interprets the graphics context that s passed in as an instance of Graphics To gain access to the new features implemented in Graphics2D a Java 2D API compatible applet casts the graphics context to a Graphics2D object public void Paint Graphics g Graphics2D g2 Graphics2D g g2 setTransform t email ian chivers kcl ac uk Ian D Chivers Chapter 11 Introduction to Graphics Programming 170 Note that we still invoke paint with Graphics and switch to Graphics2D with an explicit cast To enable the development of platform independent applications the Java 2D API makes no assumptions about the resolution color space or color model of the target rendering de vice Nor does the Java 2D API assume any particular image file format Truly platform independent fonts are possible only when the fonts are built in provided as part of
219. ing the card layout mananger Font f new Font Arial Font PLAIN 20 Panel p new Panel public void setFont f init setLayout new Cardlayout add new Label QPR add new Label Arsenal add new Label Spurs add new Label Chelsea add new Label West Ham add new Label Crystal Palace public void start 12 13Putting it all togethor We will look at two examples on the College web server These are ones that are provided by Sun and are often included in third party Java compilers URLs are http www kcl ac uk kis support cit fortran java demo GraphLayout and http www kcl ac uk kis support cit fortran java demo GraphicsTest You run the them by clicking on the examplel html file We will not be doing anything more complex with this way of doing things as they have been superceded by later versions of the jdk 12 14Problems Try the examples out in this chapter Ian D Chivers email ian chivers kcl ac uk 13 Events For Madmen Only Hermann Hesse Steppenwolf Aims The aims of this chapter are to introduce some of the ideas involved in the use of events in Java This is an area where there have been major changes since the origi nal Java 1 0 x JDK Chapter 13 Events 198 13 Events Java supports windows programming and therefore has to offer facilities for handling events This is another area wh
220. int format esses nennen nenne 299 27 2 3 Two classes of extended floating point formats esee 300 27 2 4 Accuracy requirements ere pr esie ida 300 27 2 5 Base conversion i e when converting between decimal and binary floating point for Mats and VICE Versa 5 1 eite om t erp H SUELE PER GERE leida Dodge bad eee Ro ede oe teclas Libras 300 27 2 6 Exception handlinb 5 2 ac iHe e p Ste Geese sega dtp 300 27 2 7 Ro nding directions 2e lt e 300 27 2 8 Rounding ptrecisions oie eo tete e Re PER e Leve dah 300 LEN NE SUMING e n E 300 LP ML Pr dish pea axatuncesseibane acu snnenegasooen volaunts EE 301 2d Bibliography talas osdaeniguastaetaseatys 301 27 5 1 Web based SourceS rener iena e eiee adar a E E A aiaee eni 302 27 5 2 Hardware SQUICES conato ned e o pere lee a pee teet iR tds 303 27 5 3 Operating Syste S nata ero be ee tte ee Eie Leg Qe n as bee eeu tee pida 303 27 5 4 Java and IEEE 754 mene RE Rc dan pe Deere ag m Eee pe eode en 303 27 5 5 Cand IEEE 754 onde i etie ee em tere ete ries ads 303 28 Language Standardisation oomosss 306 28A SUNE US 306 1 Overview The first thing we do let s kill all the language lawyers Henry VI part II Aims The aims of the chapter are to provide a background to the organisation of the course Chapter 1 Overview 16 1 Overview 1 1 Aims The primary aim of the course is to provide a Java conversion course Some of the exam ple
221. ion call expr expr list sees 65 4 8 2 4 HE post increment EXPE A E A e reple te petenda 65 4 8 2 5 post decrement expr oocococcconnnonononnnnnnnoncnonoconoconnnnn nono eere enne nennen nete nnne 65 4 8 2 6 TE pre increment EF eXpE here te Ieri eee art a en de eed 65 4 8 2 7 pre decrement expr niini iiia ine ia iaa enne nennen trennen 65 4 8 2 8 complement exp 2 ette i te teri egeo repetere eee E En gone rne Rex edP Pee da 65 4 8 2 9 BEES ET 65 4 8 2 10 n ry min s dU TREE EN 65 Contents 5 4 8 2 11 unary plus F expri ur ed ta tede ia eig aa 66 4 8 2 12 new create NEW type xem eee tete eoo re togata eerte onere ree nota te e PES IRR nues 66 4 8 2 13 cast Cy PE RR 66 4 8 2 14 multiply expt eXpE 2 1 eenn net recae petes tete tede tddi 66 4 8 2 15 7 divide expt expt aid eene ea reed eh del aad ee hence 66 4 8 2 16 modulo or remainder expr CXL ee eee eseesecseceseceseceseeceeceaeceeeseeeeeeesaessaees 66 4 8 2 17 plus exp A E 66 4 8 2 18 MINUS expt ceXxptE 2 dubia epe por eei eite tenis peer teste oe be das 66 4 8 2 19 lt lt shift lett expr lt lt expt eiim ettet eet terti Pec tee 66 4 8 2 20 gt gt shift right expr 5 expt 2e Ree ate eg HERE eie s 66 4 8 2 21 gt gt gt shift right expr gt gt gt expr renee de eter cete ttes 66 4 8 2 22 lt less than expr expr n entree perte Re D egere ere pe eei enero ee tne 6
222. ion of VisualAge Professional Edition 3 0 is also available Typically we are looking at 80 100 Mb I don t recommend downloading this at home over the telephone line I have a copy of Nilsson D R Jakab P M Developing JavaBeans Using VisualAge for Java Wiley and the CD has the following on it VisualAge for Java Entry Edition 1 0 VisualAge for Java Patch Set 1 Sun Java Developers Toolkit 1 1 5 Sun Java Runtime Environment 1 1 5 Take care when buying a book with a CD to get hold of as recent a version as you can 19 3 Documentation IBM provide a lot of documentation in Adobe Acrobat Portable Document Format Acrobat readers are free over the web The following url http www kcl ac uk www adoacr html provides more information 19 3 1 IDE Basics Concepts and Tasks 34 pages How to use the integrated development environment Print this guide if you can Have a quick browse to get a feel for some of the things you will need to know to develop a Java applet 19 3 2 Getting Started 144 pages General introduction to using the basic features of Visual Age for Java Print this guide if you can I would work through the following chapters Chapter 2 The Basics Chapter 3 Building your first applet at least I would also work through Chapter 4 Adding State Checking to your Applet Chapter 5 Enhancing the To Do List Program Chapter 6 What Else can you do with the Visual Composition Editor Chapter 6 takes you th
223. itecture you should consider if you re developing for the Java platform JavaBeans component architecture extends Write Once Run Anywhere TM capa bility to reusable component evelopment In fact the JavaBeans architecture takes interoperability a major step forward your code runs on every OS and also within any application environment A beans developer secures a future in the emerging network software market without losing customers that use proprietary platforms because JavaBeans components interoperate with ActiveX JavaBeans architecture connects via bridges into other component models such as ActiveX Software com ponents that use JavaBeans APIs are thus portable to containers including Internet Explorer Visual Basic Microsoft Word Lotus Notes and others The JavaBeans specification which was completed ahead of schedule defines a set of standard component software APIs for the Java platform The specification was developed by Sun with a number of leading industry partners and was then re fined based on broad general input from developers customers and end users dur ing a public review period Better than apple pie mum etc O lan D Chivers email ian chivers Okcl ac uk 229 JavaBeans Chapter 15 Maurus T AMITTIT Nasir drena Ese ox www kt Foma Dabug lun Query Cggran Doo kH wndoe tdo EXETER E WIRE oo I E E E 100 Pe Fraa amero If you have used Visual Basic or Delphi you will be familiar with the way i
224. lass URLConnection is the superclass of all classes that rep resent a communications link between the application and a URL O lan D Chivers email ian chivers Okcl ac uk 261 Simple Networking Chapter 21 URLDecoder The class contains a utility method for converting from a MIME format called x www form urlencoded to a String URLEncoder The class contains a utility method for converting a String into a MIME for mat called x www form urlencoded format URLStreamHandler The abstract class URLStreamHandler is the common superclass for all stream protocol handlers 21 1 3 Exception Summary BindException Signals that an error occurred while attempting to bind a socket to a local address and port ConnectException Signals that an error occurred while attempting to connect a socket to a remote address and port MalformedURLException Thrown to indicate that a malformed URL has occurred NoRouteToHostException Signals that an error occurred while attempting to connect a socket to a remote address and port ProtocolException Thrown to indicate that there is an error in the underlying protocol such as a TCP error SocketException Thrown to indicate that there is an error in the underlying protocol such as a TCP error UnknownHostException Thrown to indicate that the IP address of a host could not be de termined UnknownServiceException Thrown to indicate that an unknown service exception has oc curred 21 2 Examples
225. lasses and can assist you in adding methods and member variables The Text editor supports IntelliSense features such as Statement Completion to help you write code Use the WFC data controls and components toa ccess data from your form WFC uses ADO to retrieve data and perform simple data binding 18 5 2 Building and Running Your Application When you build your application any compilation errors appear in the Task List After you correct these errors you can run your application from within the development environ ment Ian D Chivers email ian chivers kcl ac uk 245 Microsoft Visual J Chapter 18 18 5 3 Debugging Your Application Although your application may compile without errors it may not run as expected The pro cess of finding and fixing logic and run time errors is known as debugging Using theintegrated debugger you can set breakpoints to step through your code one statement at a time and view the values of variables and properties 18 5 4 Packaging Your Application When you have finished modifying and debugging your application you canpackage it to into an exe or cab file and deploy it to the Web 18 6 Getting Going Either follow the steps provided or get hold of the Cowell book 18 7 Bibliography Cowell J Essential Visual J 6 0 Fast Springer Quick introduction Walks you through the use of the development environment and worth it for that alone No coverage of Swing of course email ian chiver
226. ler The abstract class ContentHandler is the superclass of all classes that read an Object from a URLConnection DatagramPacket This class represents a datagram packet DatagramSocket This class represents a socket for sending and receiving datagram packets DatagramSocketImpl Abstract datagram and multicast socket implementation base class HttpURLConnection A URLConnection with support for HTTP specific features InetAddress This class represents an Internet Protocol IP address JarURLConnection A URL Connection to a Java ARchive JAR file or an entry in a JAR file MulticastSocket The multicast datagram socket class is useful for sending and receiving IP multicast packets NetPermission This class is for various network permissions PasswordAuthentication The class PasswordAuthentication is a data holder that is used by Authenticator ServerSocket This class implements server sockets Socket This class implements client sockets also called just sockets SocketImpl The abstract class SocketImpl is a common superclass of all classes that actu ally implement sockets SocketPermission This class represents access to a network via sockets URL Class URL represents a Uniform Resource Locator a pointer to a resource on the World Wide Web URLClassLoader This class loader is used to load classes and resources from a search path of URLs referring to both JAR files and directories URLConnection The abstract c
227. level of sophistication is to provide and integrated environment Terms use in clude workbench ide integrated development environment Ian D Chivers email ian chivers kcl ac uk 237 Overview of Development Environments Chapter 16 and they vary quite considerably from the very straighforward to extremely complex The Salford Fortran 90 and 95 compilers come with a simple environment called Plato The Elles ola ond ee dat Salford Fortran Development Environment Compaq Fortran compiler works within Microsoft Developer Studio which is a very com Compaq visasi Port n Works Compaq Fortran Development Environment email ian chivers kcl ac uk Ian D Chivers Chapter 16 Overview of Development Environments 238 plex environment that takes some time to get on top off The following screen shots show these 16 3 Visual Development Tools The next level of sophisticaion comes with visual development tools Microsoft Visual Ba sic s a very good example of what can be achieved Visual Basic Development Environment These are normaly the most costly but they do offer considerable benefits eventually in terms of speed of development Putting a visual interace onto a program is obviously going to be much easier using visual development tools rather than raw programming 16 4 Problems O lan D Chivers email ian chivers Okcl ac uk 17 Forte for Java Make it as simple as possible but no sim
228. ling mechanism By now the primitive nature of the AWT Abstract Windows Toolkit had became apparent 1997 saw the introduction of the Java Foundation Classes which supersedes and includes AWT These new components were called Swing JavaBeans came into existence JavaBeans is a component architecture for the Java platform We will look into this in much greater depth in later chapters 1 4 3 1 2 x aka Java 2 Sun rebadged Java in December 1998 when Java 1 2 became Java 2 Be very careful when buying books on Java You need to ensure that the books that you buy address the version we will be using 1 5 Development platforms The majority of the examples have been tested using the Sun development kits JDKs on both Solaris and Windows environments These are both free They may be downloaded and installed on your own machine if you have one The first JDK used was 1 0 2 I used 1 2 2 for the 2000 2001 course and will be using JDK 1 3 in 2001 2002 You should also get the documentation that Sun provide This is installed on the College web server There are links from the Java pages If you program at home I would download it and install it The following is the sun home page http www java sun com The following has details of the jdk http java sun com products jdk 1 x that is available for download I have also used IBM Visual Age for Java It exists in three editions Entry Edition free Professional 65 UK pounds Ente
229. lity 26 Look and feel 27 Swing utilities 28 Swing under the hood Nilsson D R Jakab P M Developing JavaBeans Using VisualA ge for Java Wiley I have had a look at JavaBeans and decided that a graphical front end would proba bly be a good idea This meant looking at the issue from proprietary software As IBM make their version available for download I chose a book that was specifically about VisualAge for Java Comes with 1 1 5 on a CD Release 2 is available for download Winder R Roberts G Developing Java Software Wiley If you don t have a formal background in programming algorithms and data struc tures object oriented programming then I would suggest that you have a look at this book Hunt J Java and Object Orientation Springer If you want an introduction to object oriented programming take a look at this one JDK 1 2 2 On line documentation This is available on the college web server Just follow the links You can also download and install to your own machine This is the source of technical informa tion on Java Arnold K Gosling J The Java Programming language Addison Wesley Written by two of the Java team I normally try to get hold of a book by people who have been behind the design of a programming language when trying to learn it This one is very disappointing Gosling Yellin and the Java Team The Java API Volume 1 Core Packages Addison Wes ley Paper definition of the application programming interface Also
230. lope to be ex ceeded before friction is overcome and so on Unfortunately most of these sorts of calcula tions become rather complex and not really appropriate here The following problem tries to restrict the range of calculation whilst illustrating the possibilities of decision making 4 If a cubic equation is expressed as Z a2z2 az a0 0 and we let q a1 3 a2 a2 9 and r a1 a2 3a0 6 a2 a2 a2 27 we can determine the nature of the roots as follows q gt 0 one real root and a pair of complex q r 0 all roots real and at least two equal q lt 0 all roots real Incorporate this into a suitable program to determine the nature of the roots of a cubic from suitable input 5 The form of breaking waves on beaches is a continuum but for convenience we com monly recognise three major types surging plunging and spilling These may be classified empirically by reference to the wave period T seconds the breaker wave height Hb metres and the beach slope m These three variables are combined into a single parame ter B where B Hy gmT g is the gravitational constant 981 cm sec If B is less than 003 the breakers are surg ing if B is greater than 0 068 they are spilling and between these values plunging break ers are observed i On the east coast of New Zealand the normal pattern of waves is swell waves with wave heights of 1 to 2 metres and wave periods of 10 to 15 seconds During st
231. loped at the European Particle Physics Laboratory CERN in Geneva to enable high energy physics researchers to work collaboratively on online documentation it soon became apparent that the system could be useful to a broader section of the population and the software became publicly available in 1991 Here is the html file associated with this simple applet lt html gt lt head gt lt title Hello World gt lt title gt lt head gt lt body gt applet code c030la class width 300 height 100 gt lt applet gt lt body gt lt html gt This simple html file uses a number of tags lt html gt an instruction to the web browser that this is an html document lt head gt the heading lt title gt the title of the document which appears somewhere within the browser Also appears in a booklist lt body gt the main body of the document lt applet gt used to signify a java applet More infomation can be found on html on the College web server There are links to some very good coverages of html You need to have a good working knowledge of html if you are interested in Java applets They key tag in the above is the applet tag Let us look at this in more depth email ian chivers kcl ac uk Ian D Chivers Chapter 3 An Introduction to Java 52 code c030la class width 300 height 100 The actual applet to run is called c0301a class When we compile our java programs we end up if there are no erro
232. loper java sun com developer onlineTraining index html Links to Java Beans training material http developer java sun com developer onlineTraining Beans EJBTutorial index html Enterprise JavaBeansTM Tutorial Building Your First Stateless Session Bean 15 6 Problems Try converting some of your existing Java programs to a bean Be prepared to devote some time to this email ian chivers kcl ac uk Ian D Chivers 16 Overview of Development Environments The good teacher is a guide who helps others dispense with his services R S Peters Ethics and Education Aims The aims of this chapter are look at some of the development environments available both free and commercial Chapter 16 Overview of Development Environments 236 16 Overview of Development Environments In this chapter we will look at the various options open to us for Java programming 16 1 Edit Compile and Run Sun make the development kits freely available for a numer of platforms including Solaris and Windows The development kit comprises the compiler the interpreter or Java Virtual machine and this is one of the reasons that people have shown such an interest in Java as you can try things out for zero cost in monetary terms We then use whatever native editor we like and are involved in the traditional programming cycle of edit compile run that we see with the Fortran and C families of languages 16 2 Workbench or IDE The next
233. me number of each colour and then use that to provide the on screen colour This may not match very closely the printed colour 11 6 Scamning Take care when scanning Take a 5 7 inch colour photo with 300 dpi resolution 5300 7300 35 9 10 000 3 150 000 11 7 Coordinate spaces The java coordinate space is screen based in java awt 1 0 x release and the top left is 0 0 There is also the concept of the problem coordinate space We then need to map between the two 11 8 Fonts There is a limited choice of fonts with the early versions of the JDK and but we can use them with a range of settings Things have changed considerably with later versions of the JDK 11 9 Aliasing and Antialiasing With simple raster plottng we get jagged edges or staircasing Naturally enough the term used to get rid of aliasing is antialiasing We get better quality images if we use antialiasing techniques Later versions of Java supported antialiasing See Foley et al for a coverage of this area 11 10Device context A concepts that is very useful in the graphics and windows programming area is that of a device context All drawing can be done to a device context and this might be virtual or physical e g the screen or a printer In Java we use the Graphics object as our device con text You have seen this throughout the examples already We will look at this area in more depth in this chapter 11 11 Clipping Clipping refers to the way in which a gr
234. method All rendering operations modify only pixels which lie within the area bounded by the current clip which is specified by a Shape in user space and is controlled by the pro gram using the Graphics object This user clip is transformed into device space and com bined with the device clip which is defined by the visibility of windows and device extents The combination of the user clip and device clip defines the composite clip which deter mines the final clipping region The user clip cannot be modified by the rendering system to reflect the resulting composite clip The user clip can only be changed through the setClip or clipRect methods All drawing or writing is done in bsthe current color using the current paint mode and in the current font 11 23 5 1 Constructor Summary Graphics Constructs a new Graphics object 11 23 5 2 Method Summary abstract void clearRect int x int y int width int height Clears the specified rectangle by filling it with the background color of the cur rent drawing surface abstract void clipRect int x int y int width int height Intersects the current clip with the specified rectangle abstract void copyArea int x int y int width int height int dx int dy Copies an area of the component by a distance specified by dx and dy abstract Graphics create Creates a new Graphics object that is a copy of this Graphics object Graphics create int x int y int width int height Creates a new Gr
235. ming Chapter 11 For example through the Graphics class you can draw rectangles ovals and polygons Graphics2D enhances the concept of geometric rendering by providing a mechanism for rendering virtually any geometric shape Similarly with the Java 2D API you can draw styled lines of any width and fill geometric shapes with virtually any texture 11 29 2 Rendering Model The basic graphics rendering model has not changed with the addition of the Java 2D APIs To render a graphic you set up the graphics context and invoke a rendering method on the Graphics object The Java 2D API class Graphics2D extends Graphics to support more graphics attributes and provide new rendering methods The Java 2D API automatically compensates for differences in rendering devices and pro vides a uniform rendering model across different types of devices At the application level the rendering process is the same whether the target rendering device is a display or a printer 11 29 3 Backward Compatibility and Platform Independence The Java 2DTM API maintains backward compatibility with JDK 1 1 software It is also architected so that applications can maintain platform independence To ensure backward compatibility the functionality of existing JDK graphics and imaging classes and interfaces was maintained Existing features were not removed and no package designations were changed for existing classes The Java 2D API enhances the functionality of the AWT by implement
236. ming Languages 38 and Object Oriented Programming We can now add another shape e g circle and still have things work without recompiling the old code We just compile the new move and draw procedures and link them in The method resolution is handled by dynamic binding We will look into this in greater depth later in the course 2 24 Other Developments The chapter rounds off with a look at recent developments that have taken place and that apply to one or more programming languages in some cases 2 24 1 Development Environments The traditional working practice for program development involves the following steps edit compile link run debug in a loop This method has the advantage of working on most hardware and software plat forms The major drawback is learning several ways of doing exactly the same thing as we move from platform to platform and from one language to another How many editors do you know how to use There have also been developments to provide an integrated environment for program de velopment These environments started out as workbenches providing simple access to the editor compiler linker etc through simple key strokes and the mouse They have grown very sophisticated 2 24 2 Graphical Development Tools There has also been the development of a visual interface to programming Increasingly people want easy to use software that almost by definition has a wndows based interface Microsoft Visual Basic provide
237. mportant happens in the life of a rowset like when a column value changes 22 7 Examples Deitel provides three examples You will need to register the Access database with the ODCB manager which is in the control panel They are in chapter 18 You will need to download all of the files and try them out on a pc Register them as a User Data Source Name Choose the Access driver Look carefully at the Deitel source Yoy need to ensure that you register the database with the same names as those used in the Java source You need a basic understanding of SQL and the relational model I ve provided references at the end of this chapter I have Access installed and used this to look at the databases provided This enables to see much more about the databases concerned Note that 22 8 Summary If you have Microsoft Visual J then you can try out jdbc using this If you are going to try out anything original then you will need Access to create your own databases Various versions of Microsoft Office include Access 22 9 Bibliography Cannen S Otten G SOL The Standard Handbook McGraw Hill This is a very good reference text to the SQL standard Date C An Introduction to Database Systems Addison Wesley One of the most prolific writers about database systems Pratt P J A Guide to SQL Boyd and Fraser Very good gentle introduction with clear examples Rbase Technologies Inc Rbase 2000 Release 6 5 Rbase Technologies Inc email ian
238. n 23 1 1 4 Incorrect example link The Java Server Development kit documentation home page is f jdk1 2 2 jsdk2 1 webpages index html The servlet example link is incorrect Try f jdk1 2 2 jsdk2 1 examples servlets index html instead The examples links don t work 23 1 1 5 Complete source code The source code listed is incomplete The complete code is in F jdk1 2 2 jsdk2 1 examples WEB INF servlets and so are the class files Don t forget to copy them to F jdk1 2 2 jsdk2 1 webpages WEB INF servlets HTML files to run the examples The html files do not run the servlets Example html files are not included 23 1 1 6 Calling Servlets From a Browser The URL for a servlet has the following general form where servlet name corresponds to the name you have given your servlet http machine name port servlet servlet name The following http localhost 8080 servlet HTTPGetServlet runs the first Deitel Java servlet example Servlet URLs can contain queries such as for HTTP GET requests For example the servlet that delivers details about a particuar book takes the stock number of the book as a query The servlet s name is bookdetails the URL for the servlet to GET and display all the infor mation about the bookstore s featured book is http localhost 8080 servlet bookdetails gt bookId 203 email ian chivers kcl ac uk Ian D Chivers Chapter 23 Servlets 280 23 1 1 7 Calling Servlets from an HTML page The follo
239. n seconds So the recommendation would seem to be to do all real arithmetic as double rather than have to cast all the time or append all variables with f If your program is heavy on numeric computation would you be using Java anyway 4 10 Char Characters are Unicode based in Java Given the large number of natural languages in the world and the requirements of the publishing world several companies got togthor and formed Unicode Inc a non profit making consortium to draw up a standard for international character sets ISO was tackling the same probelm and the outcome was the Unicode Stan dard As Unicode is 16 bit based it can handle 65 536 distinct characters which is enough for most if not all languages in use today plus a number of older or arcane languages e g Egyptian hieroglyphs Note that not all computer systems can necessarily handle the display of the full Unicode character set The bibliography contains some pointers to sources of information regarding Unicode I ve also printed out the following ASCII character set 7 bit ISO Latin 1 8 bit email ian chivers kcl ac uk Ian D Chivers Chapter 4 Arithmetic and Expressions in Java 72 DOS character set code pages 437 and 850 Windows character set Apple character set Unicode Now you have some idea why the interchange of computer information from one system to another can be fraught with problems 4 11 Boolean This is the last primitive d
240. n e System out printin Exceptions raised e In this example we are interested in doing i o In the previous program and applet we only did output We first import from java io to make available in shortened name form the vari ous facilities we need The next thing is the name of the class c0302 Remember java is case sensitive and the file name must match the class name We then have the standard statement for a java program email ian chivers kcl ac uk Ian D Chivers Chapter 3 An Introduction to Java 54 public static void main String args where main is made public static and returns a void type We have the standard arguments to main which are the argumnets to the program when it is executed returned as a String Let us now look at each statement in turn try Mechanisms for handling execution errors in a programming language are to be found in most programming langauges Java supports exception handling This facility is also to be found in C Modula 2 and Ada It is a significant improvement over the facilities pro vided in older languages If you are doing i o you have to include the code doing the i o in an exception handler So the try statment indicates the start of an exception handling block InputStream i System in You should be familiar from your programming background with the the concept of a vari able being of a particular data type and having a
241. n initial value So the above means that the variable i is of type InputStream and has an initial value of System in DatalnputStream in new DatalnputStream i This statement is similar to the above but adds one very important extension Java is an ob ject oriented language and objects have to be created The in object is of type DataInputStream and is created by the New DataInputStream i statement Objects are cre ated using new String Line Line is a variable of type String In fact String is an object in Java terminology and is not a fundamental type like integer or float System out printin Type in a line of text This statement causes the text string Type in a line of text to appear on the screen Line in readLine This statement reads in a line of text from the keyboard System out println Line This statement echos the line back to the screen catch IOException e This is the second part of the execution handling syntax Within the above block if an error occurs control passes to this statement and the following statement is executed System out printin Exceptions raised e In the event of an error the above message appears on the screen If we compare the above to similar programs in other more conventional programming lan guages the additional syntax looks very off putting Text i o in Basic C C Fortran For tran 90 Pascal or Modula 2 is much simpler However there ar
242. n paper for more information Lecture Notes on the Status of IEEE 754 27 3 Resum The above has provided a quick tour on IEEE 754 Ian D Chivers email ian chivers kcl ac uk 301 IEEE Arithmetic Chapter 27 27 4 ematics This is the best place to start http www cs berkeley edu darcy Borneo Abstract The design of Java relies heavily on experiences with programming languages past Major Java features including garbage collection object oriented programming and strong static type checking have all proved their worth over many years However Java breaks with tra dition in its floating point support instead of accepting whatever floating point format a machine might provide Java mandates use of the nearly ubiquitous IEEE Standard for Bi nary Floating Point Arithmetic IEEE 754 1985 Unfortunately Java s specification creates several problems for numerical computation Only a proper subset of IEEE 754 s required features are supported by Java useful IEEE 754 features are either explicitly forbidden or omitted from the Java specification Java does not allow use of the IEEE 754 recommended double extended format on the x86 Using the double extended format often protects simple numerical formulas from floating point anomalies Strict adherence to Java s floating point semantics leads to significant performance penalties on popular architectures including both the x86 and PowerPC To address these problems the Borneo langua
243. n which you can develop a program using a visual interface Look at the screen shot on the next page when reading the following With Visual Basic you drag and drop tools from the toolbar on the left and drop them onto the form in the middle You then alter the state of the object by us ing the propertires displayed on the right hand side This process is similar in all visual de velopment environments just the words and phrases change This is called visual development You don t actually have to write any code or so the claims go JavaBeans in conjunction with java awt dnd opens up this possibility with Java To do this properly you obviously need a graphical work environment We have been com piling from the unix or dos prompt so far I recommend getting hold of IBM Visual Age for Java and installing that The entry level version is free of charge I would also recommmend getting hold of the BeanBox Development Kit This enables you to test out your beans The url is given later in this chapter Java Beans will obviously vary in functionality but will have one or more of the following attributes Introspection looking inside and finding out how a bean works Customization how to alter the appearance and behavior of a bean Event handling events they can handle and events they generate Properties beans can be programmed and customised Persistence saving state information e g saving a word processing document email ian
244. nd develop our applet email ian chivers kcl ac uk Ian D Chivers Chapter 19 IBM VisualA ge for Java 252 The composition editor provides with access to four sets of beans These are swing awt other available and under available we have IBM Data Access Beans Select and DB Navigator Domino Java Class Library 4 6 1 Sun BDK Examples 1 0 IBM Domino Examples 2 0 Sun JDK Examples 1 1 6 Sun JFC Examples 1 0 2 IBM Java Examples 2 0 19 7 Summary Follow the instructions in the two documents and be patient It takes a while to get used to working in this new way The key feature is the way that everything is based around beans This is a major step forward when developing professional Java applets The learning curve 1s steep but your productivity will increase O lan D Chivers email ian chivers Okcl ac uk 20 Multimedia Aims The aims of this chapter are to provide a brief coverage of standardisation efforts imple mentation differences and future developments Chapter 20 Multimedia 254 20 Multimedia For more general capabilities you will need to download the Sun Java Media Framework Visit http java sun com products java media Jjmf There are verisons for Windows and Solaris The JavaTM Media Framework JMF is an application programming interface API for incorporating time based media into Java applications and applets The JMF 1 0 API the Java Media Player API enabled programmers to develop Java programs th
245. nere A ete eene eda 208 13 67 cing or S 208 Sede SUMMA V Lo centu qom modit stisseaboam di lmao cilc ohase do euet EAD ECT r der 212 138 Problems ia ii is 212 TAS pyar E EE E EO OCN 214 o AN 214 14 2 AWBabdo T need 5 esce deserto cones ordettaal etate oras ei getto Deal epe des ee vs Rea deb sashes 214 e A eee tou O RE EOD OmU 215 14 3 1 Po O EDD 215 14 3 2 JAVARIS WING accionada Pie e beris pic rt ee FUE Ie ERE P EO DE regiae 215 14 3 3 Javax swing border 0 0 endete nl esee externe onte ea e dee Dad 215 14 3 4 javax swing colorchioo8et 5 erc re eere ERE Ee Ere ERE DULL Dee 215 14 3 5 SS ES 215 14 3 6 Javax swing TIECHOOSEN ssccscseccake sce irte terc racer obere ee EE odds cotos EO PEE epo reas 215 14 3 7 JA VAR WINE pending et elec at e eese e Pe rede eed Meios desea 215 14 3 8 Javax swing plaf eet rere en ed ees nei eon bere eee T eR e 215 14 3 9 Javax s Wing talonario aiii 215 14 3 10 JAVAR SWINGER ioeina P 215 14 3 11 Jayax sWing text htmh nnne a aie ein en in eee 215 14 3 12 EA DEA 215 14 3 13 EA A A re Dep irre tete reste gre eie AET E E TN 215 14 4 Enter Microsoft Stage Left odisea es etase tote ct tn vxo ene rtr aaa sntssoaatanustaccoacsceans 215 14 3 Pluggable Look and Eel ascen asses a as 216 14 6 Lightweight COompotlellEs a beali eodd usa a va dee aC Y 216 14 7 Model View Controller MVC Architecture coooccccconoccccnononnonnnononononnnnnnnnnnnnnnos 216
246. ng processing languages SQL is the database language and Prolog is a logic based language 2 26 Bibliography Adobe Systems Incorporated Postscript Language Tutorial and Cookbook Addison Wes ley Adobe Systems Incorporated Postscript Language Reference Manual Addison Wesley Adobe System Incorporated Postscript Language Program Design Addison Wesley e The three books provide a comprehensive coverage of the facilities and capabili ties of Postscript ACM SIG PLAN History of Programming Languages Conference HOPL II ACM Press e One of the best sources of information on programming language developments from an historical perspective The is coverage of Ada Algol 68 C C CLU Concurrent Pascal Formac Forth Icon Lisp Pascal Prolog Smalltalk and Sim ulation Languages by the people involved in the original design and or imple mentation Very highly recommended This is the second in the HOPL series and the first was edited by Wexelblat Details are given later Adams Brainerd Martin Smith Wagener Fortran 90 Handbook Complete ANSI ISO Ref erence McGraw Hill e A complete coverage of the language As with the Metcalf and Reid book some of the authors were on the X3J3 committee Expensive but very thorough Annals of the History of Computing Special Issue Fortran s 25 Anniversary ACM publi cation e Very interesting comments some anecdotal about the early work on Fortran Arnold K Gosling J The Java
247. nk POINTER Next END TYPE Link TYPE Link POINTER Root Current INTEGER IO Stat Number 0 ALLOCATE Root READ UNIT FMT 10 ADVANCE NO amp 10 FORMAT A1 IOSTAT IO Stat Number Root C print io stat number F IO Stat Number 1 THEN NULLIFY Root Next ELSE ALLOCATE Root Next ENDIF print At start of input DO WHILE Current Root DO WHILE ASSOCIATED Current Next Current Current Next READ UNIT print io s EMT 10 ADVANCE NO amp IOSTAT IO Stat Number Current C tat number F IO Stat Number 1 THEN NULLIFY Current Next ELSE ALLOCATE Current Next ENDIF END DO email ian chivers kcl ac uk Ian D Chivers Chapter 8 Exceptions 110 print At end of input DO WHILE print At start of output DO WHILE Current Root DO WHILE ASSOCIATED Current Next PRINT Current C Current Current Next END DO print At end of output DO WHILE END PROGRAM C20_01 d 8 3 Linked List C old C syntax include lt iostream h gt include lt stdio h gt include lt stdlib h gt struct link char c struct link next int main char c struct link first NULL Start of list struct link current End of list Pd struct link ptr
248. nsional arrays The following looks at a two dimensional array problem in Java class c0603 public static void main String args int latitude longitude float height new float 5 5 for latitude 0 latitude lt 5 latitude for longitude 0 longitude lt 5 longitude height longitude latitude latitude longitude System out printin height longitude latitude float height new float 5 5 The syntax for a 2 d array is a simple extension of the syntax for a 1 d array Things are now getting a little away from our original real world way of looking at prob lems We now have 0 4 everywhere where the real world says 1 5 6 4 Example 4 1 d array with real world 20 to 20 Now consider a simple physics example where in the real world voltage goes from 20 to 20 class c0604 public static void main String args int voltage float current new float 41 float resistance float 100 0 for voltage 0 voltage lt 40 voltage current voltage voltage 20 resistance System out printin current voltage The solution to the problem in a programming language is now quite removed from the original problem 20 through 20 has become 0 through 40 We are now having to do a few mental gymnastics to understand what is going on Ian D Chivers email ian chivers kcl ac uk 95 Arrays In Java Chapter 6 The real world Java 20 0
249. nstead of the JApplet itself The contentPane will always be non null Attempting to set it to null will cause the JApplet to throw an exception The default contentPane will have a BorderLayout man ager set on it 14 14Swing Containers and JComponent JComponent is the base class for the Swing components JComponent provides A pluggable look and feel I amp f that can be specified by the programmer or optionally selected by the user at runtime Components that are designed to be combined and extended in order to create custom components Comprehensive keystroke handling that works with nested components Action objects for single point control of program actions initiated by multiple components A border property that implicitly defines the component s insets The ability to set the preferred minimim and maximum size for a component Tool Tips short descriptions that pop up when the cursor lingers over a com ponent Autoscrolling automatic scrolling in a list table or tree that occurs when the user is dragging the mouse Simple easy dialog construction using static methods in the JOptionPane class that let you display information and query the user Slow motion graphics rendering using debugGraphics so you can see what is be ing displayed on screen and whether or not it is being overwritten Support for Accessibility Support for international Localization The following are sub classes AbstractButt
250. nt class represents fonts FontMetrics The FontMetrics class defines a font metrics object which encapsulates informa tion about the rendering of a particular font on a particular screen Frame A Frame is a top level window with a title and a border GradientPaint The GradientPaint class provides a way to fill a Shape with a linear color gradi ent pattern Graphics The Graphics class is the abstract base class for all graphics contexts that allow an application to draw onto components that are realized on various devices as well as onto off screen images Graphics2D email ian chivers Q kcl ac uk O Ian D Chivers Chapter 11 Introduction to Graphics Programming 158 This Graphics2D class extends the Graphics class to provide more sophisticated control over geometry coordinate transformations color management and text layout GraphicsConfigTemplate The GraphicsConfigTemplate class is used to obtain a valid GraphicsConfiguration GraphicsConfiguration The GraphicsConfiguration class describes the characteristics of a graphics desti nation such as a printer or monitor GraphicsDevice The GraphicsDevice class describes the graphics devices that might be available in a particular graphics environment GraphicsEnvironment The GraphicsEnvironment class describes the collection of GraphicsDevice ob jects and Font objects available to a Java tm application on a particular plat form GridBagConstraints The GridBagConstrai
251. ntent for the page Additionally the application logic can reside in server based re sources e g JavaBeans that the page accesses with these tags and scriptlets Any and all formatting HTML or XML tags are passed directly back to the response page By separat ing the page logic from its design and display and supporting a reusable component based design JSP technology makes it fast and easy if you believe that you ll believe anything to build web based applications 24 1 Bibliography 24 1 1 JSP Visit http java sun com products jsp Also have a look at http www serverpages com Java_Server_Pages 24 1 2 HTML Visit http members aol com htmlguru or just try putting in html to AskJeeves 24 13 XML Visit http www xml org and http www xml org xmlorg_resources whitepapers shtml O lan D Chivers email ian chivers Okcl ac uk 25 Package java util Aims The aims of this chapter are to provide a coverage of the package java util Chapter 25 Package java util 286 25 Package java util This chapter looks at some of the the java util package It should be apparent by now that a working knowledge of the class library is essential for a good understanding of any object oriented language 25 1 Package java util Contains the collections framework legacy collection classes event model date and time facilities internationalization and miscellaneous utility classes a string tokenizer a ran dom number gener
252. nts class specifies constraints for components that are laid out using the GridBagLayout class GridBagLayout The GridBagLayout class is a flexible layout manager that aligns components vertically and horizontally without requiring that the components be of the same size GridLayout The GridLayout class is a layout manager that lays out a container s components in a rectangular grid Image The abstract class Image is the superclass of all classes that represent graphical images Insets An Insets object is a representation of the borders of a container Label A Label object is a component for placing text in a container List The List component presents the user with a scrolling list of text items MediaTracker The MediaTracker class is a utility class to track the status of a number of media objects Menu A Menu object is a pull down menu component that is deployed from a menu bar O Ian D Chivers email ian chivers Okcl ac uk 159 Introduction to Graphics Programming Chapter 11 MenuBar The MenuBar class encapsulates the platform s concept of a menu bar bound to a frame MenuComponent The abstract class MenuComponent is the superclass of all menu related compo nents Menultem All items in a menu must belong to the class Menultem or one of its subclasses MenuShortcut A class which represents a keyboard accelerator for a Menultem Panel Panel is the simplest container class Point A point representing a lo
253. o Addition the White Queen asked What s one and one and one and one and one and one and one and one and one and one T don t know said Alice I lost count Through the Looking Glass Lewis Carroll Aims The aims of this chapter are to look in more depth at arithmetic and in particular what support Java has for the IEEE 754 standard There is a coverage of Hardware support for arithmetic Integer formats Floating point formats single and double Special values denormal infinity and not a number NAN Exceptions and flags divide by zero inexact invalid overflow underflow Chapter 27 IEEE Arithmetic 296 27 IEEE Arithmetic This chapter is based on material from Chivers I D Sleightholme J Introducing Fortran 95 Springer Verlag The literature contains details of the IEEE 754 standard and the bibliography contains de tails of a number of printed and on line sources 27 1 History When we use programming languages to do arithmetic two major concerns are the ability to develop reliable and portable numerical software Arithmetic is done in hardware and there are number of things to consider The range of hardware available both now and in the past The evolution of hardware and there has been a very considerable change in arithmetic units since the first computers The following is a list of hardware and computing systems that the authors have some used or have heard of It is not exhaustive or definitive
254. o areas and very useful in the third 3 15 1 Java As with most programming langauges it is useful to make the following distinctions language tutorial and examples language reference language algorithms The aims of the notes are to provide a brief coverage of the first and second areas There are little or no sources at this time of algorithms in Java Look at the web pages for more details of on line sources There are a lot of these There are a lot of good complete example programs 3 15 2 HTML Use the pointers on the college web pages Most of these are free you only have to pay for the printing email ian chivers kcl ac uk Ian D Chivers Chapter 3 An Introduction to Java 58 3 15 3 Character sets Have a look in the documentation that comes with the system that you work with There are also sources on the web it just takes time to find them and get them printed 3 16 Problems 1 Type in the examples in this chapter You will invariably make typing mistakes Look at the error messages that the compiler give you The compiler gives error messages from their view point Make an attempt to understand what this means 2 What happens with the first example with characters outside of the ASCII character set Does the screen representation of these characters match the printed representation Why do you think that is 3 With the example what happens to so called white space i e spaces tabs and carriage re
255. o use a cast or append with an f We could have also written float f float 1 1 To convert 1 1 from double to float double fd 1 1 This is the second kind of real number in Java So f d is a variable of type double and has an initail value of 1 1 System out println f Print out the float variable System out printlin f d Print out the double variable 4 4 IEEE 754 1985 The standard defines two basic real types single and double and two extended types single extended and double extended Java only supports the basic types This ensures 24 bit precision with single and 53 bit precision within double This means 6 7 digits and 10 38 for single and 15 16 digits and 10 308 for double The idea behind the standard is that you can run your programs on any IEEE compliant sys tem and get the same numeric results 4 5 Numeric Type Conversion With expressions of mixed type the variable of the strongest type will cause promotion of all others The sequence is byte gt short gt int gt long float gt double Explicit casts can always be used 4 6 Whither complex This is not provided in the language 4 7 Constants or Parameters A constant or parameter is defined in Java using the static and final attributes Consider the following example static final double pi 3 14159265358 A complete example is given later 4 8 Operators and Expression Evaluation Java has a large number of
256. ocess can be broken down into four phases that are controlled by the Graphics2D rendering attributes Determine what to render O Ian D Chivers email ian chivers Okcl ac uk 165 Introduction to Graphics Programming Chapter 11 Constrain the rendering operation to the current Clip Determine what colors to render Apply the colors to the destination drawing surface using the current Composite attribute in the Graphics2D context The three types of rendering operations are Shape operations Text operations Image Operations applied to a Graphics2D context 11 24 2 Compatability Whilst the rendering models are different between jdk 1 1 x and jdk 1 2 x this supports anti aliasing Sun have attempted to ensure backwards compatability when running legacy code under 1 2 x 11 24 3 Constructor Summary protected Graphics2D Constructs a new Graphics2D object 11 24 4 Method Summary abstract void addRenderingHints Map hints Sets the values of an arbitrary number of preferences for the rendering algo rithms abstract void clip Shape s Intersects the current Clip with the interior of the specified Shape and sets the Clip to the resulting intersection abstract void draw Shape s Strokes the outline of a Shape using the settings of the current Graphics2D con text void draw3DRect int x int y int width int height boolean raised Draws a 3 D highlighted outline of the specified rectangle abstract void drawGlyphVector Gly
257. of objects and methods What we are doing is invoking the print 1n method on the System class s out object With Java there is the concept of the core language and additional functionality is provided by a number of built in classes Much work has been done with Java to provide a lot of functionality with these additional in built classes It is essential to develop a good working knowledge of what has already been provide There is little point reinventing the wheel This is achieved in C and C using the include statement Text or strings are delimited in Java with marks 1s the statement seperator in Java The character signifies the end of the program There are a number of issues that are important whilst preparing java programs the file name of the java program or applet must be the same as the class name if using more than one platform then stick to an operating system that supports long file names This means that using Windows 3 x is not recommended java is case sensitive I go against the normal style in java texts and stick to lower case I also use short names compile you java program using javac c0301 java run your programs using the java interpreter java c0301 class 3 5 Hello World Java Applet The following is a complete Java applet email ian chivers Q kcl ac uk O Ian D Chivers Chapter 3 An Introduction to Java 50 import java awt public class c0301a extends java applet Applet public void
258. of years namely that the primary purpose of a programming language is to help the programmer in the practice of his art Jenson K Wirth N Pascal User Manual and Report Springer Verlag e The original definition of the Pascal language Understandably dated when one looks at more recent expositions on programming in Pascal Kemeny J G Kurtz T E Basic Programming Wiley e The original book on Basic by its designers Kernighan B W Ritchie D M The C Programming Language Prentice Hall Englewood Cliffs New Jersey e The original work on the C language and thus essential for serious work with C Kowalski R Logic Programming in the Fifth Generation The Knowledge Engineering Re view The BCS Specialist Group on Expert Systems e A short paper providing a good background to Prolog and logic programming with an extensive bibliography Knuth D E The TeXbook Addison Wesley e Knuth writes with an tremendous enthusiasm and perhaps this is understandable as he did design TeX Has to be read from cover to cover for a full understand ing of the capability of TeX Lemay L Perkins Teach Yourself Java in 21 Days Sams net e Most gentle of the books I ve found Includes a CD with the Sun JDK Lyons J Chomsky Fontana Collins 1982 e A good introduction to the work of Chomsky with the added benefit that Chomsky himself read and commented on it for Lyons Very readable Malpas J Prolog A Relational Language an
259. ollowing page has a simple language feature comparison The emphasis is on high lighting the strengths and weaknesses of languages used mainly in the scientific area The following symbols are used Y supported y supported with qualification e g may be achieved using a different mechanism not supported unable to verify adequately at the time of writing In all cases please see the more detailed coverage that follows email ian chivers kcl ac uk Ian D Chivers Chapter 2 An Introduction to Programming Languages 28 and Object Oriented Programming Simple Program Language Feature Comparison Fortran Pascal C CH Ada Java 66 77 90 Modula 2 95 Oberon 2 P M2 02 C C Year 66 78 91 75 82 78 86 87 95 96 82 96 89 97 Feature Independent Y Y Y Y Y compilation Separate Y Y Y Y Y Y Y compilation Concrete T Y Y Y Y Y Y yY 2 data types Abstract Y Y Y Y XO yY Y data types Dynamic Y Y Y Y Y Y arrays Modules Y Y Y y y y y See below Numeric Y 2 Y y y y Polymorphism See below General Y Y Y X X E Polymorphism Pointers a Y Y Y Y Y Y y x 2 Procedure Y Y Y Y Y 2 2 variables Inheritance S M S S single mult Dynamic Y Y b ED 4 binding Operator Y Y YoY cs overloading Threads c Y S Y Y Tasking Exception Y R Y X Handling These are some of the major features that we need to look at when comp
260. ology these are methods and fields The character signifies the start of the class The public static void main String args statement signifies that this is a Java program We will look at turning the above into an applet in the next example The c0301 class contains one method main This method returns a value of void There is the concept of functions and procedures in other languages with functions like sine return ing a value but within the C C Java family of languages we just have functions and when they behave as a procedure or subroutine in another language they are void and re turn a void data type This method is static We will look in more depth a full coverage of static throughout the course For the time being all that is necessary to know is that if we are writing Java pro grams that the main method has to be static This method has the public attribute This means that the method is visible whereever the class is used The main method takes one argument or parameter args and this is of type String This enables the program to access data typed at the command line We will look at arrays of type String in much greater depth throughout the course We then have the character signifying the start of the main method There is one state ment in this method and that is System out println Hello world Let us look at this statement in more depth With object oriented languages there are the twin con cepts
261. olor Color white bgg fillOval int oldx int oldy 20 20 bgg setColor Color blue bgg fillOval int x int y 20 20 g2d drawImage bgi 0 0 this oldx x O lan D Chivers email ian chivers Okcl ac uk 177 Introduction to Graphics Programming Chapter 11 oldy y public void update Graphics g paint g public void run for xt deltax yt deltay if x gt x1 x lt 0 deltax deltax if y gt y1 y lt 0 deltay deltay repaint try Thread sleep 10 catch InterruptedException e public static void main String argv final graphicl2 g12 new graphicl2 gl12 rnvt C JFrame jf new JFrame Using Graphics2D jf addWindowListener new WindowAdapter public void windowClosing WindowEvent e System exit 0 The differences are The init method creates a BufferedImage from an Image An explicit cast is re quired The paint method uses Graphics2D variables and again we have an explicit cast A main method has been added which is identical with that used in 11 30 Experiment with the sleep time email ian chivers kcl ac uk Ian D Chivers Chapter 11 Introduction to Graphics Programming 178 11 32Simple jpeg display import java awt import java awt event import java awt geom import java awt image import javax swing
262. on BasicInternalFrameTitlePane JColorChooser JComboBox JFileChooser JInternalFrame JInternalFrame JDesktopIcon JLabel JLayeredPane JList JMenuBar JOptionPane JPanel JPopupMenu Ian D Chivers email ian chivers kcl ac uk 225 Swing Chapter 14 JProgressBar JRootPane JScrollBar JScrollPane JSeparator JSlider JSplitPane JTabbedPane JTable JTableHeader JTextComponent JToolBar JToolTip JTree JViewport For more information on these subjects see the Swing package description 14 15Examples Chapters 12 and 13 of the Deitel book look at basic and advanced gui programming I would recommend looking at some of these examples to see the newer and better ways of doing things The Eckstein book has a very comprehensive coverage Over 1200 pages Sun provide a very comprehensive demonstration program that can be found on the College web server The url is http www kcl ac uk kis support cit fortran java jdk1 2 2 jfc SwingSet I would recommend trying to run this You will need to get all the source java files and then compile them and run under the appletviewer If you have the jdk installed on your machine they are in the demo directory hanging off the root of the installation There are about 30 files taking up 320Kb on my local hard disk 14 16Problems 0 Try the programs out in this chapter especially the SwingSet demo 14 17Bibliography The major sources I used during the development of these examples in
263. on of a Java package 4 14 2 18 Process The Runtime exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it 4 14 2 19 Runtime Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running 4 14 2 20 RuntimePermission This class is for runtime permissions 4 14 2 721 SecurityManager The security manager is a class that allows applications to implement a security policy 4 14 2 22 Short The Short class is the standard wrapper for short values 4 14 2 23 String The String class represents character strings 4 14 2 24 StringBuffer A string buffer implements a mutable sequence of characters Ian D Chivers email ian chivers kcl ac uk 77 Arithmetic and Expressions in Java Chapter 4 4 14 2 25 System The System class contains several useful class fields and methods 4 14 2 26 Thread A thread is a thread of execution in a program 4 14 2 27 ThreadGroup A thread group represents a set of threads 4 14 2 28 ThreadLocal This class provides ThreadLocal variables 4 14 2 29 Throwable The Throwable class is the superclass of all errors and exceptions in the Java language 4 14 2 30 Void The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void Y
264. on y Vr Ar while findex lt 0 0 findex parent bounceimages length index int findex parent bounceimages length email ian chivers kcl ac uk Ian D Chivers Chapter 11 Introduction to Graphics Programming 184 public class Bounceltem extends Applet implements Runnable boolean images_initialized false Bouncelmage images boolean time_to_die AudioClip music AudioClip sounds Image bounceimages public Bounceltem void makeImages int nimages bounceimages new Image 8 for int i 1 i lt 8 itt bounceimages i 1 getImage getCodeBase images jon T i gif System out println d bounceimages i 1 getWidth bounceimages i 1 getHeight images new BounceImage nimages for int i 0 i lt nimages i Bouncelmage img images i new BounceImage this img move 1 img width 8f i 3 3f img width oo 3 i img height 3f i 3 3f img height sounds new AudioClip 4 sounds 0 getAudioClip getCodeBase au dio ooh au sounds 1 getAudioClip getCodeBase au dio ah au sounds 2 getAudioClip getCodeBase au dio dah au sounds 3 getAudioClip getCodeBase au dio gong au music getAudioClip getCodeBase au dio spacemusic au public void r
265. onnectivity handled by a visual interface on the right It uses ODBC to handle database access Register the database within the ODBC manager under NT and the data sources will appear in the Tango visual interface Clicking on the datbase will then throw up the tables You can then drag and drop the columns you want onto the form 22 1 2 The Web Server It will install a web add on to your server which will handle all web access It passes the re quest onto the database via the odbc driver and will then dynamically generate the html on the fly as the data is returned I have accessed the following data sources in this way Microsoft Access RBTI Rbase Oracle dBase Oracle requires the installation of an Oracle data manager 22 2 Java Java obviously has to work in a similar fashion So you need at least a database on a web accessible machine a jdbc driver for that database a web server process to handle the jdbc request 22 3 Data Sources You will obviously need a data source This is best done using an SQL based relational da tabase management system 22 3 1 Oracle You obviously need an Oracle data source You can get a personal copy of Oracle from the Oracle site They also offer it on a cd Ian D Chivers email ian chivers kcl ac uk 267 Web Data Access Chapter 22 22 3 2 Microsoft If you have Office then you may already have Access This combined with Microsoft Vi sual J should be enough to get you started
266. ook at a simple hello world example to look at java programs to look at java applets to look at a simple string example to look at a simple numeric example to introduce some of the formal syntactical rules of Java to look at the Java keywords to provide definitions of some technical terms used throughout the rest of the notes to look at the Java memory model to look at the Java character set Chapter 3 An Introduction to Java 48 3 An Introduction to Java In this chapter we will look at three simple program examples The first looks at a simple hello world example the second a simple text i o and the third looks at simple numeric i o We will also look at variants of these programs that occur with Java depending on whether we want to write a Java program or a Java applet that runs within a web browser We will also look at the flavours of doing this that exist within Java due to the evolution of the lan guage We will also look at some of the syntax of Java programs 3 1 Program Development Most people will have the following model of programming write the program using an editor compile the source using a compiler linking the output from the compiler to produce an executable running the executable and as most of us know this is an iterative process We rarely get it right first time Java is different There is in effect no link stage The compiler generates byte codes that are then interpreted directly us
267. operators A working knowledge of the more commonly used ones is essential for successful use of Java You should also be aware of the rest 4 8 1 Expression Evaluation Expressions are evaluated left to right in Java when involving operators of a similar prece dence Brackets can be used to alter the order of evaluation The following example illus trates this email ian chivers kcl ac uk O Ian D Chivers Chapter 4 class c0403 Arithmetic and Expressions in Java 64 public static void main String args int 1 2 3 4 System out println i The program prints out 14 4 8 2 Operators Precedence and Associativity The following table summarises the rules concerning precedence and associativity All oper ators associate left to right except for those in the third and eighteenth position in the prece dence hierarchy i e the unary and assignment operators Operator Summary member selection subscripting Q function call post increment post decrement pre increment pre decrement complement not unary minus unary plus new new O cast i multiply divide modulo or remainder plus minus lt lt shift left gt gt shift right sign extend gt gt gt shift right zero fill lt less than lt less than or equal gt greater than gt greater than or equal instanceof instanceof equal l not equal Ian D Chivers object member exp
268. operties class represents a persistent set of properties 25 1 2 23 PropertyPermission This class is for property permissions 25 1 2 24 PropertyResourceBundle PropertyResourceBundle is a concrete subclass of ResourceBundle that manages resources for a locale using a set of static strings from a property file 25 1 2 25 Random An instance of this class is used to generate a stream of pseudorandom numbers 25 1 2 26 ResourceBundle Resource bundles contain locale specific objects 25 1 2 27 SimpleTimeZone SimpleTimeZone is a concrete subclass of TimeZone that represents a time zone for use with a Gregorian calendar 25 1 2 28 Stack The Stack class represents a last in first out LIFO stack of objects 25 1 2 29 StringTokenizer The string tokenizer class allows an application to break a string into tokens 25 1 2 30 TimeZone TimeZone represents a time zone offset and also figures out daylight savings 25 1 2 31 TreeMap Red Black tree based implementation of the SortedMap interface 25 1 2 32 TreeSet This class implements the Set interface backed by a TreeMap instance 25 1 2 33 Vector The Vector class implements a growable array of objects 25 1 2 34 WeakHashMap A hashtable based Map implementation with weak keys Ian D Chivers email ian chivers kcl ac uk 289 Package java util Chapter 25 25 1 3 Exception Summary 25 1 3 1 ConcurrentModificationException This exception may be thrown by methods that have detec
269. orms the wave period is generally shorter say 6 to 8 seconds and the wave heights higher 3 to 5 metres The beach slope may be taken as about 0 1 What changes occur in breaker charac teristics as a storm builds up 11 Similarly many beaches have a concave profile The lower beach generally has a very low slope say less than 1 degree m 0 018 but towards the high tide mark the slope in creases dramatically to say 10 degrees or more m 0 18 What changes in wave type will be observed as the tide comes in 6 Personal taxation is usually structured in the following way no taxation on the first mo units of income taxation at t1 on the next m units taxation at t2 on the next m2 units taxation at t3 on anything above Ian D Chivers email ian chivers kcl ac uk 105 Control Structures Chapter 7 For some reason this is termed progressive taxation Write a generalised program to deter mine net income after tax deductions Write out the gross income the deductions and the net income You will have to make some realistic estimates of the tax thresholds mi and the taxation levels ti You could use this sort of model to find out how sensitive revenue from taxation was in relation to cosmetic changes in thresholds and tax rates 8 The specific heat capacity of water is 2009 J kg kc the specific latent heat of fusion ice water is 335 kJ kg and the specific latent heat of vaporization water steam is 2500 kJ kg As
270. ote debugging Both provide programming wizards and access to the Windows Foundation Classes The on line documentation is adequate I ve provided details of third party books in the bibliog raphy The emphasis throughout is on creating Windows based applications or programs using Java If you don t mind sticking to the Windows platform then this doesn t matter However if you want an application that can run on any platform then this is a major headache and you would be better off with another development environment or compiler 18 2 The Development Environment If you have used Visual Basic or Visual C then you will be quite at home If you haven t don t panic Work through the examples provided I would start by using the help menu and Ian D Chivers email ian chivers kcl ac uk 243 Microsoft Visual J Chapter 18 following the links to the Java documentation and work through that The Cowell book is another option grapt cl java Codo import jswa mwt B Solution Solution 0 project S B micro Mia E 5 ff dimple graphics example of a bouncing ball ff Things to look at are the amount of flicker ff amd the amount of time that the thread is put to sleep This is in milliseconds It is warth axpeclmentiag wlth thia as the applet will behave differently on different systema public clase graphic extends java spplet hpplet implem i 1 double x y delrtax delray double x1 3005 do
271. ou must look at the on line documentation for more details of what are in these classes 4 15 Bibliography TEEE 754 1985 The standard is the definitive statement Other sources include Suns Numerical Computa tion Guide Similar publications will exist for other platforms What Every Computer Scientist Should know About Floating Point Arithmetic This paper first appeared in the March 1991 issue of Computing Surveys ACM Inc It can also be found after some rumaging around on Sun systems I recommend the paper very highly 4 16 Problems 1 Try typing in and running the examples given in this chapter Remember that you need to gain familiarity with the Java rules You need to make mistakes and see what goes wrong 2 Write a program that will read in your name and address and porint them out Now mod ify the program to read in your age also Print out your name age and address 3 One of the easiest ways to write a program is to modify an existing one The example given earlier dealing with the time taken for light to travel from the sun to the earth could form the basis of several other programs many communications satellites follow a geosynchronous orbit some 35 870 Km above the earth s surface What is the time lag in using such a satellite for a tele phone conversation the moon is about 384 400 Km from the earth on average what implications does this have for control experiments on the moon what is the time lag the follo
272. ou use Windows try CTRL ESC to bring up a list of tasks Some programming languages offer support for writing programs that can multitask Mod ula 2 offers coroutines Ada has tasks and Java has threads This will enable us to write Java programs that run each of the following as a separate thread download data from a remote system play sound interact with a user carry out calculations display the output from these calculations as the calculations run 10 1 Example 1 extends Thread The first example creates two threads and starts them running The main loop of the pro gram then gets the current thread name and prints it out public class thread01 extends Thread public static void main String args thread01 tl new thread01 0 thread01 t2 new thread01 0 El sstart E2 start public void run for System out printin Thread currentThread getName Ian D Chivers email ian chivers kcl ac uk 131 Threads Chapter 10 Let us look at the program in more depth public class thread01 extends Thread This creates our own class called threadO1 that is an extension of the inbuilt class thread thread01 tl new thread01 thread01 t2 new thread01 These two statements create two objects of type thread01 We use the class name as the constructor tl start t2 start These two statements start the thr
273. ource of information if you have Sun equipment http www validgh com This web site contains technical and business information relating to the validgh profes sional consulting practice of David G Hough Contains links to the Goldber paper and the above addendum by Doug Priest http babbage cs qc edu courses cs341 IEEE 754references html Brief coverage of IEEE arithmetic with pointers to further sources There is also a coverage of the storage layout and ranges of floating point numbers Computer Science 341 is an in troduction to the design of a computer s hardware particularly the CPU and memory sys tems http www nag co uk nagware NP TR html NAG provide coverage of TR 15580 and TR 15581 The first is the support Fortran has for IEEE arithmetic http www cs berkeley edu wkahan Willam Kahan home page http www cs berkeley edu wkahan ieee754status 754story html An Interview with the Old Man of Floating Point Reminiscences elicited from William Kahan by Charles Severance which appears in an issue of IEEE Computer March 1998 not confirmed http www cs berkeley edu wkahan ieee754status ieee754 ps Lecture Notes on the Status of IEEE Standard 754 for Binary Floating Point Arithmetic Well worth a read http www stewart cs sdsu edu cs575 labs 13floatpt html CS 575 Supercomputing Lab 3 Floating Point Arithmetic CS 575 is an interdisciplinary course to introduce students in the sciences and engineering to advanced
274. ovided in previous versions of the JDK software The immediate mode model introduced in the Java 2 SDK software release The pipeline pull model compatible with the immediate mode model and that will be fully implemented in the forthcoming Java Advanced Imaging API The following table contrasts the features of each of these imaging models Push Immediate Pull Class Image BufferedImage RenderableImage Interface ImageProducer Ratser RenderablelmageOp ImageConsumer BufferedlmageOp RenderedOp ImageObserver RatserOp RenderableOp TiledImage Pros Driven by image Simplest Required availability Programming data only processed interface Lazy incrementally Commonly used evaluation Cons Transfer memory required more complex required for whole image interface and more complex api complete image implementation processing This API supports accessing image data in a variety of storage formats and manipulating image data through several types of filtering operations 11 29 10 Color Color imaging is one of the fundamental components of any graphics system and it is often a source of great complexity in the imaging model The Java 2D API provides support for high quality color output that is easy to use and allows advanced clients to make sophisti cated use of color The key color management classes in the Java 2D API are ColorSpace Color ColorModel A ColorSpace represents a system for measuring colors typically using three separate nu
275. paint Graphics g g drawString Hello world 10 20 The first line identifies which of the java classes are to be made available to the applet the syntax is in fact the same for a Java program There are several core classes in the Java application program interface api These are java lang java io java util java net java awt java applet and we will look at these in more depth where appropriate A good understanding of Java therefore requires a knowledge of the contents of each class When we import a class we are able to use methods within that class with a shortened name form So import java awt makes available the abstract windowing toolkit This package is made of the following main components graphics for controlling fonts colours etc components for controlling graphical user interfaces gui and pronounced gooey using buttons menus lists etc layout managers for the control of components within their container objects image for manipulating images We will look into this whole area in more detail throughout the course The following identifies this class as an applet rather then a program public class c0301a extends java applet Applet The first thing to note is that our class c0301a is an extension of one of the inbuilt Java classes Applet This is a simple example of inheritance This means we can create our own applets by using the build in class java appl
276. phVector g float x float y Renders the text of the specified GlyphVector using the Graphics2D context s rendering attributes abstract void drawImage BufferedImage img BufferedImageOp op int x int y Renders a BufferedImage that is filtered with a BufferedImageOp abstract boolean drawImage Image img AffineTransform xform ImageObserver obs Renders an image applying a transform from image space into user space before drawing abstract void drawRenderableImage RenderableImage img AffineTransform xform Renders a RenderableImage applying a transform from image space into user space before drawing abstract void drawRenderedImage RenderedImage img AffineTransform xform email ian chivers kcl ac uk O Ian D Chivers Chapter 11 Introduction to Graphics Programming 166 Renders a RenderedImage applying a transform from image space into user space before drawing abstract void drawString AttributedCharacterlterator iterator float x float y Renders the text of the specified iterator using the Graphics2D context s current Paint abstract void drawString AttributedCharacterlterator iterator int x int y Renders the text of the specified iterator using the Graphics2D context s current Paint abstract void drawString String s float x float y Renders the text specified by the specified String using the current Font and Paint attributes in the Graphics2D context abstract void drawString String str int x int y
277. ple looks a little unpleasant do to the requirment to cast from the various default types Let us now look at a slight variant using double throughout class c0408 static final double light_year 9 46 10E12 public static void main String args double light_minute distance lapse int minute second light_minute light_year 365 25 24 0 60 0 distance 150 0 10E6 elapse distance light_minute minute int elapse second int elapse minute 60 System out print Light takes System out print minute System out print minutes System out print System out print second System out printin seconds O Ian D Chivers email ian chivers Okcl ac uk 71 Arithmetic and Expressions in Java Chapter 4 Better now look at the last variant class c0409 static final float light year 9 46f 10E12f public static void main String args float light_minute float distance float elapse int minute int second light_minute light_year 365 25f 24 0f 60 0f distance 150 0f 10E06f elapse distance light_minute minute int elapse second int elapse minute 60f System out print Light takes System out print minute System out print minutes System out print System out print second System out printi
278. pler Albert Einstein Aims The aims of this chapter are to provide an overview of Sun s offerings in this area Chapter 17 Forte for Java 240 17 Forte for Java So far we have only looked at a simple command line interface to Java programming We have been able to achieve quite a lot with this approach and working under Unix or Dos is almost identical We are now going to look at another way of working with a complete development environment There are two components to a complete environment and these comprise the JDK the graphical interface and you need both and they need to work togethor The early Sun development environments were not very good They then took an interest in a third party product called Netbeans and bought the product and rebadged it It is now called Forte for Java The following urls are useful http java sun com j2se 1 3 download windows html provides details of several IDEs for Java http www sun com forte ffj ce 1s the Forte home page The IDE is written entirely in Java The idea is that through a set of wizards utilities and templates you can write code quicker The IDE provides the ability to design a graphical user interface using a form editor 17 1 Forte Recommended Configurations Sun s recommendation on an Intel platform is Intel Pentium II processor with a 300 MHz CPU 128 Mbytes of memory and 30Mbytes of disk space I ve tried the following P120 with 64 Mb of memory Windows 93
279. ponents and they include Menus Buttons Dialog Boxes List Boxes Combo Boxes Layout Managers O lan D Chivers email ian chivers kcl ac uk 217 Swing Chapter 14 Tables Trees Undo Look and Feel We will look at each in turn and use the examples from the AWT chapter as our starting point 14 10Simple Examples Given the sheer size of Swing we are only going to touch briefly on what can be done In this section we will simply rewrite the AWT examples to use Swing classes where possible and simply compare the differences What we will try in most cases is a minimal set of changes to the original examples Some will work some won t We will look at the new ways of doing things later on in the chapter 14 10 1 JButton In this case we only have to make very minor changes The first is the extra import line and the simple replacement of Button with JButton import java awt import javax swing public class s1410 extends java applet Applet public void init Font f new Font Arial Font PLAIN 20 setFont f add new JButton QPR add new JButton Arsenal add new JButton Spurs Compile and run the program Compare this example with the AWT equivalent 14 10 2 JLabel import java awt import javax swing public class s1411 extends java applet Applet public void init Font f new Font Arial Font PLAIN 20 setFont f
280. pper around a millisecond value that allows JDBC to identify this as a SQL DATE 22 5 2 2 DriverManager The basic service for managing a set of JDBC drivers 2252 3 DriverPropertyInfo Driver properties for making a connection email ian chivers kcl ac uk O Ian D Chivers Chapter 22 Web Data Access 270 22 5 2 4 Time A thin wrapper around java util Date that allows JDBC to identify this as a SQL TIME value 22 5 2 5 Timestamp This class is a thin wrapper around java util Date that allows JDBC to identify this as a SQL TIMESTAMP value 22 5 2 6 Types The class that defines constants that are used to identify generic SQL types called JDBC types 22 5 3 Exception Summary 22 5 3 1 BatchUpdateException JDBC 2 0 22 5 3 2 DataTruncation An exception that reports a DataTruncation warning on reads or throws a DataTruncation exception on writes when JDBC unexpectedly truncates a data value 22 5 3 3 SQLException An exception that provides information on a database access error 22 5 3 4 SQLWarning An exception that provides information on database access warnings 22 6 Package javax sql 22 6 1 Interface Summary 22 6 1 1 ComnectionEventListener A ConnectionEventListener is an object that registers to receive events generated by a PooledConnection 22 6 1 2 ConnectionPoolDataSource A ConnectionPoolDataSource object is a factory for PooledConnection objects 22 6 4 DataSource A DataSource object is a factory
281. pplet public void init Font f new Font Arial Font PLAIN 20 setFont f add new JCheckBox OPR null true add new JCheckBox Arsenal add new JCheckBox Spurs 14 10 CheckBox with Grouping import java awt import javax swing public class s1416 extends java applet Applet public void init Font f new Font Arial Font PLAIN 20 setFont f JCheckBoxGroup g new JCheckBoxGroup add new JCheckBox QPR g false add new JCheckBox Arsenal g false This example won t compile Look at the on line documentation and work out what we need from Swing to replace what we have in the above AWT based example 14 10 8 List import java awt import javax swing public class s1417 extends java applet Applet public void init Font f new Font Arial Font PLAIN 20 setFont f JList l new JList 3 false l addltem Qpr additem Arsenal addItem Spurs additem Chelsea addItem Crystal Palace add 1 email ian chivers Okcl ac uk O Ian D Chivers Chapter 14 Swing 220 This compiles with 6 error messages Do you think it will run Try it what What do you think has happened 14 10 9 TextField import java awt import javax swing public class s1418 extends java applet Applet public void init add new JTextField Who are you favourite London team
282. quare root and trigonometric functions You make the fields and methods available by adding import java lang Math at the start of you program and qualify the functions by preceding the function name with Math The following example illustrates the above with a simple trigonometric function class sine_example public static void main String args int angle_d 30 float angle_r angle_r float angle_d float Math PI float 180 System out printin Math sin angle_r Ian D Chivers email ian chivers kcl ac uk 75 Arithmetic and Expressions in Java Chapter 4 Run the program What should be the value for the sine of 30 degrees Note that I ve also left out the import I recommend adding it as it clearly indicates what parts of the class library you are using Fields Methods static double E The double value that is closer than any other to e the base of the natural logarithms static double PI The double value that is closer than any other to pi the ratio of the circumference of a circle to its diameter static double abs double a Returns the absolute value of a double value static float abs float a Returns the absolute value of a float value static int abs int a Returns the absolute value of an int value static long abs long a Returns the absolute value of a long value static double acos double a Returns the arc cosine of an angle in the range of 0 0 through pi static double as
283. r expr expr_list expr expr expr expr expr expr expr expr new object type expr expr expr expr expt expr expr expr expr expr expr expr lt lt expr expr gt gt expr expr gt gt gt expr expr lt expr expr lt expr expr gt expr expr gt expr object instanceof object expr expr expr expr email ian chivers kcl ac uk 65 Arithmetic and Expressions in Java Chapter 4 amp bitwise AND expr amp expr bitwise exclusive OR expr expr bitwise inclusive OR amp amp logical AND Il logical OR ie conditional expression conventional assignment multiply and assign divide and assign Jo modulo and assign add and assign subtract and assign lt lt shift left and assign gt gt shift right and assign gt gt gt shift right and assign amp AND and assign I inclusive OR and assign A exclusive OR and assign expr expr expr amp amp expr expr ll expr expr expr expr lvalue expr lvalue expr lvalue expr expr expr expr expr expr expr expr lt lt expr expr gt gt expr expr gt gt gt expr expr amp expr expr l expr expr expr There will be more complete examples of each of the following in later chapters 4 8 2 1 member selection object member This operator allows us to select a member of a class 4 8 2 2 The normal array subscripting operator 4 8 2 3
284. rag and Drop operation 26 1 2 2 DragGestureEvent A DragGestureEvent is passed to DragGestureListener s dragGestureRecognized method when a particular DragGestureRecognizer detects that a platform dependent drag initiating gesture has occurred on the Component that it is tracking 26 1 2 3 DragGestureRecognizer The DragGestureRecognizer is an abstract base class for the specification of a plat form dependent listener that can be associated with a particular Component in order to iden tify platform dependent drag initiating gestures 26 1 2 4 DragSource The DragSource is the entity responsible for the initiation of the Drag and Drop operation and may be used in a number of scenarios 1 O Ian D Chivers email ian chivers kcl ac uk 293 Package java awt dnd Chapter 26 default instance per JVM for the lifetime of that JVM 26 1 2 5 DragSourceContext The DragSourceContext class is responsible for managing the initiator side of the Drag and Drop protocol 26 1 2 6 DragSourceDragE vent The DragSourceDragEvent is delivered from the DragSourceContextPeer via the DragSourceContext to the currently registered DragSourceListener 26 1 2 7 DragSourceDropEvent The DragSourceDropEvent is delivered from the DragSourceContextPeer via the DragSourceContext to its currently registered DragSourceListener s dragDropEnd method 26 1 2 8 DragSourceEvent This class is the base class for DragSourceDragEvent and DragSourceDropEvent 26 1 2 9
285. read a variety of books used the on line documentation that comes with each version I ve used use the links that Sun provide to their web server They provide a lot of essential information regarding Java read the definitions of the language provided both in books published by Sun and available on line with the development kit last and most importantly write examples to test out my understanding Sun provide on line turorials and you may like to have a look at what they offer Home page is http java sun com docs books tutorial index html The tutorial is also available for download You might want to consider this option when working at home Avoids the cost of the telephone URL is http java sun com docs books tutorial information download html O lan D Chivers email ian chivers Okcl ac uk 17 Overview Chapter 1 The size of these may put you off downloading over a telephone line Around 9 10 Mb in March 2000 1 4 Java Versions Bits of History Java is evolving There are a number of versions around The first I used was JDK 1 0 2 The oldest books will use this version The date of the book is very important Later chap ters in the notes will provide additional information 1 4 1 1 0 x The first release was in early 1996 1 0 2 was the first version I used and came out in 1996 too 1 0 2 added an improved set of graphics classes First College course given in 1996 1997 1 4 2 1 1 x Early 1997 Added a new event hand
286. reate s1 and s2 as String objects and give them initial values There is no explicit new here String s3 s3 is declared to be an object of type String String s4 new String s4 is declared to be an object of type String and we have an explicit use of new here to cre ate the object s4 s3 sl s2 s3 is created again no explicit new and is given an initial value of s1 concatenated with s2 We then print out each string il sl length 12 s2 length i4 s4 length These statements highlights the way in which object oriented programming differs from conventional programming We have a binding of an object with an action i e a String object with a length determina tion 5 2 1 String Methods Here are some of the more common String methods They are organised into three catego ries Constructors public String public String String value public String char value public String StringBuffer buffer Class Methods public static String copyValueOf char data public static String valueOf Object data public static String valueOf boolean b public static String valueOf char c public static String valueOf int i public static String valueOf long 1 public static String valueOf float f public static String valueOf double d Public Instance public char charAt int index Methods public int compareTo String str public boolean equals Object o public boolean equalsIgnoreCase String str public int index
287. rom left to right and afterwards in case he had missed some of it from right to left A A Milne Winnie the Pooh From a programmer s point of view the user is a peripheral that types when you is sue a read request Peter Williams Aims The aims of this chapter are to look at the mechanisms in Java for i o As Java is fully object oriented the way Java does i o will appear strange at first There is a coverage of streams and their use for both input and output Chapter 9 i o 120 9 i o There is a complete package for i o called java io This contains paired streams A stream is an ordered sequence of data A stream has either a source or a destination There is no way at the moment within Java of getting formatted output This means that you cannot define a minimum width on output define a maximum width on output define precision for floating point output Thus it is impossible at present to achieve neat tabular output A subset is listed below InputStream OutputStream ByteArrayInputStream ByteArrayOutputStream PipedInputStream PipedOutputStream FilterInputStream FilterOutputStream DataInputStream DataOutputStream FileInputStream FileOutputStream RandomAccessFile DataInput DataOutput DataInputStream DataOutputStream The complete hierarchy is given below This highlights many of the very important con cepts involved in object oriented programming Object File FileDescriptor InputStream ByteArrayInputStream
288. rough the use of working with Beans including manipulating beans moving them around changing their properties connecting beans There is also a coverage of working with relational using the select bean email ian chivers kcl ac uk Ian D Chivers Chapter 19 IBM VisualA ge for Java 250 19 3 3 Visual Composition Concepts and Tasks 267 pages IBM provide and I quote a state of the art object oriented visual composition editor for assembling programs visually from JavaBeans components 19 3 4 Data Access Concepts and Tasks 61 pages Web access to data is becoming increasingly important This takes you through some of what IBM have done to make this possible with Java 19 3 5 SCM Tools Concepts and Tasks 16 pages Software Configuration Management 19 3 6 AgentRunner Concepts Tasks and Samples 25 pages Create and run Domino based agents 19 3 7 Tool Integrators 20 pages Integrate file based code within the IDE 19 4 Installation Follow the installation guidelines for which ever version you have 19 5 Overview If you are used to thinking in terms of a program being made up of one or more source files and going through the following cycle edit compile link if no errors run then the first time you meet a development environment can be quite a shock Both Microsoft Visual Basic and Developer Studio take a while to get used to Visual Basic also introduces the concept of visual development where one
289. rprise approx 2 000 uk pounds Needless to say I haven t used the Enterprise Edition The Entry Edition can be downloaded from the web Visit http www7 software ibm com vad nsf email ian chivers kcl ac uk Ian D Chivers Chapter 1 Overview 18 for more details Microsoft Visual J 6 0 This comes bundled with Developer Studio Enterprise Edition This is available at quite a reasonable price I also use Visual Basic and Visual C I also have Visual Fortran from DEC Now Compaq This is inte grated into the Developer Studio Environment Sun Java Workshop Netbeans Forte Details of the last two can be found at Sun s addresses above Other implementations of Java exist and include Java Workshop Sun JBuilder Sybase PowerJEnterprise Edition Sybase Visual Cafe IBM Jikes this is freely available and provides a dos based working enviornment on the pc There are a number of ways of working with Java Use the command prompt under DOS or Unix and compile and run the pro grams Use a workbench to provide a graphical interface to the above Use a visual development environment that enables you to develop programs us ing a mouse and drag and drop components The quick and dirty method is to use the command prompt The other two approaches take additional time due to their learning curve The environments are generally different so learning one may not shorten the learning curve for the next Web access to dat
290. rs with a file with a class extension So this is the compiled java applet The width and height are the size of the inital sizes of the browser window in pixels These two values must be specified So when we create an applet as opposed to a program we need to also create an html file that can be used by the web browser The applet examples will be put up on the college web server as the course progresses These can then be ran using Netscape on a pc or a mac I use Netscape 3 under both Win dows 95 and NT You can run them yourselves on the Sun using the appletviewer that co mes with the development kit So the sequence is now create the java applet use the unix editor vi compile the java applet use the Sun Java compiler javac create the associated html file vi use the appletviewer to run the html file appletviewer Alternatively use a web browser I have put up the applets on the college web server so that you can try them out using a web browser 3 6 Hello World JApplet The next variation uses JApplet rather than Applet JApplet provides access to the graphi cal components from javax swing import java awt public class c0301b extends javax swing JApplet public void paint Graphics g g drawString Hello world 10 20 Note that we are still using the graphics components from java awt 3 7 Hello World JApplet alternate syntax This shows an alternate syntax for this program import
291. rs and strings The following provides some information regarding the languages supported under Unicode Arabic ISO 8859 6 Catalan ISO 8859 1 Chinese Simplified GB2312 Chinese traditional BIGS Danish ISO 8859 1 Dutch ISO 8859 1 English ISO 8859 1 Esperanto ISO 8859 3 Finnish ISO 8859 1 French ISO 8859 1 Georgian UTF 8 German ISO 8859 1 Hebrew ISO 8859 1 Hungarian ISO 8859 2 Irish Gaelic ISO 8859 1 Italian ISO 8859 1 Japanese SHIFT JIS Korean EUC KR Norwegian Bokmal ISO 8859 1 Norwegian Nynorsk ISO 8859 1 Occitan ISO 8859 1 Portuguese Brazil ISO 8859 1 Portuguese Portugal ISO 8859 1 Romanian ISO 8859 2 Russian ISO 8859 5 Slovenian ISO 8859 2 Spanish ISO 8859 1 Swedish ISO 8859 1 Yiddish UTF 8 Other languages that I know are supported within Unicode include Gujariti Telugu Kannada Mayalam Thai Lao O Ian D Chivers email ian chivers Okcl ac uk 89 Strings Chapter 5 5 6 Summary So far we ve only looked at characters and Strings and StringBuffers As Java is unicode based we are dealing with 16 bit characters and each element of a string is 16 bit We can also look at character manipulation in a number of other ways that may be more appropriate to the problem in hand Thus we can have arrays of characters conversion to byte from both char and String and StringBuffer conversion
292. rse by using the on line doc umentation O lan D Chivers email ian chivers Okcl ac uk
293. rt this System out printin s1 System out printin s2 try sl insert 1 s2 System out printin s1 sl insert 10 s2 System out printin s1 sl insert 20 s2 System out printin s1 sl insert 99999 s2 System out println s2 email ian chivers kcl ac uk Ian D Chivers Chapter 5 Strings 86 catch StringIndexOutOfBoundsException e System out printin String too large Let us look in more details at some of the statements in this program StringBuffer sl new StringBuffer this is the base string StringBuffer s2 new StringBuffer insert this These two statements define and create the two StringBuffer objects with initial values There are only three constructors defined for the StringBuffer class compared to seven for the String class The creation of String and String Buffer objects within Java is quite different e g Creation Mechanism String StringBuffer Text in quotes Yes No and Yes No explicit new Yes Yes This means that code that we write for handling objects of these types is syntactically quite different We next print out the two StringBuffer objects try sl insert 1 s2 System out printin sl sl insert 10 s2 System out printin sl sl insert 20 s2 System out printin s1 sl insert 99999 s2 System out println s2 catch StringIndexOutOfBoundsExcep
294. s Looks at some of the trade offs and design philosophy behind the alpha chip The author worked with VAX MicroVAX and VAX vectors as well as the Prism Also looks at the GEM compiler technology that DEC Compaq use http www digital com alphaserver workstations Home page for the Compaq DEC Alpha systems http www sgi com Silicon Graphics home page http www sun com Sun home page http www ibm com IBM home page 27 5 3 Operating Systems Deitel H M An Introduction to Operating Systems Addison Wesley The revised first edition includes case studies of Unix VMS CP M MVS and VM 27 5 4 Java and IEEE 754 http www cs berkeley edu darcy Borneo Borneo Language Homepage Borneo is a dialect of the Java language designed to have true support for the IEEE 754 floating point standard Well worth reading 27 5 5 C and IEEE 754 http wwwold dkuug dk JTC1 SC22 WG14 email ian chivers kcl ac uk Ian D Chivers Chapter 27 IEEE Arithmetic 304 The official home of JTC1 SC22 WG14 C The C programming language standard ISO IEC 9899 was adopted by ISO in 1990 ANSI then replaced their first standard X3 159 by the ANSI ISO 9899 standard identical to ISO IEC 9899 1990 http www c9x org Another source of information regarding C9X There is a draft of the standard available and Annex F G and H contain details of the changes concerning arithmetic Ian D Chivers email ian chivers kcl ac uk 28 Language S
295. s kcl ac uk Ian D Chivers 19 IBM Visual Age for Java Aims The aim of this chapter is to provide a brief introduction to IBM Visual Age for Java Chapter 19 IBM VisualA ge for Java 248 19 IBM VisualAge for Java The aim of this chapter is to provide a brief introduction to IBM Visual Age for Java 19 1 Health Warning The major part of the development work in this chapter has been done on a 350 MHz Pentium PII with 64 Mb of memory I ve also tried the entry level on a Cyrix clone be tween a Pentium 133 and Pentium 166 with 32Mb of memory This is slow 19 2 Versions and Availability Home page for VisualAge Developer Domain is http www7 software ibm com vad nsf Three versions are available Entry Professional Enterprise The first is free At the time of writing these notes VisualAge 2 0 Entry Edition was avail able This includes support for JDK 1 1 6 Swing 1 0 2 You have to register to get a user id and password that allows you to then download the various offerings Don t forget our password I ve forgotten mine The Professional Edition costs about 80 uk pounds It comes with a couple of additional CDs containing a variety of material I ve included some details of what you get below 19 2 1 VisualAge Object Connection Partners CD Version 2 0 1 This CD provides a number of Java products built with or built for IBM VisualAge for Java It contains software including JavaBeans and tools an
296. s I recommend starting at http java sun com products servlet index html and downloading the following the Java servlet api documentation the Java servlet development kit and following the instructions I have had mixed results with the install depending on what I ve already got installed I would not recommend installing jdk1 3 Forte for Java which currently requires the 1 3 jdk IBM Visual Age for Java I would recommend installing in the directory where you have the JDK The 2 1 JSDK will create the following directory structure and associated files on you sys tem 8978 Apr 27 1999 LICENSE txt 3028 Apr 28 1999 README txt 837 Apr 27 1999 default cfg 92904 Apr 2 1999 server jar 22562 Apr 2 1999 servlet jar 1397 Apr 2 1999 startserver 664 Apr 27 1999 startserver bat 1162 Apr 2 1999 stopserver 648 Apr 2 1999 stopserver bat O Jul 11 13 45 unix txt etc 1696 Apr 27 1999 SimpleStartup java examples examples WEB INF O Ian D Chivers email ian chivers Okcl ac uk 275 Servlets Chapter 23 237 Apr 27 1999 mappings properties 219 Apr 27 1999 mime properties 350 Apr 27 1999 servlets properties 324 Apr 27 1999 webapp properties examples WEB INF jJsp examples WEB INF jsp beans examples WEB INF jsp beans cal 1630 Apr 21 1999 Entries class 1088 Apr 27 1999 Entrie
297. s a good example of this Products like this typically have a toolbox of components that can be dragged and dropped onto a screen a screen or form that the user will see this comprises the user interface a set of properties for each of the components that can be tailored for your own requirements You typically use the mouse to select the item you want from the toolbox menu form etc drag and dop onto the form and then alter the various associated setting using the propertiy entries on the right hand side Skeleton code is often generated for you which you then tai lor to your own specific requirements For some alternatives to using Visual Basic to put a windows based front end to a program have a look at the following url for more details http www kcl ac uk kis support cc fortran language html There will be a course later this academic year that looks at this whole area in more depth 2 04 Software Components As the problems that we attempt to solve become more complex and the interfaces we pro vide become more sophisticated we need better tools to help with program development O lan D Chivers email ian chivers Okcl ac uk 39 An Introduction to Programming Languages Chapter 2 and Object Oriented Programming One major step forward is in reusable software components This can be seen as an exten sions to the object oriented approach to programming Consider building an application that required a spelling checker Th
298. s are taken from the Fortran 95 and C courses These examples are available on the college web server enabling you to compare the syntax of the three languages The rest of the examples look at what Java has to offer in its own right In particular there is a coverage of both Java programs and Java applets Java programs are usually interpreted using the Java interpreter provided with the development kit you use whilst Java applets run in a web browser We will look into the differences in more depth later The emphasis is on breadth rather than depth 1 2 Assumptions It is assumed that the reader has a working knowledge of programming with one of Fortran 77 Fortran 90 Fortran 95 Pascal Modula 2 C or C knows about the benefits of structured programming knows about the data structuring facilities in one of the above languages has some knowledge of object oriented programming 1 3 Course Material and Recommended Sources The course material is not complete It is useful to make the following distinctions when learning any programming language introductory complete texts on a programming language reference texts on a programming language good programming practice in a programming language introductions to object oriented programming The following are some sources I ve found useful The list is not exhaustive and your mile age will vary To get a reasonable working knowledge of Java I ve found that I ve had to
299. s java 771 Apr 21 1999 Entry class 586 Apr 27 1999 Entry java 3112 Apr 21 1999 JspCalendar class 2949 Apr 27 1999 JspCalendar java 2018 Apr 21 1999 TableBean class 1890 Apr 27 1999 TableBean java examples WEB INF jsp beans colors 1858 Apr 21 1999 ColorGameBean class 2788 Apr 27 1999 ColorGameBean java examples WEB INF jsp beans error 463 Apr 21 1999 Smart class 231 Apr 27 1999 Smart java examples WEB INF servlets 3265 Apr 2 999 CookieExample class 3398 Apr 27 1999 CookieExample java 1721 Apr 2 1999 HelloWorldExample class 1714 Apr 27 1999 HelloWorldExample java 1354 Apr 27 1999 LocalStrings properties 2251 Apr 2 1999 RequestHeaderExample class 2153 Apr 27 1999 RequestHeaderExample java 2464 Apr 21 1999 RequestInfoExample class 2814 Apr 27 1999 RequestInfoExample java 2661 Apr 21 1999 RequestParamExample class 2973 Apr 27 1999 RequestParamExample java 3407 Apr 2 1999 SessionExample class 3574 Apr 27 1999 SessionExample java examples images 292 Apr 21 1999 code gif 1242 Apr 2 1999 execute gif 1231 Apr 2 1999 return gif examples servlets 1895 Apr 2 1999 cookies html 1854 Apr 2 1999 helloworld html email ian chivers Q kcl ac uk O Ian D Chivers Chapter 23 4451 4 281 1684 4 8 2475 SrC Ssrc javax src javax
300. se n 98 7 4 if expression statement miii rial india ER ERR URBE Sea NR PER eee anra dI ve 98 7 4 1 Example A id ene ee dte RI ere ere DU T 98 7 5 if expression statement else statement iaa pet ee It Ree MIR bU ee dab qa ad n6d 98 7 5 1 Example lus 99 1 5 2 lo cuin RAR 99 7 6 Switch expression statement pins nepos eia citu ier pd esae dad pedet decus ae 99 7 6 1 Example Troe tete e Pane tee rta deser decetero ertt onde 99 Jul While expression Statements quoc sdeesoda dieta c i ep po bet de Beda testa ensbpd 100 7 7 1 Example L 2 deett ciet eee eet etr ees eet i eerie ced erre ete edite 100 7 8 do statement while Expresi n iio dee su io Pla ptt oo ater Pee Opel ee acerseo nes 101 7 8 1 Example DP CET 101 7 9 for init statement expression 1 expression 2 statement ooooococnnocccoonccnnoncnonanan nns 102 7 9 1 Example ou nee ett be t debes cse tet iode Lose ALAE RS 102 7 9 2 ls end nRRPUI RT 102 7 10 break continue goto statements ae ceci oer i Ier ITA Ne Ere e eU Se CE VE d RN 102 DAL CiniV mc A A 103 T2 A etos tta eeu de Ite bns tosttetitbc tutatus ite totae e dS bes cdi 103 Contents 7 7 13 Bibliography init din 105 A 108 8 1 Linked List Pascal icsninids dal iia lata 108 5o Emked List Fortran 90 esnias vient riot ie to Eaa cid 109 8 3 Linked List C old C syntax sic scsccists cesesntewccens Secesansaversceusndeceentecoansesebeneceanscchas 110 Bobo DISCUSS Ord 111 8 4 1 A A
301. sert int char str throws StringIndexOutOfBoundsException public StringBuffer insert int boolean b throws StringIndexOutOfBoundsException public synchronized StringBuffer insert int char c throws StringIndexOutOfBoundsException public StringBuffer insert int int i throws StringIndexOutOfBoundsException public StringBuffer insert int long 1 throws StringIndexOutOfBoundsException public StringBuffer insert int float f throws StringIndexOutOfBoundsException public StringBuffer insert int double d throws StringIndexOutOfBoundsException public int length synchronized void set CharAt int index char ch throws exception StringIndexOutOfBoundsException synchronized void setLength innt newlength throws exception StringIndexOutOfBoundsException email ian chivers kcl ac uk 85 Strings Chapter 5 String toString Note again that we have many functions with the same name and different signatures There are two new concepts raised here The first is the concept of synchronised and the second of throwing an exception Let us look at each in turn Something that you may never have thought much about is multiprocessing With most computer systems there will be several processes running Type ps ef the next time you are logged onto a unix system to see what proceeses are running If you have ever used a pc or a mac you will probably have logged into a computer system whilst at the same time using netscape or
302. sing the original jdk 1 0 x style This hopefully will show some of the problems that exist with the original release and why Sun had to make changes 11 15Example 1 Bouncing Balls import java awt Simple graphics example of a bouncing ball Things to look at are the amount of flicker and the amount of time that the thread is put to sleep This is in milliseconds It is worth experimenting with this as the applet will behave differently on different systems public class graphicOl extends java applet Applet implements Runnable double x y deltax deltay double x1 300 double y12300 Thread ball public void init setBackground Color white deltax 3 deltay 3 x Math random xl y Math random yl public void start if ball nu11 Ian D Chivers email ian chivers kcl ac uk 141 Introduction to Graphics Programming ball new Thread this ball start public void stop if ball null ball stop ball null public void run for xt deltax yt deltay if x gt x1 x lt 0 deltax deltax if y gt y1 y lt 0 deltay deltay repaint try Thread sleep 1 catch InterruptedException e public void paint Graphics g g setColor Color blue g fillOval int x int y 20 20 C
303. sms in Java for exception handling try catch finally to look at a complete realistic example that highlights the power of exception handling Chapter 8 Exceptions 108 8 Exceptions Errors always occur at run time in programs that do anything useful The facilities for han dling errors have gradually improved in programming languages The concept of raising an exception and then passing control to an error handler is one that is now seen in a number of programming languages including C Ada 95 and Java Let us look at some common errors and solutions invalid input ask the user to retype the data values file not found ask the user to retype the file name numeric overflow terminate the program with a warning numeric underflow terminate the program with a warning array out of bounds terminate the program with an error message and you will all be familiar with one or more of these common errors One of the major problems in languages that do not support the concept of raising an ex ception and passing control to an error handler is that the logic of something really quite simple can be lost completely because of the additional coding complexity So we have to chose between correctness by trapping all possible errors at one extreme with code that is very difficult to understand and probable erroneous output because we have only trapped a small number of er rors with code that is relatively easy to understand
304. snscas 74 4 14 2 3 erit Me api 74 4 14 2 4 Character Subsectores 74 4 14 2 5 Character UncodebBlock 1 1 petet LER EE teh id 74 4 14 2 6 CLASS ELE 74 4 14 2 7 ClassLoadetr enia mum eie neqatequunatoaitinanda ii atte 74 4 14 2 8 enis ation oboe 74 4 14 2 9 Do ble eL 74 4 14 2 10 El E 74 4 14 2 11 Inheritable Thread Local rire cemere ette aoi 74 4 14 2 12 cupo LL 74 4 14 2 13 EL 74 4 14 2 14 D ETE da 74 4 14 2 15 n4 UE 76 4 14 2 16 lus 76 6 Contents 4 14 2 17 Package uni etude tate ai a dr ens 76 4 14 2 18 PIOCESS MM EE 76 4 14 2 19 RUN Mirate isos n TO EEEE eves RN eii 76 4 14 2 20 RuniimeP rmissiOty RN 76 4 14 2 21 Security Marager denegare qt trier E 76 4 14 2 22 MOOT ey E DE 76 4 14 2 23 Nis MM PEE ES 76 4 14 2 24 StringB lffer e ie ise eit E T betae 76 4 14 2 25 NA Igne ES 77 4 14 2 26 Thread EET TI 4 14 2 27 Thread Groups 2 net neret tpe ete eer t Er ios eerte icio rete Tene TI 4 14 2 28 Threadl ocal nms oerte be e ERR D ge e erbe eee e us ee iR TI 4 14 2 29 BN IVEDU NH TI 4 14 2 30 MOI um LER DN NO OS AN TI 4 15 E s ib TTE T EMO vProblefisss co ceso s ao e qd A inves e UHR A inluandueniaeia teu 80 5 1 The AST GS A A 80 52 Java DEDICAN TENIS DER NE 80 5 2 1 Stine Methods stilo nee tbe eiTe nio per tomo tre ia 81 5 2 1 1 String Example 1 replace 1 tritt noticed E eer
305. space or colors in arbi trary color spaces identified by a ColorSpace Component A component is an object having a graphical representation that can be displayed on the screen and that can interact with the user O lan D Chivers email ian chivers Okcl ac uk 157 Introduction to Graphics Programming Chapter 11 ComponentOrientation The ComponentOrientation class encapsulates the language sensitive orientation that is to be used to order the elements of a component or of text Container A generic Abstract Window Toolkit AWT container object is a component that can contain other AWT components Cursor A class to encapsulate the bitmap representation of the mouse cursor Dialog A Dialog is a top level window with a title and a border that is typically used to take some form of input from the user Dimension The Dimension class encapsulates the width and height of a component in inte ger precision in a single object Event Event is a platform independent class that encapsulates events from the plat form s Graphical User Interface in the Java 1 0 event model EventQueue EventQueue is a platform independent class that queues events both from the underlying peer classes and from trusted application classes FileDialog The FileDialog class displays a dialog window from which the user can select a file FlowLayout A flow layout arranges components in a left to right flow much like lines of text in a paragraph Font The Fo
306. sume that the specific heat capacity of ice and steam are identical to that of wa ter Write a program which will read in two temperatures and will calculate the energy re quired to raise or lower ice water or steam at the first temperature to ice water or steam at the second Take the freezing point of water as 273 K and its boiling point as 373 K For those happier with Celsius 0 C is 273 K while 100 c is 373 K One calorie is 4 1868 J and for the truly atavistic 1 BTU is 1055 J approximately 7 13 Bibliography Dahl O J Dijkstra E W Hoare C A R Structured Programming Academic Press 1972 This is the original text and a must The quote at the start of the chapter by Dijkstra summarises beautifully our limitations when programming and the disci pline we must have to successfully master programming Knuth D E Structured Programming with GOTO Statements in Current Trends in Pro gramming Methodology Volume 1 Prentice Hall The chapter by Knuth provides a very succinct coverage of the arguments for the adoption of structured programming and dispells many of the myths concerning the use of the GOTO statement Highly recommended email ian chivers kcl ac uk Ian D Chivers 8 Exception Handling Don t interrupt me while I m interrupting Winston Churchill Aims The primary aims of the chapter are to look generally at errors and how they can be handled in a programming language to look at the mechani
307. t public void init String s This is some text that is going n to spread over several lines n and use the control characters for An end of line as in c and c add new TextArea s 10 10 12 12Layout There are a number of layout managers in Java We look at each in turn and privide simple examples The following methods apply to all 5 layout classes add String component add the component remove component remove the component layoutContainer reshape the components in the container to meet the requirements of the BorderLayout ob ject minimumLayoutSize container return the minimum dimensions needed to lay out the components preferredLayoutSize container return the preferred dimensions needed to lay out the components 12 12 1 Panels The first thing to look at is the concept of dividing the screen up into panels We can then use the various layout managers within these panels 12 12 22 FlowLayout This is the simplest layout manager The objects are displayed from left to right in the order they are added to the screen import java awt public class c1130 extends java applet Applet public void init layout using the FlowLayout mananger Font f new Font Arial Font PLAIN 20 setFont f setLayout new FlowLayout FlowLayout LEFT add new Button QPR add new Button Arsenal email ian chivers kcl ac uk
308. t and origin A Raster object itself uses two objects to manage the pixel data a DataBuffer and a SampleModel The DataBuffer is the object that stores pixel data for the raster and the SampleModel provides the interpretation of pixel data from the DataBuffer 11 29 7 Geometries The Java 2DTM API provides several classes that define common geometric objects such as points lines curves and rectangles These new geometry classes are part of the java awt geom package For backward compatibility the geometry classes tha t existed in previous versions of the JDK software such as Rectangle Point and Polygon remain in the java awt package The Java 2D API geometries such as GeneralPath Arc2D and Rectangle2D implement the Shape interface defined in java awt Shape provides a common protocol for describing and inspecting geometric path objects A new interface Pathlterator defines methods for re trieving elements from a geometry Ian D Chivers email ian chivers kcl ac uk 171 Introduction to Graphics Programming Chapter 11 11 29 8 Fonts and Text Layout You can use the Java 2DTM API transformation and drawing mechanisms with text strings In addition the Java 2D API provides text related classes that support fine grain font con trol and sophisticated text layout These include an enhanced Font c lass and the new TextLayout class 11 29 9 Imaging The Java 2DTM API supports three imaging models The producer consumer push model pr
309. t printin s2 System out printin s3 System out printin s4 System out printin s5 s0 sl1 s2 s3 s4 s5 System out println s0 Note that in this example we have not used the import statement and have had to fully state the method name i e java lang String valueof 5 3 java lang StringBuffer This class also represents a string of characters but now the contents may be modified This means that email ian chivers kcl ac uk Ian D Chivers Chapter 5 Strings 84 it can grow in length characters can be replaced characters can be appended characters can be inserted 5 3 1 StringBuffer Methods Here are some of the more commonly used StringBufer methods Constructors Instance Methods O lan D Chivers StringBuffer StringBuffer int length StringBuffer String str public synchronized StringBuffer append Object obj public synchronized StringBuffer append String str public synchronized StringBuffer append char str public StringBuffer append boolean b public synchronized StringBuffer append char c public StringBuffer append int 1 public StringBuffer append long 1 public StringBuffer append float f public StringBuffer append double d public synchronized StringBuffer insert int Object obj throws StringIndexOutOfBoundsException public synchronized StringBuffer insert int String str throws StringIndexOutOfBoundsException public synchronized StringBuffer in
310. t the output line at the first blank character after position 60 c char byte_read destination write c Convert to character and write out The program can be run with the following command line java convert before doc after txt 9 8 Problems 1 Write a program that writes a file that contains the numbers 1 through 10 as integer val ues Examine this file with an editor What do you notice 2 Now write a program to read in these values and print them out to the screen 3 Repeat problem one but now use single precision reals 4 Repeat 2 with the file containing real numbers 5 Chapter 17 in the third edition of the Deitel book has some i o examples Have a look at those to see how to create a sequential file and read it back in O lan D Chivers email ian chivers Okcl ac uk 10 Threads A person with one watch knows what time it is a person with two watches is never sure Proverb Aims The aim of this chapter is to introduce the concepts and ideas involved in using threads in Java extends Thread implements Runnable sleep static variables synchronized priority init start stop paint update repaint yield Chapter 10 Threads 130 10 Threads The computer systems that you use runs many processes It is not uncommon to be listening to a cd downloading a file using ftp printing a file reading your mail at the same time If you are using a unix system try ps ef If y
311. tColor Color c Sets this graphics context s current color to the specified color abstract void setFont Font font Sets this graphics context s font to the specified font abstract void setPaintMode Sets the paint mode of this graphics context to overwrite the destination with this graphics context s current color abstract void setXORMode Color c1 Sets the paint mode of this graphics context to alternate between this graphics context s current color and the new specified color String toString Returns a String object representing this Graphics object s value abstract void translate int x int y Translates the origin of the graphics context to the point x y in the current co ordinate system 11 24Package java awt Graphics2D JDK 1 2 This Graphics2D class extends the Graphics class to provide more sophisticated control over geometry coordinate transformations color management and text layout This is the fundamental class for rendering 2 dimensional shapes text and images on the Java plat form All coordinates passed to a Graphics2D object are specified in a device independent coordinate system called User Space which is used by applications The Graphics2D object contains an AffineTransform object as part of its rendering state that defines how to convert coordinates from user space to device dependent coordinates in Device Space Where possible use Graphics2D in preference to Graphics 11 2241 Rendering The Rendering Pr
312. tResponse html 6147 Apr 2 1999 SingleThreadModel html 15644 Apr 2 1999 UnavailableException html 1939 Apr 2 1999 package frame html 7671 Apr 2 1999 package summary html 6194 Apr 2 1999 package tree html 10677 Apr 21 1999 package use html webpages docs api javax servlet class use 5830 Apr 21 1999 GenericServlet html 6043 Apr 21 1999 RequestDispatcher html email ian chivers kcl ac uk O Ian D Chivers Chapter 23 Servlets 278 10034 Apr 21 1999 Servlet html 9758 Apr 21 1999 ServletConfig html 7072 Apr 2 1999 ServletContext html 17706 Apr 21 1999 ServletException html 7584 Apr 2 1999 ServletInputStream html 5991 Apr 21 1999 ServletOutputStream html 10510 Apr 2 1999 ServletRequest html 10430 Apr 2 1999 ServletResponse html 4324 Apr 2 1999 SingleThreadModel html 4337 Apr 2 1999 UnavailableException html webpages docs api javax servlet http 27615 Apr 21 1999 Cookie html 36459 Apr 21 1999 HttpServlet html 33325 Apr 21 1999 HttpServletRequest html 53488 Apr 21 1999 HttpServletResponse html 21842 Apr 21 1999 HttpSession html 12208 Apr 21 1999 HttpSessionBindingEvent html 9306 Apr 21 1999 HttpSessionBindingListener html 8509 Apr 2 1999 HttpSessionContext html 13297 Apr 21 1999 HttpUtils html 1556 Apr 2 1999 package frame html 7080 Apr 21 19
313. tance class extension packages interfaces AWT Swing Java Beans Software Components Java Environments Workbenches etc Web access to data I ll be putting all sources on the web server 1 9 Coda Be prepared to devote some time to learning Java You can t gain an understanding of 50 years of program language development and an object oriented language like Java without some effort on your part Modifying existing programs is a good place to start but you have to write your own from scratch to really learn a language Think about how you learn French German etc Practice makes perfect Be patient Rome wasn t built in a day 1 10 Bibliography Deitel H M Deitel P J Java How to Program Prentice Hall 1 Edition comments This is a very well written complete coverage of the Java lan guage If you had to get just one large text then this is one to consider 1050 pages in all 3 Edition comments I bought this edition in February 2000 and it has been up dated considerably It now covers Java 2 and Swing The CD has JDK1 2 1 on it as well as Netbeans Developer 2 2 1 and Inprise nee Borland JBuilder 3 University Edition It also has coverage of JDBC servlets remote method invocation and the attempt to provide an equivalent to the STL in Java At around 30 it is very good value Also contains lots of links to Java resources available on the Web The following is a list of some of the chapters 2 Java Applications 3
314. tandardisation Aims The aims of this chapter are to provide a brief coverage of standardisation efforts imple mentation differences and future developments Chapter 28 Language Standardisation 306 28 Language Standardisation This chapter looks at standardisation efforts standard conformance implementation differ ences and future developments 28 1 Sun Sun are obviously one of the major driving forces behind Java However other companies quickly saw the potential that Java had and there was an attempt to get the language stand ardised This has had mixed success Currently Sun has pulled out of the standardisation ex ercise and there have been legal battles involving Microsoft being the most widely known The first place to start is at Sun s site They make available the Java Language Specifica tion and the second edition draft is now available for public review The draft includes all changes clarifications and amendments made to the Java programming language since the publication of the first edition of the language specification in 1996 Of particular note is the full integration of the changes made in the 1 1 release of the Java platform into the specification especially nested classes and interfaces The document is available in the fol lowing formats HTML tar Z 865K HTML zip 600K PDF 3706K PostScript tar Z 1765K PostScript zip 1267K You ve also seen what else they make available during the cou
315. ted concurrent modification of a backing object when such modification is not permissible 25 1 3 2 EmptyStackException Thrown by methods in the Stack class to indicate that the stack is empty 25 1 3 3 MissingResourceException Signals that a resource is missing 25 1 3 4 NoSuchElementException Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration 25 1 3 5 TooManyListenersException The TooManyListenersException Exception is used as part of the Java Event model to an notate and implement a unicast special case of a multicast Event Source 25 2 Bibliography email ian chivers kcl ac uk O Ian D Chivers 26 Package java awt dnd Aims The aims of this chapter are to provide a coverage of some of the the package java awt dnd Chapter 26 Package java awt dnd 292 26 Package java awt dnd This chapter looks at some of the the java awt dnd package 26 1 Package java awt dnd JDK 1 2 Drag and Drop is a direct manipulation gesture found in many Graphical User Interface sys tems that provides a mechanism to transfer information between two entities logically asso ciated with presentation elements in the GUI Normally driven by a physical gesture of a human user using an appropriate input device Drag and Drop provides both a mechanism to enable continuous feedback regarding the possible outcome of any subsequent data trans fer to the user during navigation over th
316. terruptedException e public void actionPerformed ActionEvent e repaint public static void main String args bean01 joanbean new bean01 JFrame app new JFrame Bean test app getContentPane add joanbean BorderLayout CENTER app addWindowListener new WindowAdapter public void windowClosing WindowEvent e System exit 0 email ian chivers Q kcl ac uk O Ian D Chivers Chapter 15 JavaBeans 232 app setSize 400 400 app show Note that the first line of the program is a package statement We put classes into a package when working with beans There is also an additional compilation option required and this would be in the above case javac d bean01 java where is the current directory The development environment is set up to create a subdi rectory based on your package name In this case you will end up with the compiled class file in jbeanOl After successful compilation we then need to create the Java Archive File or jar file You can put more than one bean into a jar file We do this with the following command jar cfm bean01 jar manifest tmp jbeanO1N and note again that everything will refers to this sub directory The manifest file is required and I ve followed the Sun naming convention calling it mani fest tmp The manifest file from this example is given below Main Class jbean01 bean01 Name beanOl class Java Bean True
317. test standard is 1995 Java Exact date not well defined Hopefully the standardisation effort will make life easier 2 15 Language Features It is illuminating to look at the languages from the viewpoint of their features and function ality 2 45 4 Independent Compilation The ability to break a problem down into parts and work on one part at a time No checking between compilation units 2 45 2 Separate Compilation As above with checking across compilation units Major step forward in the construction of more complex programs Lint helps out with C Forcheck is useful for Fortran 66 and 77 programmers 2 15 3 Concrete Data Types The ability for the user to define data types that mapped directly onto their problem A ma jor step forward User has to know about the implementation however 2 15 4 Abstract Data Types The twin concept of data types and procedures that manipulated the data Hiding the inter nals from the calling routine 2 45 5 Dynamic arrays Arrays that are allocated dynamically at run time 2 45 6 Numeric and General Polymorphism Numeric Polymorphism In the simplest case the ability to have so called mixed mode arithmetic expressions e g mix integers and reals both of one or more underlying representations without casting be email ian chivers Q kcl ac uk O Ian D Chivers Chapter 2 An Introduction to Programming Languages 30 and Object Oriented Programming tween one type and another The explicit type
318. text and imaging capabilities of the Abstract Windowing Toolkit AWT enabling the development of richer user interfaces and new types of Java applications Along with these richer graphics font and image APIs the Java 2D API supports enhanced color definition and composition hit detection on arbitrary geometric shapes and text and a uniform rendering model for printers and display devices The Java 2D API also enables the creation of advanced graphics libraries such as CAD CAM libraries and graphics or imaging special effects libraries as well as the cre ation of image and graphic file read write filters When used in conjunction with the Java Media Framework and other Java Media APIs the Java 2D APIs can be used to create and display animations and other multimedia presenta tions The Java Animation and Java Media Framework APIs rely on the Java 2D API for rendering support 11 29 41 Enhanced Graphics Text and Imaging Early versions of the AWT provided a simple rendering package suitable for rendering common HTML pages but not full featured enough for complex graphics text or imaging As a simplified rendering package the early AWT embodied specific cases of more general rendering concepts The Java 2DTM API provides a more flexible full featured rendering package by expanding the AWT to support more general graphics and rendering operations O Ian D Chivers email ian chivers Okcl ac uk 169 Introduction to Graphics Program
319. th the development of Smalltalk Provides a good introduction if that is possible with the written word of the capabilities of Smalltalk Goos and Hartmanis Eds The Programming Language Ada Reference Manual Springer Verlag e The definition of the language Gosling J Yellin F The Java Team The Java API Volumes I and II Addison Wesley e Volume I looks at the core packages and Volume II looks at the Window Toolkit and Applets I find the pricing a bit much at just under 40 uk pounds a book Griswold R E Poage J F Polonsky I P The Snobol4 Programming Language Prentice Hall e The original book on the language Also provides some short historical material on the language Griswold R E Griswold M T The Icon Programming Language Prentice Hall e The definition of the language with a lot of good examples Also contains infor mation on how to obtain public domain versions of the language for a variety of machines and operating systems Hoare C A R Hints on Programming Language Design SIGACT SIGPLAN Symposium on Principles of Programming Languages October 1973 e The first sentence of the introduction sums it up beautifully would like in this paper to present a philosophy of the design and evaluation of programming lan O Ian D Chivers email ian chivers kcl ac uk 43 An Introduction to Programming Languages Chapter 2 and Object Oriented Programming guages which I have adopted and developed over a number
320. the Fortran 90 and or C courses the examples will look very familiar class c0601 public static void main String args float sum float 0 0 average float 0 0 float rainfall 1 2 3 4 5 6 7 8 9 10 11 12 int month System out println Rainfall values are for month 0 month lt 12 month System out printlin rainfall month for month 0 month lt 12 month sum sum rainfall month average sum 12 System out print Average is System out printin average ct cl Let us look more closely at some of the statements in this program float sum float 0 0 average float 0 0 This statement declares the variables sum and average to be of type float and it gives them initial values of 0 0 Remember that real constants are of type double by default and as Java 1s strongly type we must cast to float float rainfall 1 2 3 4 5 6 7 8 9 10 11 12 This declares the array rainfall to be of type float rainfall is an array of float We then as sign initial values for the elements of the array The values 1 through 12 have been chosen to make it easy to see whether the calculations give the correct results The size of the array is worked out from the number of elements between the brackets for month 0 month lt 12 month System out printlin rainfall month This is a simple for loop in Java It prints out each element of the array on a new line
321. the JDK software or when they are mathematically or programmatically generated The Java 2D API does not currently support built in or mathematically generated fonts but 1t does enable the programmatic definition of entire fonts through their glyph set Each glyph can in turn be defined by a Shape that consists of line segments and curves Many fonts of particular styles and sizes can be deriv ed from a single glyph set 11 29 4 Setting Up the Graphics2D Context To configure the Graphics2D context for rendering you use the Graphics2D set methods to specify attributes such as the RenderingHints Stroke Paint clipping path Composite and Transform 11 29 5 Rendering Graphics Primitives Graphics2D provides rendering methods for Shapes Text and Images draw strokes a Shape s path using the Stroke and Paint objects in the Graphics2D context fill fills a Shape using the Paint in the Graphics2D context drawString renders the specified text string using the Paint in the Graphics2D context drawImage renders the specified image To stroke and fill a shape you must call both the draw and fill methods Graphics2D also supports the draw and fill methods from previous versions of the JDK software such as drawOval and fillRect 11 29 6 Managing and Manipulating Rasters A BufferedImage object uses a Raster to manage its rectangular array of pixel data The Raster class defines fields for the image s coordinate system width heigh
322. the deficien cies of Pascal in a straightforward way From what I ve seen of the draft standards it will be a powerful and expressive language Standard versions of the language look like being quite expensive and it is unlikely that we would be able to make available a compiler on any platform given the proposed cuts in ex penditure by the various government funding bodies 2 22 The OO Approach We will look at two approaches here The work of Meyer and Rumbaugh et al are both well regarded and we will cover both briefly 2 22 1 Meyer s Approach Meyer in his first edition dated 1988 identified seven steps that lead towards object ori ented solutions These were object based modular structure systems are modularised on the basis of the data structures data abstraction objects should be described as implementations of abstract data types automatic memory management unused objects should be deallocated by the underlying language systems without programmer intervention classes every non simple type is a module and every high level module is a type inheritance a class may be defined as an extension of restriction of another polymorphism and dynamic binding program entities should be permitted to refer to objects of more than one class and operations should be permitted to have different realisations in different classes multiple and repeated inheritance it should be possible to declare a class
323. tic event like button pressed 13 5 Example 1 This is taken from the Java Swing book It is in several files CCPHandler java A Cut Copy and Paste event handler Nothing too fancy just define some constants that can be used to set the actionCommands on buttons XA A A X import java awt event public class CCPHandler implements ActionListener public final static String CUT cut public final static String COPY copy public final static String PASTE paste public void actionPerformed ActionEvent e String command e getActionCommand if command CUT we can do this since we re comparing statics System out println Got Cut event else if command COPY System out printin Got Copy event else if command PASTE System out println Got Paste event This is the second file LnFListener java A listener that can swing the look and feel of a frame based on the actionCommand of an ActionEvent object Supported look and feels are email ian chivers kcl ac uk Ian D Chivers Chapter 13 Events 206 Metal Windows id Motif i import java awt import java awt event import javax swing public class LnFListener implements ActionListener Frame frame public LnFListener Frame f frame f public void actionPerformed ActionEvent e String lnfName null if
324. tic and double buffering 145 11 19 Example 6 Loading jpg images static display ooooconnnncccnonccinonccononaconancnnnncnnnno 147 8 Contents 11 20 Example 7 Loading image simple scaling eene 147 11 21 Exanpl i gt Movi g Image A uide IR 148 11 22 Basic Drawing Methods eee dienten et gea eh caia Do Ee ea eR seneastdsderaceauenecaie 149 11 22 1 Lines e drawline x1 y 1 32 y2 ec eret tota eov pe ce aedis 149 11 222 Rectangles g drawRect xstart ystart width height PSUNSUIO QAI 149 11 223 Rounded Rectangles g drawRoundRect xstart ystart w h xcurve ycurve 150 11 22 4 3D Effects g draw3Drect X y W H TUE ooooonoocnnonnnnococnnoconnnccnonononnccononocnnnc ennt enne 151 11 22 5 POLY OS PN 151 11 22 6 Ovals g drawOval x y w h and g fillOval x y w h eene 152 11 22 7 Arcs g drawArc x y w h start end and g fillArc x y w h s e 0ooooooconocccooccconacononccnnnoss 152 11 22 8 Colour Colorines eR ee ees 152 11 22 9 Texts and Fonts it e eerte tte dere eene se Ie Erde aaa 153 E23 AWT IOR qur cc Ea aay ite ladies Sade shots Saedat annette ated T R ES 154 11 23 1 Interface lt SumM ary tien tne leto de eene ORE E atone 155 11 23 2 Class Summary nnne PR RR ee etal ea dee deep ees 156 11 23 3 Exception Summary aseetan eane TEO 160 11 23 4 Error Summary i RI Re isa 160 11 23 5 Java awt Graphics ecrit p reet ni t tte a e
325. tion e System out printin String index too large We next have the try f catch block In the event of an error control will pass to the catch statement and the statements following will be executed In this case in the event of an StringIndexOutOfBounds error the message String index too large will appear Within the try catch block we have code which inserts one string within another and then prints out the value of the new string Notice the object oriented way of doing this where we have the binding of StringBuffer object in each case s1 with the insert action The the StringBuffer object s1 will grow successfully in size until we try providing a start ing point for the insertion that is outside of the current size of sl Ian D Chivers email ian chivers kcl ac uk 87 Strings Chapter 5 This program highlights quite clearly the different way of thinking required when we ap proach things from an object oriented viewpoint 5 3 1 2 StringBuffer Example 2 throwing an exception and splat import java lang class c0508 public static void main String args StringBuffer sl new StringBuffer this is the base string StringBuffer s2 new StringBuffer insert this System out printin sl System out printin s2 sl insert 1 s2 System out printin s1 sl insert 10 s2 System out printin s1 sl insert 20 s2 System out printin s1 sl insert 999999 s2
326. tries or see yourself working with real time embed ded systems then this is certainly a language to consider looking at 2 200 Java Java is a recent OO language It is unusual in that it is the product of one company Sun rather than the subject to formal language standardisation like the majority of the other lan guages covered in this chapter It is hoped that it will pass out of Sun s hands in the near fu ture into the mainstream of language standardisation Freely available if you have internet access IBM have taken it on board in a big way and so have Microsoft They both realise the potential earning capacity of Java and the internet Due to long file names and multithreading requirements needs operating systems like Win dows 95 and above Ian D Chivers email ian chivers Okcl ac uk 35 An Introduction to Programming Languages Chapter 2 and Object Oriented Programming 2 21 Other Languages There are languages that offer limited support for OOP The two that follow fit into this cat egory I don t have completely up to date information on what is likely to be in the Modula 2 standard at this time 2 21 1 Fortran 90 and Fortran 95 Through the functionality provided via user defined data types and modules it offers support for object based programming See Dupee s MSc thesis for a good coverage of what Fortran 90 has to offer here 2 21 2 Modula 2 The original language was a major advance over Pascal It corrected many of
327. ts on operating systems and programming langauges that support real time programming Ada 95 and Modula 2 offer support in this area Barnes J Programming in Ada 95 Addsion Wesley e The chapter on tasking provides a description of the way that Ada handles multitasking Christian K A Guide to Modula 2 Springer Verlag e The chapter on coroutines is worth looking at Deitel H M An Introduction to Operating Systems Addison Wesley e There are several chapters that look at the whole area of multi processing asyn chronous and snychronous processes Easy read Very comprehensive bibliogra phy The following faq is excellent http www best com bos threads faq Searching Amazon will reveal a fascinating spread of books on threads Try it O lan D Chivers email ian chivers Okcl ac uk 11 Introduction to Graphics Programming A picture paints a thousand words anon Aims The aim of this chapter is to introduce the concepts and ideas involved in using the facilities offered in Java for graphical output The coverage looks at what was avail able in the original 1 0 x JDK and the facilities in later releases There is a coverage of Basic graphics concepts vector vs raster graphics pixels bit maps gif vs jpg fonts coordinate space user space screen resolution colour and colour models scan ning integer arithmetic real arithmetic flicker double buffering se lective erasure device contexts clipping ren
328. ty in the behaviour of programs that use threads public class thread08 extends Thread public static void main String args thread08 tl new thread08 thread08 t2 new thread08 tl start t2 start public void run for System out printin Thread currentThread getName Thread yield 10 8 Example thread priority This example looks at using threads and providing them with priorities public class thread09 extends Thread public static void main String args thread09 tl new thread09 thread09 t2 new thread09 tl setPriority 10 tl start t2 setPriority 1 t2 start public void run for System out printin Thread currentThread getName Thread yield email ian chivers kcl ac uk Ian D Chivers Chapter 10 Threads 136 10 9 Problems The important thing with these examples is to see them actually running See if you can predict what the output will be The next thing is to try all of the examples out on another platform Do you think that you will get the same results Compare the actual output for each of the examples on the various systems that you have access to Chapter 15 of the Deitel book has a coverage of multithreading They have a number of ex amples including one implementing a circular buffer 10 10Bibliography The two main types of sources are tex
329. uage or in a mixture of the Java programming language and Java Native Interface JNI native meth ods The JDBC web site maintains a list of vendors with drivers currently available or un der development The latest SDK includes the JDBC ODBC Bridge This JDBC technology based driver makes most Open Database Connectivity ODBC drivers available to programmers using the JDBC API The JDBC ODBC Bridge Guide describes the current status of this soft ware Drivers Types of JDBC technology drivers JDBC technology drivers fit into one of four categories 1 A JDBC ODBC bridge provides JDBC API access via one or more ODBC drivers Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver Hence this kind of driver is generally most appropriate when automatic installa tion and downloading of a Java technology application is not important For in formation on the JDBC ODBC bridge driver provided by Sun see JOBC ODBC Bridge Driver 2 A native API partly Java technology enabled driver converts JDBC calls into calls on the client API for Oracle Sybase Informix DB2 or other DBMS Note that like the bridge driver this style of driver requires that some binary code be loaded on each client machine 3 A net protocol fully Java technology enabled driver translates JDBC API calls into a DBMS independent net protocol which is then translated to a DBMS pro tocol
330. uble y1 3005 Thread ball public void init i mathackgrcund Color hite Beltaxe Math random doltay Hath nanda zaHath random kl v Hsth random wl MIL MM a a Jide hera kn mii aree bun Microsoft J 18 3 Working practices Work is directory based Do not mix code in one directory I have developed examples in one directory as I started learning Java using the Sun JDK This working habit is a disaster with both Microsoft Visual J and IBM VisualAge for Java 18 4 Documentation Map Below is an overview of what you ll find in the Visual J documentation What s New Highlights the new features in Visual J Getting Started Explains how to get up and running with Visual J User s Guide Shows how to use Visual J Programmer s Guide Provides in depth information on using the Windows Foundation Classes for Java WFC and discusses other advanced programming techniques WEC and Java Reference Contains detailed reference information for the WFC API and controls the Java API and the Java Language Specification email ian chivers kcl ac uk Ian D Chivers Chapter 18 Microsoft Visual J 244 Visual J Reference Contains comprehensive reference information for the Vi sual J Code Model extensibility conditional compilation reserved words and compiler errors Samples Provides a rich collection of ready to run samples that illustrate key technologies Located elsewhere in the MS
331. ulations with F meaning finite number we have the following x y x y xy F 0 0 9 NaN F 9 00 x 0 0 0 0 NaN NaN 9 F 0 NaN 0 9 NaN NaN Floating point division and remainder can produce both NaN and infinities without raising an exception Some of the major differences between IEEE 754 1985 and the Java variant are nonstop arithmetic Java will not signal the IEEE conditions of invalid opera tion division by zero overflow underflow or inexact extended formats these are optional rounding Java rounds towards the nearest which is the IEEE default but it does not offer user selectable rounding Java is in a state of flux in this area and this is covered in more depth in chapter 25 The following program provides an example of the use of each real data type supported in Java class c0402 public static void main String args float f 1 1f double fod Lib System out printl System oul t print Let us look at each statement in turn class c0402 Ian D Chivers email ian chivers kcl ac uk 63 Arithmetic and Expressions in Java Chapter 4 Every program has to be a class public static void main String args Standard program statement float f 1 1f There are two kinds of real numbers in Java One is float The variable f is of type float and has an initial value of 1 1 Note that this real literal has f appended Real constants are dou ble by default You have t
332. un long lasttime O Ian D Chivers email ian chivers Okcl ac uk 185 Introduction to Graphics Programming Chapter 11 try if images null System out printin Making images makelmages 4 if music null music loop lasttime System currentTimeMillis while time_to_die int i long now System currentTimeMillis long deltaT now lasttime boolean active false Dimension d size for 1 0 i lt images length 1 Bouncelmage img images i img step deltaT if img Vy gt 05 img Vy gt 05 img y img width lt d height 10 4 active true if active amp amp images length 0 for i 0 i lt images length i Bouncelmage img images i img Vx float Math random 4 0f 0 125f img Vy float Math random 4 0f 0 2f img Vr 0 05f float Math ran dom y dE if sounds 3 null sounds 3 play repaint lasttime now LEY d Thread sleep 100 catch InterruptedException e return finally email ian chivers Q kcl ac uk O Ian D Chivers Chapter 11 Introduction to Graphics Programming if music null music stop public void init Dimension d size if d width lt 100 d height lt 100 resize 500 300 public void start time_to_die false new Thread this start public void stopi time_to_die
333. ut Nothing s Sign Bit for more details Subnormals which permit gradual underflow fill the gap between 0 and the smallest nor mal number Simply stated underflow occurs when the result of an arithmetic operation is so small that it is subject to a larger than normal rounding error when stored The existence of subnormals means that greater precision is available with these small numbers than normal numbers The key features of gradual underflow are When underflow does occur there should never be a loss of accuracy any greater than from ordinary roundoff The operations of addition subtraction comparision and remainder are always exact Algorithms written to take advanage of subnormal numbers have smaller error bounds than other systems If x and y are within a factor of 2 then x y is error free which is used in a num ber of algorithms that increase the precision at critical regions The combination of postive and negative zero and subnormal numbers means that when x and y are small and x y has been flushed to zero the evaluation of Ze can be flagged and located Certain arithmetic operations cause problems including 0 oo 0 0 Vx when x lt 0 and the support for NaN handles these cases The support for positive and negative infinity allows the handling of x 0 when x is non zero and of either sign and the outcome of this means that we write our programs to take the appropriate action In some cases this would mean recalcul
334. vide Drag Under feedback effects based upon the operation s supported and the data type s involved The gesture itself moves a logical cursor across the GUI hierarchy intersecting the geome try of GUI Component s possibly resulting in the logical Drag cursor entering crossing and subsequently leaving Component s and associated DropTarget s The DragSource object manifests Drag Over feedback to the user in the typical case by animating the GUI Cursor associated with the logical cursor DropTarget objects manifest Drag Under feedback to the user in the typical case by ren dering animations into their associated GUI Component s under the GUI Cursor The determination of the feedback effects and the ultimate success or failure of the data transfer should one occur is parameterized as follows By the transfer operation selected by the user and supported by both the DragSource and DropTarget Copy Move or Reference link By the intersection of the set of data types provided by the DragSource and the set of data types comprehensible by the DropTarget When the user terminates the drag operation normally resulting in a successful Drop both the DragSource and DropTarget receive notifications that include and result in the type negotiation and transfer of the information associated with the DragSource via a Transferable object 26 2 Bibliography Ian D Chivers email ian chivers kcl ac uk 27 IEEE Arithmetic Can you d
335. vided at sorted set creation time Ian D Chivers email ian chivers kcl ac uk 287 Package java util Chapter 25 25 1 2 Class Summary 25 1 2 1 AbstractCollection This class provides a skeletal implementation of the Collection interface to minimize the effort required to implement this interface 25 1 2 2 AbstractList This class provides a skeletal implementation of the List interface to minimize the effort re quired to implement this interface backed by a random access data store such as an array 25 1 2 3 AbstractMap This class provides a skeletal implementation of the Map interface to minimize the effort required to implement this interface 25 1 2 4 AbstractSequentialList This class provides a skeletal implementation of the List interface to minimize the effort re quired to implement this interface backed by a sequential access data store such as a linked list 25 1 2 5 AbstractSet This class provides a skeletal implementation of the Set interface to minimize the effort re quired to implement this interface 25 1 2 6 ArrayList Resizable array implementation of the List interface 25 1 2 7 Arrays This class contains various methods for manipulating arrays such as sorting and searching 25 1 2 8 BitSet This class implements a vector of bits that grows as needed 25 1 29 Calendar Calendar is an abstract base class for converting between a Date object and a set of integer fields such as YEAR MONTH
336. w new FileCopyException FileCopy destination is not a file dest_name else File parentdir parent destination file if parentdir exists throw new FileCopyException FileCopy destination directory doesn t exist dest name if parentdir canWrite throw new FileCopyException FileCopy destination directory is unwriteable dest name If we ve gotten this far then everything is okay we can copy the file source new FileInputStream source file destination new FileOutputStream destination file buffer new byte 1024 while true bytes read source read buffer if bytes read 1 break destination write buffer 0 bytes read O Ian D Chivers email ian chivers Okcl ac uk 115 Exceptions Chapter 8 No matter what happens always close any streams we ve opened finally if source null try source close catch IOException e if destination null try destination close catch IOException e 3 File getParent can return null when the file is specified without a directory or is in the root directory This method handles those cases private static File parent File f String dirname f getParent if dirname null if f isAbsolute return new File File separator else return new File System getProperty user dir
337. wing html file runs the first Deitel servlet example Fig 19 6 HTTPGetServlet html gt lt HTML gt lt HEAD gt lt TITLE gt Servlet HTTP GET Example lt TITLE gt lt HEAD gt lt BODY gt lt FORM ACTION http localhost 8080 servlet HTTPGetServlet METHOD GET gt lt P gt Click the button to have the servlet send an HTML document lt P gt lt INPUT TYPE submit VALUE Get HTML Document gt lt FORM gt lt BODY gt lt HTML gt 23 2 Package java servlet 23 2 1 Interfaces RequestDispatcher Servlet ServletConfig ServletContext ServletRequest ServletResponse Single ThreadModel 23 2 2 Classes GenericServlet ServletInputStream ServletOutputStream 23 2 3 Exceptions ServletException UnavailableException 23 3 Package java servlet http 23 3 1 Interfaces HttpServletRequest HttpServletResponse HttpSession O Ian D Chivers email ian chivers Okcl ac uk 281 Servlets Chapter 23 HttpSessionBindingListener HttpSessionContext 23 3 2 Classes Cookie HttpServlet HttpSessionBindingEvent HttpUtils 23 4 Package java servlet jsp 23 4 4 Interfaces HttpJspPage JspPage 23 4 Classes JspEngineInfo JspFactory JspWriter PageContext 23 4 3 Exceptions JspException JspTagException 23 5 Package java servlet jsp tagtext 23 5 1 Interfaces BodyTag Tag 23 5 2 Classes BodyContent BodyTagSupport TagAttributeInfo TagData TagExtraInfo TagInfo TagLibraryInfo Tag
338. wing table gives the distance in MKm from the sun to the planets in the solar system mercury 57 9 venus 108 2 earth 149 6 mars 227 9 jupiter 7118 3 saturn 1427 0 email ian chivers kcl ac uk Ian D Chivers Chapter 4 Arithmetic and Expressions in Java 78 uranus 2869 6 neptune 4496 6 pluto 5900 0 Use this information to find the greatest and least time taken to send a message from the earth to the other planets Assume that all orbits are in the same plane and circular if it was good enough for copernicus its good enough for this example For all practical purposes the speed of light in a vacuum is a constant and therefore a good candidate for a const statement Use it 4 Write a program to calculate the period of a pendulum Use the following formula t 2 pi sqrt length 9 81 The length is in metres and the time is in seconds Use a length of 10 0 metres Use single precision throughout PI is built into Java Where would you expect it to be So is square root 5 Repeat the above using double precision throughout 6 Base conversion The following is a complete program that looks at base conversion What output do you expect class c0422 public static void main String args float x1 x2 x3 x4 x5 x1 float 1 0 x2 float 0 1 x3 float 0 01 x4 float 0 001 x5 float 0 0001 System out println x1 System out println x2 System out println x3 System out printin x4 System out printin
339. x5 7 Rewrite the above program in a language that you already know Do the results agree 8 Modify the base conversion program to use double precision What do expect the ansers to be 9 Expression equivalence In mathematics the following expressions are equivalent x y x y xty x x y y Write a Java program to evaluate these three expressions with x 1 002 and y 1 001 There is no exponentiation operator in Java you have to use the pow function Do the three expressions give the same results Why do you think that is 10 Rewrite the above in a another programming language Do the results agree What about Excel 11 If you have a pc with Java installed repeat the above examples on that system O Ian D Chivers email ian chivers Okcl ac uk 5 Strings Don t Panic Douglas Adams The Hitch Hiler s Guide to the Galaxy Aims The aims are to introduce the String object to look at some of the implications of Strings being objects rather than a primitive data type to look at the functions provided within Java for the manipulation of Strings Chapter 5 Strings 80 5 Strings This chapter looks at strings in Java Where characters are a built in primitive type strings are fully blown objects This means that there are some very important differences between the way we think of strings in older programming languages and Java 5 1 The basics There are two kinds of string objects in Java The
340. xpects them in the first place The Sun version I use ex pects them in the second I can t find them at all within Microsoft J The following is a complete list of what is in Swing 14 3 1 javax accessibility Support for people who have difficulty using the traditional user interface methods i e key board mouse screen 14 3 2 javax swing The major part of Swing 14 3 3 javax swing border Fancy borders 14 3 4 javax swing colorchooser Colour access 14 3 5 javax swing event Event handling 14 3 6 javax swing filechooser File access 14 3 7 javax swing pending Stuff waiting to be formally released 14 3 8 javax swing plaf Pluggable look and feel 14 3 9 javax swing table Table support 14 3 10 javax swing text Text manipulation 14 3 11 javax swing text html Html support 14 3 12 javax swing tree Tree handling 14 3 13 javax swing undo Undoable operation support 14 4 Enter Microsoft Stage Left As developments were taking place coordinated by Sun Microsoft set off on their own An outcome of their work was AFC or Application Foundation Classes This was intended to do very similar things to Swing and worked with the 1 0 2 release The two parts to it are email ian chivers Okcl ac uk O Ian D Chivers Chapter 14 Swing 216 UI the user interface component FX the classes for control of graphics etc Legal battles have been taking place If you have Microsoft Visual J then you can see what Microsoft h
341. xpression 2 is evaluated after each loop and is generally used to modify the for loop con trol variable 7 9 1 Example 1 This complete program illustrates the above class c0707 public static void main String args float x 1 2 3 4 5 6 7 8 9 10 int i System out printin Numbers are for is0 i lt 10 itt System out println x i 7 9 2 Example 2 class c0708 public static void main String args for System out printin Hello world What happens here 7 10 break continue goto statements The break statement can only occur within a switch or loop for do or while Note how ever that you can only break from a single loop If it is necessary to terminate an action within nested loops then the break won t do what we want The continue statment only makes sense with a loop Control passes immediately to the ap propriate statement depending on what type of loop we are in O lan D Chivers email ian chivers Okcl ac uk 103 Control Structures Chapter 7 Statements may be labelled and we can use the break statement to jump to an appropriate point in the code There is no goto statement in Java The following is a complete program that illustrates the use of all three statements Type the program in and run it to see what happens class c0710 public static void main String args int 3 0 goto2 for gotol for 57 acp System
342. y are objects of one of the following two classes java lang String java lang StringBuffer The first is read only The second can be modified Let us look at the String class and asso ciated methods first 5 2 java lang String Whilst Strings are objects they can be created in three ways by enclosing the text in marks by using and on two strings to create a new string explcitly using new as with objects The following program illustrates all three class c0501 public static void main String args int 11 12 13 14 String sl This is a string String s2 and this is another String s3 String s4 new String il sl length i2 2s2 length i4 s4 length System out printin il System out printin i2 System out printin i4 s3 sl s2 i3 s3 length System out printin i3 System out printin s1 System out printin s2 System out printin s3 System out printin s4 Let us look at each line in turn String sl This is a string String s2 and this is another Ian D Chivers email ian chivers kcl ac uk 81 Strings Chapter 5 It is important to distinguish between declaration and creation With our knowledge of convential programming languages we tend not to think very much about this With object oriented programming we have to think about it all the time These two statements declare s and s2 to be of type String and they also c
343. ywhere capability to resuable component development There is considerable interest in JavaBeans because of the platform neutrality of the devel oped code Sun also provide mechanisms to migrate ActiveX OLE COM to JavaBeans Sun and Microsoft and battling this one out and there is little love lost between them Watch this space as they say 2 25 Coda There is a lot that John Backus has to be proud of He achieved a lot with Fortran As we shall see Fortran is still the language of first choice for the majority of numeric based prob lem solving There is a lot of very well written code in Fortran and we find both commer cial and public domain numeric libraries available for most platforms Wirth has a lot to be proud of too with the Algol family of languages Algol Algol W Pascal Modula Modula 2 Oberon Oberon 2 The sad thing that is that whilst abandoning the previous language enabled successor languages to be well designed and compact there was a lot of effort required in moving production code from older languages to their succes sors Knowledge of one of the more recent languages Modula 2 or Oberon in this family is a worthwhile investment C and C have a considerable amount of code written in them C represents a very ma jor advance over C correcting some of the program correctness problems that arise in C from array subscript checking pointer manipulation type checking and optimisation prob email ian chivers kcl a

Download Pdf Manuals

image

Related Search

Related Contents

熱中症・ インフルエンザ警告計  Manuel d`utilisation  nina Cappuccino/取説  

Copyright © All rights reserved.
Failed to retrieve file