Java – Objects First

:
An Introduction to Computer Programming using Java and BlueJ

Copyright 2008-10 Rick Gee

Table of Contents
Table of Contents ................................................................................................................................... i Preface to the reader.............................................................................................................................. 1 To students ........................................................................................................................................ 1 To teachers ........................................................................................................................................ 3 To everyone ....................................................................................................................................... 5 Acknowledgements ............................................................................................................................... 6 Notes ..................................................................................................................................................... 7 Chapter 0 – Introduction ....................................................................................................................... 9 Learning objectives ........................................................................................................................... 9 What is computer science?................................................................................................................ 9 Hardware ........................................................................................................................................... 9 Software .......................................................................................................................................... 10 Programming languages.................................................................................................................. 11 Summary ......................................................................................................................................... 12 Chapter 1 – Classes and objects – identity, state, and behaviour ........................................................ 13 Learning objectives ......................................................................................................................... 13 Introduction ..................................................................................................................................... 13 Definitions....................................................................................................................................... 13 Classes............................................................................................................................................. 15 The Student class ............................................................................................................................ 17 Class diagrams ............................................................................................................................ 17 Datatypes..................................................................................................................................... 19 The Professor class ......................................................................................................................... 20 Tradeoffs of storing the name as one field versus several .............................................................. 21 Behaviours ...................................................................................................................................... 23 A first look at Java .......................................................................................................................... 23 Documentation ............................................................................................................................ 25 Programming Style – documentation.......................................................................................... 25 Class declaration ......................................................................................................................... 26 Programming Style – class names .............................................................................................. 26 Instance variables ........................................................................................................................ 26 Programming Style – instance variables ..................................................................................... 27 Constructor(s) ............................................................................................................................. 27 Programming Style – constructors .............................................................................................. 29 Getters and setters ....................................................................................................................... 30 Programming Style – getters and setters ..................................................................................... 31

toString........................................................................................................................................ 31 Programming Style – toString .................................................................................................... 33 Creating another class, the College ................................................................................................. 33 Summary ......................................................................................................................................... 35 Exercises ......................................................................................................................................... 36 Chapter 2 – Introducing BlueJ ............................................................................................................ 37 Learning objectives ......................................................................................................................... 37 Introduction ..................................................................................................................................... 37 BlueJ ............................................................................................................................................... 37 Creating a new project ................................................................................................................ 38 Virtual machines and bytecode ................................................................................................... 41 Testing the Student class ............................................................................................................. 42 Inspecting an object .................................................................................................................... 43 Unit testing - definition ............................................................................................................... 46 Unit testing with BlueJ................................................................................................................ 47 Unit testing – the results ............................................................................................................. 52 Smoke testing .................................................................................................................................. 53 The Professor class ......................................................................................................................... 54 The College class ............................................................................................................................ 54 Summary ......................................................................................................................................... 54 Exercises ......................................................................................................................................... 55 Chapter 3 – Making decisions............................................................................................................. 59 Learning objectives ......................................................................................................................... 59 The if statement............................................................................................................................... 59 Boolean algebra .......................................................................................................................... 59 Boolean algebra – an example .................................................................................................... 61 A revised toString method .......................................................................................................... 62 Using the Java documentation ................................................................................................ 62 Programming style – if statements .............................................................................................. 64 Simpler tests .................................................................................................................................... 65 More complicated tests ................................................................................................................... 66 Summary ......................................................................................................................................... 69 Exercises ......................................................................................................................................... 70 Chapter 4 – Inheritance ....................................................................................................................... 73 Learning objectives ......................................................................................................................... 73 Abstract classes ............................................................................................................................... 73 The Person class .......................................................................................................................... 74 toString in an abstract class..................................................................................................... 75 The Person class, continued ........................................................................................................ 77 The Student class – a derived class ............................................................................................. 78 The Professor class ..................................................................................................................... 79 Summary ......................................................................................................................................... 79 Exercises ......................................................................................................................................... 80 Chapter 5 – An Address class.............................................................................................................. 83 Learning objectives ......................................................................................................................... 83

ii

Introduction ..................................................................................................................................... 83 Adding an address ........................................................................................................................... 83 The Address class ........................................................................................................................ 84 The Address class – the code ...................................................................................................... 85 The Address class – the code – in detail ..................................................................................... 86 The Address class – getters and setters ....................................................................................... 88 Person uses Address .................................................................................................................... 88 Making copies (cloning) ............................................................................................................. 89 The Address class – unit testing .................................................................................................. 91 Testing Address cloning .............................................................................................................. 92 The reserved word null ............................................................................................................... 92 The College class and addresses ..................................................................................................... 93 Summary ......................................................................................................................................... 94 Exercises ......................................................................................................................................... 95 Chapter 6 – Dates ................................................................................................................................ 97 Learning objectives ......................................................................................................................... 97 Introduction ..................................................................................................................................... 97 How old is a person? ....................................................................................................................... 97 Dates ........................................................................................................................................... 98 Details about calendars ............................................................................................................... 98 The MyDate class – a simplification .......................................................................................... 99 Programming style – a skeleton for a class ........................................................................... 100 Primitive types ...................................................................................................................... 100 Digression ............................................................................................................................. 101 The MyDate class – the code .................................................................................................... 101 The MyDate class – unit tests ................................................................................................... 103 Using MyDate objects............................................................................................................... 104 Simplifying the class diagram ................................................................................................... 105 Retirement of a professor .......................................................................................................... 106 Retirement of a professor - unit tests ........................................................................................ 107 Programming style – common errors ............................................................................................ 109 Summary ....................................................................................................................................... 110 Exercises ....................................................................................................................................... 111 Chapter 7 – Collections, part 1 ......................................................................................................... 113 Learning objectives ....................................................................................................................... 113 Life is complicated ........................................................................................................................ 113 Collections the college model contains......................................................................................... 114 The Java Collections Framework.................................................................................................. 116 A set .............................................................................................................................................. 117 A collection of professors ............................................................................................................. 118 HashSet ......................................................................................................................................... 119 Generic collections........................................................................................................................ 120 Programming style .................................................................................................................... 121 HashSet<Professor>...................................................................................................................... 121 The equals method .................................................................................................................... 122 The hashCode method............................................................................................................... 123

iii

How many items are in a set? ....................................................................................................... 124 What are the elements in the set? .................................................................................................. 124 Traversing a collection with a for loop ..................................................................................... 125 Adding a professor ........................................................................................................................ 125 Cloning a professor ................................................................................................................... 127 Removing a professor ................................................................................................................... 128 Traversing a collection with an iterator and a while loop ......................................................... 128 Another collection of professors – the department ....................................................................... 130 Listing all the professors ........................................................................................................... 131 The Singleton pattern ................................................................................................................ 132 Listing all the professors, continued ......................................................................................... 133 Collection of departments ............................................................................................................. 134 Collection of students ................................................................................................................... 135 Summary ....................................................................................................................................... 135 Exercises ....................................................................................................................................... 136 Chapter 8 – Collections, part 2 ......................................................................................................... 139 Learning objectives ....................................................................................................................... 139 Introduction ................................................................................................................................... 139 A collection of courses .................................................................................................................. 139 The Course class ........................................................................................................................... 139 Course – unit tests ..................................................................................................................... 140 Formatting the output ................................................................................................................ 140 A collection of courses, continued ................................................................................................ 142 The Section class........................................................................................................................... 142 Set? List? ............................................................................................................................... 142 What is a section? ..................................................................................................................... 144 The Singleton pattern revisited ..................................................................................................... 146 Listing a collection in order .......................................................................................................... 147 Comparable ............................................................................................................................... 147 Comparators .............................................................................................................................. 148 Unit testing the comparator ....................................................................................................... 150 Alternative versions of the comparator ..................................................................................... 151 Producing an alphabetical list of professors ................................................................................. 151 The for-each statement, revisited .............................................................................................. 152 BlueJ revisited........................................................................................................................... 153 Producing a professor list in numeric order .................................................................................. 154 Passing a Comparator to a method............................................................................................ 154 Registering students in sections .................................................................................................... 156 Producing an alphabetic class list ................................................................................................. 157 The for-each statement, revisited .............................................................................................. 158 Producing a class list in numeric order ......................................................................................... 159 Students enrol in sections.............................................................................................................. 160 Summary ....................................................................................................................................... 160 Exercises ....................................................................................................................................... 161 Chapter 9 – Collections, part 3 ......................................................................................................... 163 Learning objectives ....................................................................................................................... 163

iv

Introduction ................................................................................................................................... 163 The Meeting class ......................................................................................................................... 163 Instance variables ...................................................................................................................... 164 Behaviours ................................................................................................................................ 164 Time arithmetic ......................................................................................................................... 164 Section uses Meeting .................................................................................................................... 166 The if statement, revisited ..................................................................................................... 168 Creating the collection of Meeting objects ............................................................................... 169 Section uses Meeting – displaying the times ................................................................................ 170 Arrays ........................................................................................................................................ 171 StringBuffer .............................................................................................................................. 172 Adjusting to different colleges .................................................................................................. 173 Another for loop ........................................................................................................................ 175 Processing all the meetings ........................................................................................................... 175 Manipulating StringBuffers .......................................................................................................... 176 Placing data in StringBuffers .................................................................................................... 176 Converting numbers to day of the week ................................................................................... 178 Processing second and subsequent meetings ............................................................................ 179 A lot of code .............................................................................................................................. 179 Programming Style ....................................................................................................................... 182 Course contains Section ................................................................................................................ 183 Mark, and Student contains Mark ................................................................................................. 184 Professor contains Section ............................................................................................................ 185 Summary ....................................................................................................................................... 185 Exercises ....................................................................................................................................... 187 Chapter 10 - Collections, part 4 ........................................................................................................ 189 Learning objectives ....................................................................................................................... 189 Introduction ................................................................................................................................... 189 Grade Average ............................................................................................................................... 189 When to calculate an average ................................................................................................... 189 Weighted average ...................................................................................................................... 190 The transcript method - original version ................................................................................... 190 Knowing when a semester changes .......................................................................................... 191 Transcript – a skeleton for changes ........................................................................................... 191 When the semester changes ...................................................................................................... 192 Integer division ..................................................................................................................... 193 When the semester remains the same ....................................................................................... 194 The declarations ........................................................................................................................ 194 The overall average ................................................................................................................... 194 The transcript String – problems and deficiencies .................................................................... 195 The String class and its methods ............................................................................................... 195 Details of split ....................................................................................................................... 196 Details of indexOf and lastIndexOf ...................................................................................... 197 Reversing a String ..................................................................................................................... 197 Palindromes............................................................................................................................... 198 The transcript String – reordering ............................................................................................. 199

v

The transcript String – problems and deficiencies, continued .................................................. 201 Summary ....................................................................................................................................... 203 Exercises ....................................................................................................................................... 204 Chapter 11 - Exceptions .................................................................................................................... 205 Learning objectives ....................................................................................................................... 205 Definition ...................................................................................................................................... 205 Examples ....................................................................................................................................... 206 Runtime and nonruntime exceptions ............................................................................................ 207 Creating and throwing exceptions ................................................................................................ 208 Catching exceptions ...................................................................................................................... 212 CloneNotSupportedException .................................................................................................. 212 Bad input data ........................................................................................................................... 213 Summary ....................................................................................................................................... 213 Exercises ....................................................................................................................................... 214 Chapter 12 – Persistence, part 1 ........................................................................................................ 215 Learning objectives ....................................................................................................................... 215 Warning to the reader .................................................................................................................... 215 Why persistence? .......................................................................................................................... 215 External devices ............................................................................................................................ 216 Streams .......................................................................................................................................... 216 Persistence via object serialization ............................................................................................... 217 Object serialization - Address ................................................................................................... 217 Object serialization – MyDate .................................................................................................. 221 Object serialization – Meeting and Mark.................................................................................. 221 Object serialization – Person, Student, Professor ..................................................................... 221 Object serialization – some subtleties ....................................................................................... 221 Object serialization – creating writeObject and readObject methods ....................................... 222 Object serialization – Section and Student ............................................................................... 224 Object deserialization – Section and Student............................................................................ 226 Programming style .................................................................................................................... 228 Object serialization – Section and Student, revisited................................................................ 228 Object serialization – Professor ................................................................................................ 228 Object serialization – College ................................................................................................... 228 Summary ....................................................................................................................................... 229 Exercises ....................................................................................................................................... 230 Chapter 13 – Persistence, part 2 ........................................................................................................ 231 Learning objectives ....................................................................................................................... 231 Persistence via XML ..................................................................................................................... 231 A Digression - Scalable Vector Graphics ...................................................................................... 231 Using an XMLEncoder - no collections ................................................................................... 232 Using an XMLDecoder - no collections ................................................................................... 234 Using an XMLEncoder - with a collection ............................................................................... 237 Using an XMLDecoder - with a collection ............................................................................... 242 Programming Style ................................................................................................................... 243 Using XML – summary ............................................................................................................ 243

vi

........................................................ 247 Introduction ........................................... 266 ActionEvents.. 257 The JFrame................................................................................... 265 Create the button‘s bindings............................................................................................................................................................................................................................................................................................ 262 Position and size the frame ....................................................................................................................................... 266 Create a mnemonic .................................................. 249 Layout managers ................................Creating a GUI – Data entry screens................... and ActionListeners ................................................................................... 257 The layout manager................................................................................... 263 Displaying the frame ............................................................................................................................................................................. 266 The default button ..................................... 252 Import statements .............................................................................................. 244 Exercises ............................................................................................................................................................................... 260 Textfields................................................................................................................................................................. 254 Making the JFrame visible ....................... 258 The other labels ............................................................................................................................. 257 The labels ................................................ 244 Persistence via traditional files ................................. 251 Creating a data entry screen ....................................................................................................................................................................................................................................... 262 Make it visible.................. 258 The label Bindings ............................................................................................................................................ 263 Exit ............................................................................................................................................................. 245 Chapter 14 ......................................................... 252 How the data entry screen should appear ................................................................ 256 Explaining the code................................................................................................... 262 Create the frame .......................................................................................................................................................... 261 Displaying the frame .................................................................................................................. 249 Installing the RelativeLayout layout manager .......................................................................... 261 Summarizing building a data entry screen ............................................................................................................................................................................................................................................................................................................................................................................................................. 265 Add the button and its bindings to the frame .... 247 Warning to the reader ......................................................................................................................................................................... 263 Answering some questions ............................................................................................................................................................................................................ 265 Cancel button ............................................. 257 BindingFactory ...................................................................................................... 247 GUI ......................................................................................................................... 266 The OK Button ................................. 266 Button action ...................................................................................................................Persistence via databases ............................................................................................................................................... 247 Learning objectives ........................................................................ 261 Done!....................... 260 Other textfields...................................................................................... 253 Creating the JFrame ......................................................................................................................................................................... 244 Summary .............................................................................................................. 265 Create the button ..................................... part 1 ............................................................................................................................................................................................................................................................... 262 Keep it visible .............. 248 Some HCI considerations ................................................................................................................................................................................. 267 vii .................... 263 Buttons ...................................................

..................................... 281 Decorate the panel............................. 289 ActionListeners for radio buttons .. 267 What does an ActionListener do................ 282 Labels ................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................ 277 Learning objectives ................. 296 Exercises .............................................................................................................................................................................................................. 269 Editing data ........... 279 Create the three panels .......... 274 Summary ............................................................................................................ 293 Which layout manager should we choose? .......................................................................... 287 Placing the arrays in the frame......... 284 Create the middle panel........................................................................................ 275 Chapter 15 ....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................Creating a GUI – Menus ........................................ 272 Data entry for other classes .................................................................... 270 Verifying the day of the month ..............Creating an ActionListener ....................................................................................................................................................................... 294 Summarizing building a data entry screen .... part 2 ....................................................................................................................... 286 An array of textfields ..... continued .................................................. 279 Populate the top panel ............................................................................................................................................................................................................................................................................................................ 281 Create the middle panel .......................................... 277 Building the Section data entry screen....................................................................................... 279 Create a column of panels ... 286 An array of radio buttons ..................................................................... 267 Linking an ActionListener to a JButton ........................................................................................................................................................................................................................ 293 The bottom panel ............................................ 282 The meetings ................................................................................................................ 299 viii ................................ 295 Some general comments on data entry ................................................................................................... 270 Verifying year and month................................................................... 277 Introduction ..................................................................................................................................................................................................................................................................................................................................... 285 Radio buttons ............................................................................................................... 283 Arrays ............................................................................................................. 299 Learning objectives ....................................................................................................................................................................................................................................................................... 286 Checkboxes ......................... 267 What does an ActionListener do? .............................................................. 294 Done!.......................... 274 Exercises ...................................................................................................................................................................................... 287 InputVerifiers .................................................... 295 Summary ......................... 297 Chapter 16 ................................... 292 Decorate the middle panel ......... 285 ButtonGroup ........... 268 Behind the Cancel Button .......................................... 291 ActionListeners for checkboxes ................................................................................... 293 Button ActionListeners ............................................................................. continued? ............................... 280 Place boxes in the panel ....................................................................Creating a GUI – Data entry screens....................................................................................... 277 Create the frame ................................................................................................................................................................

........................................................................................................................................................................................................Applets .......................................................................................................................................... 323 Creating HTML to run an applet............................................................................................................................................................................................................................................................................... 327 Chapter 18 – Design Patterns .......................................... 333 Learning objectives ........... 299 Definitions.................. 319 getAppletInfo ................................. 322 Canadian flag ............................................................................................................................................................................................................... 299 Designing the menu system ................................................. 311 Creating an applet ....................................................................................................................................................................................................... 326 Exercises .................................................................. 336 High Cohesion ... 311 Learning objectives .......................................................................................................................................................................................................... 333 Introduction ............................................................................................................... 311 Running an applet ............... 323 A quick introduction to HTML .......................................................................................................................................................... 303 Completing the menu .................................................................................................................................................................................................... 311 Introduction ..................................... 304 Help ............................................................................... 336 Low Coupling ............................................................................................................................................................................................................................................................................ 314 init ............................. 305 Steps to follow ........................................... 333 Interface pattern ........... 305 Definition ............................................................................................................................................ 322 Squares ...................... 300 Accessibility.................................................................................................................................... 318 paint........................................................................................................ 319 getParameterInfo ........................................................................................................................................................................................................................................................................................................................................................................ 320 Hello world ............................................ 305 The Java statements to make the magic happen ............................................................................................................................................................................................................................................... 299 Creating the menus ......... 317 stop ............................................................................................................................................................................................................................ 312 An applet (as created by BlueJ) under the microscope .................................................................................................................................................................................................................................................................................. 321 A problem................................................................. 300 Implementing the menu ...................... 309 Exercises ............................................................................................... 305 Internationalization ............................................................................................................ 303 Performing actions .................. 337 ix .....................................Introduction ......................................................................................................................................................... 308 Conclusion ...................................................................................................................................................................................................................................... 318 destroy ........................................ 336 Creator pattern .......................................................................................................................... 307 Who did the translation? ................................................................................................................................................................................... 325 Summary ............................................................................ 317 start ............. 310 Chapter 17 ............................................................................. 308 Summary ........................................................................................... 335 Marker interface pattern .....................................................................................................................................................................................................................................................................................................................................................................................

......................................... 349 Converting a rational number to a double............................................. 349 Arithmetic operations and complex numbers .................................................................................. 343 The java................................................................ 349 Complex numbers ....................................................................................... 357 Recursive Fibonacci method ......................................................................................... 348 Subtracting................................................... 344 Rational numbers ......................................................................... 360 The Ackermann function............................................................................................................................ 350 Exercises ....................................................................Math package .................Fibonacci.................................................................................................................................................................................................Observer or Event listener ....................................................................................... 338 Singleton pattern .... multiplying.......... 349 What if ints are not big enough? .................. 351 Chapter 20 ........ and dividing rational numbers .........Mathematical methods ................................................................................................................................................................................................................................... 362 Serializing the data ......................................................... 350 Implementing ComplexNumber .............................................lang.................................................................................. continued ................................................... 362 Storing the data .... 343 Learning objectives ..............................................Fibonacci ...................................................................................................................................................................................... 358 The choose function ...................................................................................................................................................................................... 359 A Formula! ....... 339 Summary .............................................. 338 Model-view-controller (MVC) .. 357 The factorial function ........................................................................................ 353 Learning objectives .................................................................................................................................................................................................................. 365 x ........................................................................................... 356 Iterative Fibonacci method ............................................................................................................................................................................................................................................................................................................................................................................................... 364 Deserializing the data .................................................................................... 354 A recursive greatest common divisor method ............................................................................................................................................................................... 360 Recursive choose method .............................................................................................................................................................................................................................................................................. 354 Sample greatest common divisor calculations ................... 355 Fibonacci numbers ....................... 337 Factory .. 361 Dynamic programming ............................................................................................................................................................. 343 Introduction ........................................................................... 353 Greatest common divisor (gcd) .......................................................................................................................... 344 BigInteger.............................. 350 Summary .................................................................................................... 338 Lazy initialization pattern ...................................................................................................................................................................................................................... 361 Definition of the Ackermann function ........................................................... 365 Storing the data – Ackermann function ............. 340 Exercises ................................................................................................................................................................... 337 Delegation ..........................Fibonacci.................................... 348 Inverting a rational number .......................... 341 Chapter 19 ..........................................................Mathematical examples ................................................................................................................................................... 353 Introduction ...................... 345 Adding rational numbers............................................................................................................................................................ 343 BigInteger ................................................................................................................................................................................. 361 Recursive implementation of the Ackermann function .....................

.................................................................................................................................. 371 Refactoring ........... 367 Exercises ................................................................................................................................................................................................................................................................. 376 In Conclusion ...........................................................Threads.......................................................................................................................Data Entry Screens ................. 394 Lab Assignment 6 ................................................................................. 391 Lab Assignment 4 ............................................................................. 393 Lab Assignment 5 ........................ 396 Lab Assignment 7 .............. 368 Chapter 21 ..................................................definition ................................................................................................................................................................................................................................................................................................................................... 369 Threads .....Reporting .............................................................................................................................Teams and Leagues ......................................................................................................................................... 379 Printed Reference materials .............................................................................................................. 381 Introduction ............. 369 Learning objectives ....... 372 public static void main(String[] args) ................................................................................ 379 Online references ............................. 375 Exercises ......................................................... 370 Inner classes .................................................................Mathematics II ............................................................................. and other topics .................... 382 Lab Assignment 1 ........................................................... 397 Subsequent lab assignments .................................................... 399 Index ........................................................................................................................ 374 Summary .......................................... 366 Deserializing the data – Ackermann function ......................................................................................................................Mathematics I ................... 366 Summary ....................................................................................... 377 References ................................ 369 Threads and Swing ....................................Getting to know you ...................................................................................................................................................................................................................... 380 Appendix 1 – Sample lab assignments .............................................................................................................................. 369 Introduction .....Players ..And now for something completely different .............................................................................................................................Serializing the data – Ackermann function ........................................................................................................................................................... 373 Input and output .............................................................................................................................. 388 Lab Assignment 3 ........................................... 387 Lab Assignment 2 .................................................................. 381 Lab Assignment 0 ........................................ 401 xi ......................................................................................

but not all. If you or someone else cannot understand what you have written. and together. It allows us to save the tests and reuse them whenever we make a change to the programs. Tested means that you can trust the results the program produces. or with a small amount of computer resources. so they can see the advantages of objects. then how can you improve or change it? How can you fix it if it contains an error? We will use tools called Checkstyle and PMD to help us meet these goals. To students What is computer science? How does this textbook help you study computer science? Much. This is because programs are continually changing. By ―good‖. Clear. In this book we gloss over some of the details of how the program you write is translated into something which the computer can carry out. but does it 1 . Can someone else read your program and understand what it does? If not. I feel that objects should be introduced early. this is not just another Java book. Tested to ensure requirements means that the program does what it is supposed to do.Preface to the reader Oh no. The instructions to solve the problem are written as a program or programs. you have failed in creating something which can be used. but wait until you‘ve had a chance to look at this one. instruction which the computer performs. Reflecting these ideas. But a detailed discussion of efficiency is beyond the scope of this course. Efficient means that the program carries out its task quickly. of computer science involves using a computer to solve a problem. Often these two characteristics are in conflict. and does it correctly. easy-to-read. We emphasize unit testing using a tool named JUnit. perhaps on the first day of an introductory course. and well-documented go together. efficient. and we focus on how to write good programs. well-documented. not another Java textbook! Perhaps that‘s a valid comment. a program may work faster when you give it more memory. I also believe that students should use a large application as an example. There is a lot of discussion amongst teachers about when to introduce objects in Java. or a better solution becomes available. as early as possible. we mean clear. The problem they are solving changes. and tested to ensure they meet the requirements. You can test a program and it may produce what you thought it would. which allows us to test each portion of the program separately. easy-to-read.

where the students study material on their own and present their discoveries to the rest of the class. Mac OS. perhaps all taught by the same professor. January through April. In order to complete a program of study. it is a constant reminder of what you can produce using Java.produce what it should? We don‘t have a tool to test that it meets the requirements. Some courses are best taught using lectures. Some are best taught using labs. it is available online. we use one example. Students sign up to take many different courses. called semesters. but we will be very careful in ensuring we do meet them. The language itself is very simple. A course is a collection of related topics. since Java will run on many different operating systems. and gains much of its power from libraries which people have created to carry out specialised tasks. Java is a good language with which to start. labs. Some are best taught using seminars. students may take a course more than once. Checkstyle. you can use computers running Linux. there are meeting times associated with each. The example is a North American college. Some courses may be offered in two or three semesters. we need a way to save large amounts of data. the Java libraries. The academic year is divided into three portions. This is a modern language which I find very enjoyable and easy to use. or seminars. The semesters run from September through December. There are many other languages available so you will need to learn many languages during your career in computing. when there are many students wanting to take a course there may be a number of different sections of the course being offered. with marks being awarded for each attempt. This is a measure of the popularity of Java and the various types of programs it is used to create. To model this college. When we write programs. Whether a course uses lectures. 2 . where the professor teaches and the students participate by listening and asking questions. perhaps taught by different professors. the professors teach students who are enrolled in sections of courses. JUnit testing. perhaps resulting in a diploma or a degree. Since BlueJ is written in Java. and the professors provide assistance. Some courses use a mix of two or all of these. Most importantly. The number of libraries is truly amazing. A section of a course offered in one semester is different from a section of a course offered in a different semester. We will use a tool called BlueJ to help us integrate all these features – the Java language. where the students are doing predefined activities. A significant part of learning Java is becoming familiar with the documentation describing these libraries. At this college. For much of this book. and PMD. we use the Java language. and May through August. or Windows. what some call post-secondary education and others call tertiary education. Since there are limits on how many students a professor can teach at one time (the college has a goal of having no large classes).

1. and I wanted to do it objects-first. so I decided to create my own. Newer versions offer support for team work. Since then. I hope you find it interesting. Of course. 3 . I have also used the RelativeLayout manager for designing GUIs. The competition was between editions. In checking all the code in this textbook. but it does not appear to affect anything here. Although it is based on a sports league. I have used version 2. it should be understandable even if you are not interested in sports. Basically. I have used the Creative Commons approach. and other competitors were not yet available. My reviewers have given me much interesting feedback. Another time the course was taught. I addressed the question of one large example instead of several small ones.5. I do not assume any programming experience. using one example in the lab assignments also caused similar concern. To teachers Like many textbooks. Also in the preface to students. BlueJ does not include the most-recent version of JUnit. I wanted to teach an introductory programming course using Java. this one arose out of a perceived need. but it would make a valuable addition to the course. The exercises at the end of each chapter include other examples. I have not included a discussion of that aspect in this textbook. Java 6 has become available. In the time it has taken to complete this book. I could not find a textbook that met my needs. rather than one large example. I agree with the latter perspective. Since then other versions have become available. The lab assignments included in the appendix also include a large project. I used BlueJ version 2. the problem is that it is very easy to write small problems using objects. One thing which caused many of them some difficulty is the use of one large project to form the examples in this book. I hope you enjoy the approach I have used here. the labs involved the records you keep when watching birds. To see this textbook published. but the version included serves to introduce the idea of unit testing. Note that I do assume you have used computers before and are familiar with some of the terminology. Java 5 was the most powerful version of Java available at the time. But others have suggested that the way to see the benefits of objects is to see them in a large project.3 (the most-recent version at the time) along with the Checkstyle and PMD extensions. When I began writing. In the preface to students I have explained the project for the benefit of those who are not familiar with the way a North American college or university works.Some have suggested that an introductory textbook like this should use many small examples.2 as it was the most recent stable version at the time. some small and some large. other competitors have appeared.

not because of the class size. That is. Thus I need a language which forces everything to be an object (Java almost meets that requirement). it covers all the material in CS1 plus a little of CS2. you could write the small programs without using objects if you wished. I have taken the second approach. except that there is some persistence in the mathematical chapters but you could omit that too. or your preferences. At that point we look at some other examples. ―<that topic>‖ could be persistence. so I want to force people to use objects. But should you be using this textbook for a two-semester course. Notice that after a while I find I have exhausted the North American college example of ideas. or I need a project which is so large that you must use objects. which can be appreciated by students learning to program for the first time. 4 . Like this. to be followed by a data structures course. We find that the material in this book is adequate for about 80% of a two-semester course. But I believe that using objects is an important way of designing your software.but the objects are not crucial to success. starting with mathematics. the students. However. we cover the content in three semesters. should you prefer. They had some difficulty. All of those chapters are not dependent on the rest of the book. depending on the length of your course. you may wish to omit any or all of those topics. I have included them because I feel they are important topics. this textbook is more than adequate for a one-semester course. related to the environment and follow-up course. be prepared to supplement it towards the end of the second semester. mentioned above. My reviewers have also asked why is <that topic> included. instead of teaching the ACM courses CS1 and CS2. which you could omit without disturbing the integrity of the course. I have used this textbook with a small group of students and with a larger group. GUIs. That is. and there are chapters. Depending on the reviewer. Thus. The team work features of BlueJ would be an ideal supplement. Other brief sections which present interesting but non-essential material are shown with a grey background. For the rest of the course we use material specific to Okanagan College. I have used this textbook as the basis of a two-semester course. in the example in the textbook. but because they were not objects-first people. patterns. and in the lab assignments. That is. applets. and/or mathematics. Other colleagues have used the textbook with large groups of students.

BC Canada rgee at okanagan dot bc dot ca p. and the examples are. in many ways. Canadian.s.To everyone Thank you for purchasing this book. 5 .chiasmus. and especially if you find any errors or omissions or unclear sections.shtml. Rick Gee Okanagan College Kelowna. please contact me. so the spelling in this book is Canadian. I hope I have those powers. and familiar things new. Should you have any comments. I hope it meets your needs. positive or negative.com/welcometochiasmus.‖ This is a quotation which I found at http://www. Yes. I am Canadian. Remember that Dr Samuel Johnson said ―The two most engaging powers of an author are to make new things familiar.

and Paul York for their patience and assistance with version 3. I would like to thank the reviewers who provided me with interesting and challenging feedback. Maria Nemes. Mike Tribe. Kurtis Lewke. Patrick McCallen. Claire Bemben. Jonathan Gaudet. I‘d like to thank Rob McArthur and his students for their patience and assistance with version 2. Chase Marsh. Sarah Fredericks. and my students. Jay Olson. Alex Saunders. Chris Hollman. I would also like to thank my students. Rick Gee Kelowna. and Brandon Potter for their patience and assistance with version 1. Philip Pereboom. I‘d like to thank Peter Kossowski and his students.Acknowledgements I‘d like to thank my colleagues Rob McArthur (Okanagan College) and Joseph Fall (Capilano University) for their help in the writing of the examples in this textbook. Cory Ingram. Jeff Carpenter. Fraser Wozny. Neesha Jaswal. Daren Ling. BC Originally completed summer 2008 Revised summer 2010 6 . Nicholas Goertz. Sergey Raspopov. Kevin Koehler. Andrew Faraday.

This is additional material.3. are also shown using this font. which expands on the material nearby. Address is the name of a class we create but address is the place a person lives.Notes Statements in the Java language are shown using this font. and have been run through BlueJ 2. it is shown in italics. including variable and class names referred to in the body of the text. Standard Edition. Thus. Java snippets. While interesting. 7 . The occasional paragraph is shown with a light-grey background.5. Professor is a class but a professor is a person. the material is not crucial. The first time a word is defined. All the examples used assume the Java 2 Platform. Similarly Person is a class but a person is a member of the human species. Student is a class but a student is a person. and Section is a class but a section is a specific offering of a course.

8 .

that would be computer engineering. Let‘s have a quick look at those terms. To understand computers.Chapter 0 – Introduction Learning objectives By the end of this chapter. Data is the things we know or are given. Hardware Hardware is the parts of a computer which you can touch. the study of computing. both commercial and non-commercial. Depending on the programming. The hardware is capable of responding to instructions on how to do a task. you will be able to:     Describe hardware Describe software Name a few programming languages Say why the author believes Java is the appropriate language to use to introduce programming What is computer science? Computer science is not the study of computers themselves. Thus. but a computer can function as a telephone (with the addition of a microphone and speakers. a computer may perform various tasks. To study computer science. about which I assume you already know something. (The word data comes from the Latin language. and programming. or PDA) is not a computer. meaning ―given. software. solutions which often use computers. These instructions come via programming. Computer science is the study of the use of computers in various parts of life. A smartphone is a computer. Older cell phones are not computers. European institutions often use the word informatics. we need to understand how to design solutions to problems. Perhaps we should call it ―computing science‖. Information is ―the result of 9 . A computer transforms data into information. Some universities and colleges have done that. but a computer can function as an MP3 player.‖) Data includes the students who have enrolled in a course and the marks they have earned. we need to understand hardware. since it performs only one task. an MP3 player is not a computer. but a computer can function as an address book. Some define hardware as the parts of a computer you can hit when something goes wrong.) An address book (a personal digital assistant.

which is executed when the power is first turned on. First. The keyboard for a Macintosh computer has an ―Apple‖ key. The reason you want more memory is twofold. often on one chip. the faster the CPU. calendar. The operating system allows other programs to run. for example.  Read-only Memory (ROM) – a portion of memory which uses a battery to retain its contents when the power to the computer is turned off.htm) For example. manipulating and organizing data in a way that adds to the knowledge of the person receiving it. various utility programs. Mac OS. browser. Then memory became cheaper and computers contained megabytes (MB) or gigabytes (GB) of memory. abbreviated MHz) but is now measured in gigahertz (billions. Modern computers often have many CPUs (called cores). often much less. Heinrich Rudolf Hertz was a German physicist in the late 1800‘s. The marks students earn can be transformed into semester averages. ROM is more expensive than RAM. UNIX. programs. This output may be text or graphics.orafaq. This is the part of the computer which carries out the instructions given by a program. RAM was measured in kilobytes (KB). 1 hertz = 1 oscillation of a wave per second. you can have more programs in memory simultaneously. so you will have less ROM than RAM. In the old days. It all depends on what programming can be done for the computer. In general. etc. ROM is used for things like configuration information. The speed of the CPU used to be measured in megahertz (millions of cycles per second. Software Every computer has some programming available for it. it often comes with some other programs – word processing. In general. and a boot program. Solaris.). the raw data about the students in a class can be transformed into a class list. Second. information which will in turn become data for determining which scholarships students win. although when you have multiple CPUs (or cores) you can use a slower speed. and hence more powerful. We will use the mouse quite extensively to control BlueJ. the more RAM your computer contains the better. with the CPU giving each a portion of its time. clicking buttons or selecting items from a menu.  Random Access Memory (RAM) – used to store data while a program is running. This includes:  Central Processing Unit (CPU) – the brains of the computer.com/glossary/faqglosi.  Mouse or trackball – used for input. the better. or information.  Keyboard – used for input. you can run larger.‖ (http://www. abbreviated GHz).  Monitor – the screen on which output from a program is displayed. and a few games. Hardware – the parts of a computer which you can touch. or thousands of millions. of cycles per second. When you get an operating system.processing. Linux. 10 . There are many different layouts for keyboards (Where is the backspace key?) depending on the manufacturer of the keyboard and many different special keys. This includes an operating system (a version of Windows. His name has been adopted as the unit to measure frequency.

I have found that the articles about computer science are reliable and I will quote many of them in the material that follows. C was developed in 1972 for use with the UNIX operating system. What is a paradigm? It‘s a way of thinking about what you are doing. it allows you to do many different tasks and thus has applicability in a wide variety of domains (different areas of programming – games. C++. You may also want to create new programs. personal computers. When you learn your first programming language. (http://en.org/wiki/Paradigm) Wikipedia is an online encyclopaedia. etc. to some degree. its predecessor language was called B.wikipedia. Or perhaps you will want to create programs to help you write more programs. (And yes. to make backup copies of them. in a variety of styles. C. Java is a language that uses a popular programming paradigm. For those tasks. Perhaps you want to create a game. These platforms include mainframes. it‘s good to start with an easier one.) Pascal was developed in 1970 as a language for teaching people how to program. Or you may need the money to hire someone who does. and to run programs. and is being used more and more as time goes by. Programming languages Programming is done using a variety of languages. You may have heard of BASIC. How do you know that the author is reliable? In general. to locate files you have created. so I have chosen Java. Today there are many languages in common use – including Java. perhaps one to track the inventory in your warehouse. That means there is a certain risk in using Wikipedia as a source. you need a programming language and the ability to use it. and Visual Basic. C#. Why are there so many different programming languages? Because they were designed to serve special purposes. database. and student registration are examples) on a variety of platforms. 11 . Pascal. BASIC (an acronym formed from the phrase Beginner‘s All-purpose Symbolic Instruction Code) was designed in 1963 as a tool for teaching people to program. Why Java? It‘s a language commonly used today. in which the entries in the encyclopaedia are written by people like you and me. That is. These are all programming languages which have been used in the past and continue to be used. object-oriented programming. It is a powerful language.You will be using some parts of the operating system in your labs. and mobile devices. It‘s the set of practices that define a discipline during a particular period of time. or to track the hours worked by employees and pay them.

software. Now. using popular techniques which allow you to create ―good‖ programs. hopefully better. Summary In computing.In programming. At one time. paradigms change as people develop different. That is one of the topics in chapter 1. 12 . and programming are combined to create instructions to control a computer. The instructions are expressed in a programming language. ways of doing things. Perhaps we should define what we mean by object-oriented. using a particular programming paradigm. the dominant paradigm is object-oriented. the paradigm was ―structured programming‖. a paradigm is a way of creating programs. Java supports the object-oriented paradigm. Over time. hardware.

Then we look at BlueJ. constructor. you provide the instructions which tell the computer how to process pieces of data. and how we model them. Then we look at JUnit. getters. and setters Describe some primitive datatypes and some datatypes represented by classes Document Java code Describe the purpose of. we use what we have learned to create a second class. Data in the real world comes in many different types. so you‘ll want to take it slowly. Finally. we create new datatypes by creating new classes and using the classes to create objects. a toString method Introduction This chapter contains a lot of material. Depending on the language you are using. Definitions When you write a program. state. but not always the datatypes necessary to describe the real-world data. Then we discuss how to write a class. and behaviour Learning objectives By the end of this chapter. you will be able to:          Define class Define object Draw a class diagram Implement simple classes in Java Define method. In object-oriented programming. and implement. The programming language you use will allow you to create new datatypes. the tool we will be use to help us in our modelling and our coding. the tool we will use to test the programming that we create. getter.Chapter 1 – Classes and objects – identity. you will have different datatypes provided to you. First we discuss what objects and classes are. setter Create constructors. 13 .

Similarly. of something in which we are interested.In computing. 14 . They each have associations with sections of a course. they each have a name. Thus we have a definition of a class – a blueprint for creating objects – which makes more sense now than when we first proposed it. This ―something‖ may be real. A student registers in a section. Many of the apartments have the same layout. all are objects. When two objects are related in some way. the word object has a very specific meaning – an object is an instance of a class. This idea of a blueprint also works in other areas as well. or imaginary. so there can be associations between one object and another. we say there is an association between the objects. They were all made from the same blueprint. you earn marks in courses. And look at some of the new subdivisions being built around our cities. Many of the houses in those subdivisions look alike. We need to explore the concepts of object and class more fully before we can understand the definitions. Think of a new building containing apartments (flats). and a section is an object. For example. There is an association between a student and a section. But those definitions are circular. you create a blueprint for creating objects. One object may participate in many associations. like name. and an address. a student. Each course the college offers is an object. All these objects have some things in common. address. the word class has a very specific meaning – a blueprint for creating objects. You receive a final mark in each course you take. they don‘t really tell us anything. All students have things in common. Whenever you find things having common features. But think about this for a moment. like a mathematical function. an object is a representation. Each section has an association with a course. are an object in a system involving college registration. a student number. they are made from the same blueprint. and you may incur library fines. You. Many of the floors of the building have the same layout. There are many student objects enrolled at Okanagan College. rather than just creating objects. and student number. There are many students at a college. like a person or a piece of furniture. They are all made from the same blueprint. A system involving college registration will need other objects. you are registered in sections. implemented using a computer language and stored in a computer. So what is an object? Since we are talking about computer programming.

A statement in Java is a complete instruction to the computer. C++ is not a pure OO language. and behaviours (who owns the house? Is it owner-occupied?) So what is object-oriented (OO) programming? It is a programming style (a paradigm) which uses classes and objects. state (including the owner and the colour of the front door). What other classes can we identify in this room? Well. These usually are statements. In computing. But they are built from the same blueprint. we could consider the desks. and behaviours (the things it can do. A Furniture class could represent them. This is because of its roots in the C language. All your textbooks have an ISBN. several apartments may have the same layout. some of the units are identical and some are mirror-images of each other. the chairs. and an author. Java is not a pure OO language but it comes close. there are a few things in Java that are not objects. Note that I have shown the name Room in a different typeface. and behaviours (what is the rent and when was it last paid?) Houses have identities (the street address). Looking for other objects in the room. A Room class could represent a room. They too have identities (apartment number 307. The word code means the instructions we write in Java. They may have serial numbers attached.In the building in which I have recently purchased a home. and the tables themselves. This indicates that we may be implementing the Room class in Java. And we have a definition of an object – an instance of a class. depending on the application. An OO language is one which supports OO programming (OOP). we could consider the room itself. 15 . Classes We have identified ―student‖ as a class whose objects are in this room. It allows you to create classes and objects. one which I have reserved for code in the Java language. for example). They have a description. Smalltalk is a pure OO language. In the construction examples above. A statement in English is a complete thought. It has a room number and a capacity. As we will see. but they are different apartments. A Textbook class could represent a textbook. state (the names of the occupants). A pure object-oriented language lets you use only the OO style. an object has an identity (its name). a title. like tell you about its state). it has state (the values which it knows).

Those questions are relatively simple. we have been adding large amounts of greenhouse gases (carbon dioxide. methane. Plants are blooming earlier than previously seen. Most glaciers are melting. The Inuit of the Canadian Arctic are seeing birds (the American Robin. Would it not have been better to make a model and do the experiments there? When I first began teaching. this is not something we would like to do in the real-world to see what would happen. The weather is becoming more changeable. we will go on and identify the associations between them. When Mount Pinatubo erupted in June 1991. for example) which they have never seen before. Most people believe this is having an effect on climate and weather. To add an environmental note. without knowing the consequences of these changes. the same way you have a name and a student number.) to the atmosphere during the past 250 years. there was some discussion about ―nuclear winter. or the Antarctic. So where do we start when we want to model these real-world classes? Why do we want to model real-world classes in a computer? Perhaps we would like to be able to determine the effects on our institution if we reduced the class size.‖ This was the idea that if there was a nuclear war. This would lower the temperature. Again. we did see a cooling effect but only for a short time. and we could do the experiment in the real world. and reduce much of the plant growth. How many more sections of courses would we need to offer? Do we have enough classrooms? A model would help answer those questions. whether they are in the mountains. etc. A Professor class could represent a professor.) Once we have identified the classes. Some experiments are not so simple. Your professor has a name and an employee number.Your professor represents a class. Well. the Arctic. So we are surrounded by objects and can use our language to determine the classes from which they are instantiated (created as instances. the resulting explosions would throw so much dust into the atmosphere that the amount of sunlight reaching the surface of the Earth would be reduced significantly. So how do we make models using the Java language? 16 . we may actually try something like this if a large volcano erupts. they had to create a new word for the American Robin! We appear to be making some serious changes to the world.

We identified two types of people in the room (not male and female!). Notice the word ―type‖. we might have a DepartmentStore class. each is capitalised. We don‘t know its methods. One. student and professor. All that we know about the class is its name. (Note that Java is also an island in Indonesia and a synonym for coffee. The first subsection always appears. Class diagrams We need to be able to describe these two classes. This subsection is optional in the UML but is obviously necessary when you translate the diagrams into Java. a class is represented by a rectangle. whose values we mentioned earlier. These are the behaviours we mentioned earlier. will be used for drawing diagrams. Thus. In this course we will use two languages. however. in a different example. What standard am I using for the name of a class? Right. There are many coffee jokes associated with Java. and it contains the name of the class. displaying one. Thus. the pieces of data which an object contains). But we usually need to know more about the class.The Student class Let‘s begin with the people in the room. a picture is supposed to be worth 1000 words. The third subsection of the rectangle contains the names of the methods the class supports. We will model these two types of people with Student and Professor classes. This represents a class. we will use the Java programming language. This subsection is optional in the UML but is obviously necessary when you want to translate the diagrams into Java. the class name is a singular noun and its first letter is capitalised. We don‘t know its attributes. called the Unified Modelling Language (the UML). using some language. There are no Indonesian island jokes of which I am aware. When the name of a class includes several words. or three subsections. this is an English word that makes programmers think ―class‖. let‘s consider the UML representation of a Student class. two. after all. 17 . When we use words. The second subsection of the rectangle contains the attributes (the names of the data items. It can be represented simply as follows. including JavaBeans and the coffee cup logo.) In the UML.

as each of you do. her student number is never reused. These class diagrams are created by a free UML editor called Violet. I worked for a company which reused employee numbers. so they can be shown in the Student class diagram. As English is my native language.com/violet. the UML notation of the Student class. In a previous career. available at http://horstmann. describing what a Student object knows and can do. no other student will have that number. Is it a problem that BlueJ only offers simplified UML diagrams? It would be a problem were we developing a commercial product. Every Student object has a name and a number. Remember that a Student class is simply a blueprint. showing the attributes is Note that BlueJ apparently does not allow this form of the class symbol. Part of that responsibility is to ensure that once a student has graduated. Similar diagrams may be created with a BlueJ extension called PMD. That caused many problems when you looked at historical data for employees who were no longer with the company. everyone needs a number. Their numbers may have been reused two or more times so information on two or more employees would be combined.Consider the attributes of a Student object. 18 . The Registrar‘s Office at my college is responsible for ensuring that the student numbers are unique. There is nothing to stop you from using words in your native language to create attribute names. Thus. then the second and subsequent words are capitalised. we‘ll look at it later. an object instantiated from the Student class. We have already mentioned that a student has a name and a student number. the attribute names consist of English words. If an attribute name contains several words. Java coding standards specify that attribute names do not begin with a capital letter. which will be unique. Thus a Student object will have attributes named studentNumber and studentName. Since names are not unique. These are two different attributes of every Student object. but it doesn‘t seem to be a problem for our project.

and eight bits can represent 256 different values. If you have one bit. called bits. The Unicode standard. 10. 101. The encoding of these 256 values came from the American Standard Code for Information Interchange (ASCII).org. and a long which contains 64 bits (representing integers from -263 to 263 – 1). seven bits can represent 128 different values. you can represent 00. Hence the emphasis on English. Java does support many different types of numbers. byte and short 19 . a short which contains 16 bits (which. you can represent 000. What about studentNumber? One of the problems of the English language is its ambiguity. 001. the digits from 0 through 9. six bits can represent 64 different values.Datatypes What type of data do we use to store the studentNumber and studentName? Everything stored in a computer is stored as patterns of 0s and 1s. 01.‖ Binary means you only have two choices (usually 0 and 1) and digit refers to the individual parts of a number. when interpreted as numbers. an int which contains 32 bits (representing integers from -2147483648 to 2147483647). some punctuation symbols. Klingon. a bit is the smallest unit of memory. All of these could be used to store studentNumber as long as we know they are large enough (contain enough digits). you can represent 2n different values. represent integers from -32768 to 32767). Fortunately. If you have three bits. represent integers from -128 to 127). an invented language used in the Star Trek television series and movies. Java has a number of primitive datatypes. Java has a datatype named String which contains characters. These include a byte which contains 8 bits (256 values which. we need to group the bits into a larger unit. plus a few other letters. that word is not necessarily the best for the situation. If you have two bits. At first glance you would assume studentNumber is a number. That is apparently enough to represent all Earthly languages. encoded using the Unicode standards. Just because we use a particular word to describe something. and 11. and 111. four bits can represent 16 different values. In general.unicode. Everything is stored as a collection of bits. 100. described at http://www. when interpreted as numbers. this datatype can represent it faithfully. 011. When you collect eight bits and treat them together. uses 16 bits to represent individual characters. this does not represent letters in many other alphabets. To do that. However. eight different values. which are not objects. is not officially included. Similarly. when you have n bits. then a byte can represent 256 different values. If we can create the character. as one byte. then you can represent only the values 0 and 1. 110. five bits can represent 32 different bits. The word bit is an abbreviation for ―binary digit. You might suspect that the encoding came from the United States and you would be correct. As we noted above. Having 256 possible values allows us to represent all the letters of the English alphabet. four different values. 010.

At least we know the studentNumber does not contain decimal points. Thus int and long contain enough digits.are not long enough. Java also has datatypes called float and double. you should store it as some type of number. Now the more-complete UML Student representation is as follows. since student numbers at Okanagan College contain nine digits. both of which are of type String. The Professor class What is the corresponding UML representation for the Professor class? Recall that a professor also has a number and a name. we see the names of the attributes and their datatypes. But a studentNumber will probably not be used in calculations. We‘ll note for the moment that these two diagrams reflect a certain commonality. to store numbers containing decimal points. so we could just store it as a String as we did with the name of the student. since studentName is obviously a String. 20 . This discussion of numeric datatypes is interesting. Not only do we see the name of the class. Thus a Student object has two attributes. but is studentNumber really a number? A good guideline in deciding whether something called a number is a number or is something else is to ask the question ―Is it going to be used in mathematical calculations?‖ If so. We‘ll explore that commonality later in this chapter.

using attributes firstName and familyName. but that is actually his family name. That may seem to be a straight-forward task. a possible algorithm is ―start at the beginning of the string and look for the first space. Perhaps we need to create a transcript for ―Jane Doe‖. Thus the algorithm will say that Yang Changji has a first name of Yang. and sometimes the parts of the name.) I use some software that uses my full name when it says goodbye. Perhaps we need to write a letter that begins ―Dear Jane‖. The part before the space will give us the given name. Jane‖. we should consider what other name-related fields we should include. Will we always use the whole name? Will we sometimes use the parts of the name separately? I would argue that it is safest to assume we will sometimes need the whole name. let‘s have a preferredName attribute. An algorithm is a series of instructions to solve a problem. that‘s too formal for my taste. Both first names and last names may be hyphenated. using a finite amount of space. name. just start at the end and work forward until we find the first blank.‖ This algorithm expects the string containing the name to have the first name at the beginning of the string. Not all Alberts like to be called Albert. Of course. So. there is also the problem of hyphenated names. we should store the first and family names separately. described below. or Dave. Not all people like to be called by their given name.Tradeoffs of storing the name as one field versus several We discussed how to represent names and numbers-that-are-not-numbers earlier. Does that algorithm really solve the problem? What about Billy Bob Thornton (whose given name is Billy Bob)? Our algorithm does not give the correct answer! Many Asian names don‘t satisfy the conditions of the algorithm. The family name is given first instead of last. Since we are modifying our design. or family. ―To identify the family name. or maybe the name will be represented as ―Doe. they may prefer Al or Bert or Bertie. To get around the fact that breaking a name into its constituent parts is challenging (if not impossible). the part after the space will give us the family name. 21 . (Cholmondley is pronounced Chumly. It appears we have a flaw in our logic. in a finite amount of time. Perhaps a ―preferred name‖ should be there. and it‘s a well-known algorithm. the last name at the end. A similar algorithm (having similar problems) may be used to find the last. In this case.‖ Does that algorithm really solve the problem? What about Manfred von Richthofen (whose family name is von Richthofen). Cholmondley David Smith may prefer to be called David. The most important questions relate to how we will need the name. but let‘s revisit that discussion and look a little more closely at how to represent a name most efficiently. If we store the name as one field. we would need to split it up whenever we needed the parts.

There may even be times when a person‘s middle name is required, so let‘s have a middleName attribute. If our program is to be useful in other cultures, we may wish to just use the attributes name1, name2, and name3 and let the user of the program decide what to enter in each. In addition, there will be times when a person‘s full name is required, so we‘ll store it as well, but only for use when the full name is necessary. I will, at least temporarily, use the word student as part of the attribute names for a Student, and professor as part of the attribute names for a Professor. Thus the UML diagrams for our Student and Professor classes look like this.

When we create instances of these classes (a Student object or a Professor object), these objects contain the parts of the name. When we have several different objects, students as an example, each object will contain a student number, unique to the objects. In each object, the student number will be contained in an attribute called studentNumber but, since the objects will each have separate identities, it is no problem that studentNumber occurs in each. Note that while we have used the term ―attribute‖, an equivalent term is instance variable. Each instance of the class (each object) has the same attributes, and the value of those attributes can change, or be variable. Hence the term ―instance variable‖ is a reasonable one. But how do we tell the object what those values are? How do we retrieve those values when we need them?

22

Behaviours
Recall that an object has identity (the name we give the object), state (the values it contains), and behaviours (the things it can do.) First of all, we note that ―things‖ is not a very precise word. I would like to define behaviours as ―the messages to which an object responds.‖ We will send a ―This is your given name attribute value. Remember it.‖ message to a Student object and then we can, at some later time, send a ―Please tell me your given name.‖ message to that object and it will return the value it remembered. In Java, methods receive the messages and respond appropriately. This idea of sending messages to an object is a powerful one, and we can extend it to sending messages to a class, in particular, a message like ―Create an object of your class, and here are the attribute values you need.‖ Most classes contain a method, called a constructor, which responds to this message. It will take all the attributes you supply, process them appropriately, and then return an object for the program to use. Similarly we will need messages to remember (or set) each of the individual attributes (one message per attribute.) These messages are called setters. The values we provide to be remembered are attached to the message through parameters. Another name for these methods is mutators. They change, or mutate, the value an attribute contains. We also need messages to retrieve the values of each of the individual attributes (one message per attribute). These messages are called getters. Another name for these methods is accessors. They access attributes. Constructors, getters, and setters are usually not shown in the third subsection of a class symbol, the area where methods are shown. Later on, we will see a special type of class, a JavaBean. For these classes, there is a constructor which takes no parameters, and a setter for every attribute. To make and populate such an object, first use the constructor to create an object whose attributes have some default values. Then use the setters to specify the values you want. For now, our constructors will take parameters. Once we have the ability to create an object, we should have the ability to display it, to be sure that it has been created correctly. Every object needs to be displayed, so the class needs a method, usually called toString. This method converts an object to a human-readable form suitable for display, perhaps through printing. We‘ll see the code (remember that code is computer-speak for anything written in a programming language.) for this method in the next section of this chapter.

A first look at Java
So now we have a diagram which describes what a Student class contains and what it does. Computers generally don‘t know how to interpret diagrams, so we must somehow translate this diagram into Java code.

23

Here‘s part of the code for the Student class. It‘s followed by an explanation of the individual statements.
/** * A Student * @author Rick * @version Summer 2008, 2009, 2010 */ public class Student { private String studentNumber; private String studentFirstName; private String studentMiddleName; private String studentLastName; private String studentPreferredName; private String studentFullName; /** * @param studentNumber 9-digit student * number assigned by the college * @param studentFirstName Student First Name * @param studentMiddleName Student Middle Name * @param studentLastName Student Last Name * @param studentPreferredName Student preferred * name or nickname * @param studentFullName Student legal name */ public Student(String studentNumber, String studentFirstName, String studentMiddleName, String studentLastName, String studentPreferredName, String studentFullName) { this.studentNumber = studentNumber; this.studentFirstName = studentFirstName; this.studentMiddleName = studentMiddleName; this.studentLastName = studentLastName; this.studentPreferredName = studentPreferredName; this.studentFullName = studentFullName; } //end constructor /** * @return student number */ public String getStudentNumber() { return studentNumber; } /** * @param student number */ public void setStudentNumber(String studentNumber) {

24

this.studentNumber = studentNumber; } } // end class

Let‘s examine this code in detail, starting with the documentation. Documentation The class begins with some documentation, comments you make to read at a later time, and comments which will be visible to anyone viewing the code for your class. These comments typically explain the purpose of the code and give some information about its contents. In a Java class, the documentation section begins with /** and ends with */. If you have done any programming before, you may be used to /* to begin a multi-line comment, and */ to end it. While that style still is acceptable, there is a utility program named javadoc which will process your Java program and identify the comments, as long as they are preceded by /** and followed by */ Once it has identified the documentation, it formats it into a readable, useful, form. Normally the first block of comments in a class will contain information about the class. It should include such information as the author (using the @author tag) and the date the class was originally written, along with a revision history (using the @version tag). Details on writing comments for the javadoc utility program are available at http://java.sun.com/j2se/javadoc/writingdoccomments/index . It is important that you follow these standards for writing comments since javadoc is accessible via BlueJ and you want your documentation to appear as professional as possible. Important points to note are the following. o Documentation for a class must appear immediately before the class header. Any import statements, which we will see later, must appear before the class documentation. o Documentation for a method must appear immediately before the method header. The description of the method is the first complete sentence in the documentation, determined by a punctuation symbol like a period. o Documentation for the parameters to the method, or the value returned, may extend over several lines, if necessary. You may be used to writing single-line comments that begin with //. As you can see above, anything on the same line after // becomes a comment. Programming Style – documentation Style is a way of expressing something, or the appearance of something. If you search the web using the three words programming style Java, you will find many sources that provide the way to write Java programs. Throughout this book we will include small sections describing

25

appropriate style issues and, more importantly, we will use generally-accepted good style. Since style is important, we will enforce good style by using a tool called Checkstyle. Documentation is made a little easier when we use BlueJ as it generates some skeleton documentation you for every class and method it creates. That is, it gives you the beginning of the documentation. It gives some ideas of what your documentation should say. As noted above, for every class, you should provide a description of the class (what it represents). You should also provide a ―revision history‖, who wrote the class and when, plus a description of the changes made by whom and when. Following the class documentation, we begin to see Java statements. Class declaration The class header says public class Student. This marks the first line of the class itself, giving the name of the class (Student), and an indication (the word public) that it can be used by methods outside the class. Of course it must be used by others; that‘s the whole point of having classes! Other people don‘t need to reinvent your work. Yes, there are private classes and we will use some ourselves, but they are relatively rare. The body of the class, including its instance variables and methods, are enclosed in a pair of braces, sometimes called ―curly brackets.‖ Whether you place the opening brace on the same line as the name of the class is the subject of discussion in some circles. It doesn‘t really matter. Programming Style – class names Class names are nouns, generally single (not plural) nouns. Thus we could have a class names Textbook; we would not have a class named Textbooks. Be careful with your class names; there are some words in English which are singular but end in the letter ―s‖. For example, Player, Team, and League are all acceptable class names. Statistics may be an acceptable class name, since the word statistics may be plural or singular, and statistic may not be a meaningful word, depending on the situation. Remember that class names always begin with a capital letter. If the class name contains several words, all are capitalised, for example DepartmentStore. Instance variables Looking back at the code, we have six statements allocating memory for the six data items (instance variables) that each object contains.
private String studentNumber; private String studentFirstName; private String studentMiddleName; private String studentLastName; private String studentPreferredName;

26

private String studentFullName;

Each of these lines is a separate Java statement. A Java statement ends with a semi-colon (;). A Java statement may extend over more than one line, but it must eventually end with a semicolon. Each student has a number and name(s). Note that all these instance variables are declared private. The only way the outside world may access these variables is via the getters and setters which we examine below. Remember that the name of an instance variable begins with a lowercase letter. If the name actually contains several words, the second and subsequent ones are usually capitalised. studentNumber is a good example of this. After identifying these instance variables as appropriate for a name, I read (in The Globe and Mail, a newspaper published in Toronto, Canada, on, 2006-08-16) about the inhabitants of Norfolk Island. Descendants of the Bounty mutineers, there are very few family names represented on the island. The phonebook for Norfolk Island includes nicknames for the inhabitants. Perhaps we should include a nickname attribute! Programming Style – instance variables All of these instance variables are of datatype String. That is they are instances of the String class; thus they are objects! The name you choose to give an object should be meaningful. That is, the name should convey some idea of the object‘s purpose or role. If so, then you do not need to provide documentation of what the object represents. For example, studentNumber really needs no further documentation (although you may provide it should you wish), while an instance variable named x does need further documentation. Constructor(s) Continuing our examination of the Java code, we see that the instance variables are followed by a constructor. We know it is a constructor not just because the documentation says so but because it has the same name as the class. This constructor is executed whenever we need to create a new Student object. A constructor uses the values we provide as parameters to initialize the instance variables for each object we create.

27

Within a constructor, my programming style is to use the name of the attribute as the name of the parameter. That leads to statements like
this.studentNumber = studentNumber;

which means, in English, take the value provided as a parameter (studentNumber) and save it (the equals sign) in another location. The reserved word this means ―the current object‖. Thus, this.studentNumber refers to the studentNumber attribute (or instance variable) within the current object; that is where the value in the parameter is saved. It is possible to have many constructors in a class, as long as they have different parameters, different that is in type or in number. You cannot have two constructors, both with two Strings as parameters. But you could have one constructor with two Strings, and another constructor with a String and an int as parameters. Perhaps all you know about a Student is the student number and name, but you don‘t have the preferredName; the student will provide that later. A second constructor could then be the following.
public Student(String studentNumber, String studentFirstName, String studentMiddleName, String studentLastName, String studentFullName) { this.studentNumber = studentNumber; this.studentFirstName = studentFirstName; this.studentMiddleName = studentMiddleName; this.studentLastName = studentLastName; this.studentFullName = studentFullName; this.studentPreferredName = “”; } //end constructor

Since we don‘t know the preferred name, we simply remember an empty String, signified by the consecutive double quotation marks, with no characters between them. Recall that we said earlier that a method is Java‘s way of handling messages. If you send a message, you must identify the receiver, and we will see how to do that later. You must also identify the message. Part of the message is its name but part is its parameters. If you ask a friend for dinner, that is a part of the message. The rest of the message involves the choice of the restaurant and the time at which you would like to meet. The name of the restaurant and the time are parameters, the variable parts of the message. When we send a message to create an object, we usually provide the values the instance variables are to assume. These values are the parameters. We have seen several assignment statements, the ones using the equals sign, which transfer the values of the parameters into the values of the instance variables, and we have had a simple explanation of how that statement works. But what does it really mean to say this.studentFullName = studentFullName;? Start with the names of the variables. When a computer stores data, it uses its memory. Each memory location is assigned a unique address. You could write programs that use those

28

addresses, but it is very difficult to keep the addresses straight in your mind, so today we use an association between names that we understand and the numbers of memory locations. The process of translating our program from Java into something the computer can understand directly (the addresses) is called compiling. The program we use to do this compiling is called a compiler. The Java compiler is called javac. Of course, the ―c‖ part of its name stands for ―compiling‖, and the ―java‖ part stands for, well, Java. When we write our program, we use names for the variables we wish to use. The compiler establishes a correspondence between the names we use and the numeric addresses the computer knows. An object requires a block of memory, a collection of memory locations. The block of locations is referred to using the address of the first location in the block. An object has an address, and so do each of its instance variables. So too do each of its methods. Thus, when we refer to the variable this.studentFirstName, we are referring to the variable studentFirstName within the current object. Java‘s shorthand for ―the current object‖ is this. Thus, this.studentFirstName refers to a specific area of memory within the memory the computer has allocated to the current object.
studentFirstName (without the this) is another, different, variable. It represents the name which we provide to the constructor. studentFirstName is a different area of memory from this.studentFirstName.

So now we have two areas of memory that are involved in this assignment statement, a statement which calculates a value and assigns it to a variable. Now consider the equals sign. In mathematics, an equals sign means that the values on the two sides of the equals sign are identical. In computing, an equals sign is an instruction to make a copy of the memory associated with the variable name on the right of the equals sign and copy it to the variable on the left hand side. After that copy is complete, the two areas of memory contain identical values. In fact this is not strictly true. If we were to look inside a String, we would find that it contains an address of memory. If you go to that address in memory, you will find the actual contents of the String. When we say
this.studentFullName = studentFullName;

we are actually saying that the address contained in this.studentFullName should become the same as the address contained in studentFullName. We will see this in the exercises to this chapter when we inspect the objects we create. Programming Style – constructors Giving the constructor and the class the same name is not just style, it‘s one of the rules of the language.

29

it must be declared public (allowing the method to be called from outside the class). In this example. Getters and setters So far we have seen the class header. /** * @return student number */ public String getStudentNumber() { return studentNumber. all correctly documented. } Getters return a value to wherever the method was called. but it is a very common style and other styles may confuse other programmers (including your professor) with whom you work. or studentNumber = aStudentNumber. It is left as an exercise to the reader to provide the other getters. Thus it is appropriate to say ―you may see. studentNumber = inStudentNumber. A third style which you may see is to precede each parameter with a specific letter or phrase.‖ Sources of programs to read are other textbooks. though not part of the language. Depending on which style is chosen you see statements like this.You do not need to follow my style of naming the parameters and instance variables identically. Continuing our examination of the class. Having the parts of the class in this order is a very common standard. The Java statement to return a value from a method is simply the word return followed by the value. we find the getters and setters. magazines. and you should follow it. and the constructor. As such. The body of the getter is very simple. It must provide a datatype describing the value returned. and open-source projects. A different style which you may see is that instance variable names all begin with an underscore. 30 . We need one getter for each instance variable. and see how they have done it. One way to learn how to program is to look at what others have done. We know that a method is a getter because its name begins with ―get‖. the instance variables. By using this style. we have one getter. you may write _studentNumber = studentNumber.

studentNumber = studentNumber. The visibility is public. the datatype of the value to be returned (or void when nothing is being returned). so it must specify a void datatype. a method which allows us to display the contents of an object. } A setter must be declared public (allowing the method to be called). We need one setter for each instance variable. Given their names. all correctly documented. we have one setter.). The parameter list. the name of the method. The method name is toString. All the methods we write will have a visibility modifier (the ones we have seen are public and private). Setters do not return a value to wherever the method was called. } Note the structure of this method and how it compares to the discussion above. Getters and setters. as a String */ public String toString() { return ″Student number: ″ + studentNumber + ″ Student name: ″ + studentFullName + ″ (″ + studentPreferredName + ″)″ . toString Earlier we mentioned the toString method. The end of the method name is the name of the attribute being manipulated. like all methods. though. will have some documentation. The datatype returned is a String. the name of a getter method always begins with the word get and the name of a setter method always begins with the word set. We‘ll see an example of this momentarily. Programming Style – getters and setters As noted above. the parameter list (which may be empty. and the body of the method. It is left as an exercise to the reader to provide the other setters. with its first letter capitalized.Finally. Here it is. this documentation may be quite minimal. We know that a method is a setter because its name begins with ―set.‖ /** * @param student number */ public void setStudentNumber(String studentNumber) { this. /** * @return a Student. in this 31 .

Those four parts make up the method header. where we specify the value. It will appear as typed. method body.case. All methods have this structure: method header. Note its similarity to the structure of a class. Since we wish to be able to call this method from elsewhere. Since it is returning a String. and a closing brace. We will do that in parentheses after the full name. and we continue constructing the final result. it needs to be public. Note that sometimes you prepend. In this example. the opening and closing double quotation marks for a string literal must be on the same line. return ″Student number: ″ + studentNumber + ″ Student name: ″ + studentFullName + ″ (″ + studentPreferredName + ″)″ . then an opening brace. this one being the value of the instance variable studentNumber. all of the work is done in the statement which begins return. as we append (add to the end) items. The plus sign (+) indicates that what you have so far (a description) is to be followed by another String. you have an empty string. one after the other. The name toString is a name that has been adopted by many classes. followed by the class body. its return type must be String. In this case. Thus. and then a closing brace. closing brace. as we saw earlier. opening brace. First appears the class header. 32 . is empty. enclosed in double quotation marks. When used with Strings. The concatenation symbol is the plus sign. If there is nothing between the quotation marks. the plus sign is known as the concatenation operator. toString continues by adding an opening parenthesis. two are descriptions of what the instance variable represents. Perhaps it would be nice to show the preferred name since it may not be obvious. which is followed by an opening brace. and a closing parenthesis. Note that this Java statement illustrates the idea that a statement may extend over many lines in your editor. Once the complete String is available. and some are just punctuation. a literal may not extend over more than one line. This is followed by the method body. but without the quotation marks. One String followed by another one is still a String. into a long String) several shorter Strings. It describes the value the method will send back to the method which called this one. Next we append another description ―Student name:‖ and the value of the instance variable studentFirstName. we combine seven Strings. Three are the values of instance variables. However. ″Student number: ″ is a description. it is returned to the method which asked for it. The String which will be our result is getting longer. or add to the beginning of an existing String. It is an example of a string literal. the value of the instance variable studentPreferredName. containing whatever text you would like to display. That value is built by concatenating (putting together. That is.

Thus. too. there is a URL class in the Java libraries. and the URL of its website. the only instance variables are the name of the college. // build the String by concatenation return result. we‘ll add other instance variables. private String phoneNumber. of course. // start with an empty string String result = “”. If we wish the telephone number to be formatted with parentheses and hyphens. a String is adequate here. including the mailing address of the college. Creating another class. Thus we will be able to ask any object to display itself in a form we can read. there is no question about it being a String. let‘s create another one. the first attempt at creating a College class could be /** * * @author rick * @version november 2006 */ public class College { // name and contact information private String name.Programming Style – toString All classes will have a toString method. the people it employs. this time to model the college itself. a list of the students it enrols. the method may look like this. 33 . What are the instance variables we need? For now. the College Now that you have seen how to create and test classes. As we progress through this book. In other cases. What is the appropriate datatype for the URL of the college‘s website? It too is a String. and the courses it offers. there is only a return statement in this method. we‘ll model the college very simply. Yes. its phone number. but we won‘t use it for now. In some cases. What is the appropriate datatype for the telephone number of the college? Since we‘re not going to do any calculations with the ―number‖. What is the appropriate datatype for the name of the college? A String.

the process to create this code is as follows. } public String toString() { return name + '\n' + phoneNumber + '\n' + homePage. } public void setName(String name) { this. } public void setHomePage(String homePage) { this. this. } } As mentioned above.name = name. // constructor public College(String name. this.name = name.private String homePage. } public void setPhoneNumber(String phoneNumber) { this. } // name and contact information methods public String getName() { return name.phoneNumber = phoneNumber.homePage = homePage. } public String getPhoneNumber() { return phoneNumber. o o o o o o Identify the name of the class Identify its state.phoneNumber = phoneNumber.homePage = homePage. its instance variables Identify its behaviours. String phoneNumber. String homePage) { this. its methods Implement the constructor Implement the toString method Implement the getters and setters 34 . } public String getHomePage() { return homePage.

getters. setters. Now we need to see how to communicate our program to a computer. we will look at that feature when we need it. We needed to talk about constructors. If we need some special feature of language to build that model. Thus. 35 . we needed to speak about modelling and Java in this chapter. and the toString method. My approach to teaching programming is to discuss a model of something and then build the model.Summary That‘s it for your introduction to Java.

Complete the setters for the Student class. Complete the getters for the Student class. What modifications would we need to make in our College class to use the URL class? One simple class to model is a door. and thickness. you may wish to model whether the hinge is on the left or the right. height. 7. Choose one of those classes and identify the attributes it could contain. An automobile is suitable. Complete the Professor class. or an MP3 file. you will need to use int (or double) and boolean variables. including getters. Furniture. 3. 4. What datatypes are appropriate? Why did you choose those datatypes? Explore the online documentation for the URL class. and Building. A door has width. 2. 36 . What is its name? What are its attributes? What are its behaviours? 5. 6. For a good solution. Consider some other real-world classes which you may have seen. we have mentioned several other classes we could develop. As an additional complication. setters. It is either open or closed. Choose one of these classes. These included Room. In this chapter. Implement a Door class. So is a digital camera. The URL for the documentation is given in the chapter. and toString.Exercises 1. a digital photograph.

 A tool for creating and testing classes. and by indenting statements according to standards. A compiler is a program which translates Java statements into something the computer can understand. This IDE provides us with many tools:  An editor which understands the syntax (the grammar or the rules) of the Java language. BlueJ BlueJ is an integrated development environment (IDE) which we will be using.  A link to a Java compiler. A program is designed to be executed by a computer.) 37 . you will be able to:       Start BlueJ Use BlueJ to create a class diagram Use BlueJ‘s editor to create and modify classes Use BlueJ‘s Object Inspector to examine objects Define unit tests Use BlueJ to create and run unit tests Introduction So now we have some source code. the editor helps by colouring reserved words. so we must have a way of communicating the program to the computer.  A debugger (which we can use to fix hard-to-find errors. Testing is crucial to ensuring that your code works correctly. BlueJ draws class diagrams but none of the other diagrams which are included in the UML. There are many tools which will allow us to communicate with the computer. for a Student class. written in Java.  A simple UML diagramming tool. We will use one called BlueJ. You use the editor to type the statements in your program. by showing you matching braces and parentheses. Having it included in the environment is very important.Chapter 2 – Introducing BlueJ Learning objectives By the end of this chapter. The computer can not directly understand Java statements. By understanding the rules of the Java language.

release N. The project skeleton that BlueJ creates already contains one file. and New Project from the drop-down menu. described in the next paragraph. That task is included as an exercise at the end of this chapter.‖ Then it identifies some headings under which you can insert information for the reader. BlueJ allows a space in the name of the project. or o From the column of buttons to the left of the class diagram. New Class. Tell the reader (someone who does not know anything about this project) all he/she needs to know. press and hold down the key. If your operating system allows a space in the name of a folder. You choose the precise location when you create the project. you should describe your project. BlueJ displays a class diagram. you have several choices. or o Press +N. you will need to install BlueJ and Java on your personal computer. and the first few lines of it tell you its purpose. or o Right-click a blank area of the class diagram and choose New Class. the New Class dialogue appears. Whichever you choose. and release . If you are doing your programming at a college or a university. ―Here. so you may decide to double-click it to see what it contains. choose Project from the main menu. Creating a new project Start BlueJ. To place a class on the class diagram. Give the project a meaningful name. The file is a project ―readme‖ file. That is. Once BlueJ and Java are installed. The title on the window containing the class diagram is the name BlueJ followed by a colon and the name of your project. 38 . choose New Class. This is the beginning of the documentation you will be creating. press N (either uppercase or lowercase). The icon for the file looks like a piece of paper. and places that file on it. If you wish to do some work in Java elsewhere. o From the main menu.An integrated development environment provides access to all these tools through one common interface. Each project is stored in a separate folder on your computer. BlueJ will probably have been installed on the computers you will be using. you can continue to create a new project. choose Edit.

is to capitalize each word of the class name which contains more than one word.) BlueJ updates its class diagram. You could use underscores to separate individual words in a class name. as we have seen. and click Ok (or press . it‘s good to know which have been compiled and which have not. But later on. that‘s fine since we don‘t know how to compile it. when you have many classes.Type the name of the class. The class displays diagonal lines as a visual reminder that it has not been compiled. Right now. Since it hasn‘t been compiled. Note that Java requires that class names contain no spaces. 39 . we can‘t use any of its features. and are making changes to several of them. in this case Student. but the standard.

delete the rest. then Preferences from the drop-down menu. an opening parenthesis is (. A closing parenthesis is ). the IDE will momentarily highlight the matching opening one. we‘ll need them later. After you have entered the declarations for the instance variables. so you‘ll see more errors after you fix one than you had before. If you don‘t see the error. Sometimes one error will hide another. continue entering the other getters and setters. IDEs can also match parentheses and braces.) BlueJ provides you with a skeleton of a class. Enter the Java code for the Student class which we seen above. But never fear. Don‘t forget getters and setters for each instance variable you created. When you type an opening double quotation mark. Are there any obvious errors? If so. right. and BlueJ will offer some hints about what the error may be. uncheck the appropriate combo boxes. Since the IDE knows the language you are using it can make intelligent decisions about indenting. 40 . In typesetting there are two double quotation marks. When you first run BlueJ.To see the contents of a class. These are particularly useful when entering similar methods. Save (or press +S) to save your work. Click the Compile button to both save and compile the class. possibly checking ―Make backup of source files‖ also. the declaration of an instance variable and a method. Don‘t delete the first few blank lines. There are a number of advantages to using an IDE. When you type a closing parenthesis or brace. or unexpected colours. an opening one ― and a closing one ‖. Remember that the editor allows you to cut-and-paste. the screen will show red characters until you type the closing double quotation mark. so don‘t worry about fixing every error at the same time. If you have forgotten your punctuation symbols. The double quotation mark in programming is ″ and the same mark is used at the beginning and end of all strings. the documentation and Java statements it contains. you‘ll soon reduce the number of errors to zero. An opening brace is { and a closing brace is }. and search-and-replace. Sometimes one error will cause many others. It can display different aspects of the language in different colours. When you have no more errors. On the Editor tab. the compiler will find them and BlueJ will highlight (in yellow) the line containing the first one. Click Class. choose Tools from the main menu. stop. If you wish to suppress these helpful features (why would you want to?). and the constructor. fix it and compile again. If you have made any errors. fix them. click the question mark in the lower-right corner of the BlueJ window. some documentation. Keep what you need. If you see the error immediately. I leave mine that way.click the class and choose Open Editor (or double-click the class. Look at what you have typed. you will find that most of the combo boxes are checked. Obvious errors will make themselves obvious by unexpected indenting.

A main principle behind Java is that you can write a program on one type of machine and have it run on others. It doesn‘t matter which one you click. Save from the menu in the main BlueJ window. I list the constructors. click the Compile button again. Virtual machines and bytecode Every type of computer uses its own instruction set for the commands it executes. The order in which you list the declarations of the instance variables does not matter. When you compile a Java class. and one in the main BlueJ window.class file). Sometimes I list all the getters and then all the setters. Following the instance variables. Nor does the order in which you list the methods. Note that there are two Compile buttons. 41 . When you are finished typing. or vice versa. Later on we will have many classes open at the same time. choose Class. you translate from the Java statements themselves (stored in a . It translates the instructions output by the Java compiler (known as bytecode) into the appropriate instruction set of the host computer. This saves your work but does not compile it. using Project.Enter the toString method as well. This miracle works because there is a virtual machine involved. Save from the menu in the window containing your class. Open Project. Assuming you haven‘t left (or you have returned and opened the project again. without change. or Project. Now all your work has been saved should you need to leave. Open Recent). Then it may be more efficient to choose Project. These instruction sets are very complicated and depend on the design of the CPU your computer is using. This Java virtual machine is just a program which pretends to be a computer running its own language.java file) into the instruction set of the virtual machine (stored in a . It depends on the style you (and your teacher) prefer. Then I list the getters and setters. And sometimes I list a getter followed by its setter. sometimes I do the reverse. This normally makes it difficult to run a program on one type of CPU when it was designed for another. one in the window where you have entered the class. I usually list the toString method after the getters and setters. and save all the classes you have open.

student1 is acceptable for now. Both are done through the window shown below. as an example. The noted science fiction author Arthur C.org/wiki/Clarke's_three_laws) I use magic in that sense. plus Open Editor. Well.‖ (http://en. you can develop Java programs using a Macintosh computer. Testing the Student class Recall that the methods in the Student class (and the class itself) needed to be declared public so that some other methods can use them. Then you need to specify the parameters the constructor expects. The big deal is to develop on a Macintosh and then run on an IBM mainframe using the Linux operating system. Clarke said that ―Any sufficiently advanced technology is indistinguishable from magic. Create Test Class. Recall that a constructor allows you to create an instance of the class. simply click the name of the constructor. The getters and setters. 42 . you need to specify the name of the object. simply right-click the Student class in the class diagram. Compile. and toString. it‘s not really magic. separated by a line. By clicking the name of the constructor. For now. For now. but you can change it if you wish. in the background. We will explore those options later. Yes. Remove. however. First. cannot be used until we have created an object. A menu appears showing the public methods of the class. however it‘s not such a big deal. The reference to ―lifting the curtain‖ comes from the movie The Wizard of Oz. Inspect. and run it on a PC running Windows. Later we will lift the curtain and see what is in the background. The benefit of using a tool like BlueJ is that we don‘t need to create any of these other methods right now. and. an object. It is highlighted because it is the only method which you can call now. Now. you can do that too.Due to this virtual machine. you run the constructor.wikipedia. BlueJ takes care of the details by magic. In the old days that was quite a thrill.

and how one string contains the address of another. you may use an empty string for any or all of the parameters. so should be enclosed in double quotation marks. Try executing some of the getters and setters you wrote. to guide you in providing parameter values. Note that the documentation you placed at the beginning of the method appears in this dialogue. Were you like me and you specified you own name? Or were you more creative? 43 . The Object Inspector window appears. Create a couple more students. It shows the values you specified for the parameters. at least one of which does not have a preferred name. At the moment. Click Ok when you have specified all the parameters. Inspecting an object Recall that in the previous chapter we talked about the meaning of the equals sign. Right-click an object. Choose Inspect from the menu which appears. See how the result changes depending on whether or not there is a preferred name.Remember that all the values being passed to the constructor are Strings. Once BlueJ has created an object. now that we have objects on the object tray. Try some experiments with them. fix them so they do produce the correct answer. To experiment with an object. right-click it in the object tray and execute one of its methods. it appears in the object tray at the bottom of the BlueJ window. Do they produce the correct answer? If not. We can see this. Be sure to execute the toString method for the Student objects you created. Remember that you can use an empty string (―‖) to represent a value you do not know or do not wish to provide.

This is a reference to. The first (length) is the number of characters in the String. I‘ll assume we left studentNumber highlighted. In a similar way. We see that the String actually has two instance variables of its own. the Inspect button is disabled. Now we are looking under the hood. If you click Inspect in this dialog. you will see the image below. 44 . Now that we are as deep into a String as we can go. I entered six characters. at how Java represents a String. we can see how the studentFullName is stored. I was lazy and repeated the same digit over and over.Highlight any of the six instance variables by clicking them. The line reading private char[] value shows an arrow. showing the characters which make up the student number. and then click Inspect. For the next two illustrations. another area of memory. or the address of. The other contains the actual characters. That area actually contains the contents of the String.

Click Close as many times as necessary to close the Object Inspector. there is too much information to show in a window of the default size. so a scrollbar allows you to see the rest of the information. 45 .In this case.

Ideally. If zero is correct data. Correct data means data which is reasonable to expect. 46 . and 19. BlueJ provides access to a tool named JUnit which facilitates this testing. When you change the order by which you sort some data. each test case is separate from the others.Unit testing . The procedure is to write test cases for all functions and methods so that whenever a change causes a regression.‖ The word ―regression‖ refers to the need to redo previously-passed tests and ensure that the code still passes them. 5. o That setters change the correct instance variable to the correct value. with whatever data came to mind. and 6 at the lower end.definition The testing we just did to see that the object was created correctly is a form of ad hoc testing. Note that 4 and 21 are incorrect data. data that is on the boundary between correct and incorrect data include 4.wikipedia. JUnit is a testing framework. I guarantee you will break some other code. you‘ll need to know that the getters are correct. o That each method behaves correctly when you provide wildly incorrect data. and 21 at the upper end. what happens when you provide 100 or -43 as input? o That getters return the correct value. 20. this involves testing components individually. Breaking code refers to having previously-working code stop working due to some change you have made. To test setters. Ad hoc testing would be very difficult. and we may need to test some many times. make sure you test it. create and save a series of unit tests so that we can use them over and over again as necessary. … This type of testing is mostly done by the developers and not by end-users. it can be quickly identified and fixed. When you change a datatype from one type to another. Suppose you made a major change and want to make sure that you have not broken any other code. 6. you‘ll probably break code.org/wiki/Unit_testing) tells us that ―a unit test is a procedure used to validate that a particular module of source code is working properly. while 5. o That each method behaves properly when you provide input that is on the boundary between correct and incorrect.junit. described in more detail at www. o That toString returns the correct value. If the method expects integer input with values between 5 and 20. Normally we wish to test all the parts (the units) of the system. After a change. Using the previous example. a better way to test is to do systematic unit testing. you will perform regression testing. To do this. 10 and 17 are examples of correct data. What things should you test through unit testing? o That each method behaves properly when you provide ―correct‖ data. Using the previous example. and 20 are correct data. 19. Wikipedia (http://en.org.

and click ―Show unit testing tools. Preferences. Choose Create Test Class.‖ Then click Ok to dismiss the Preferences dialog and right-click the Student class again. The test class for Student is thus named StudentTest. use the main BlueJ menu and choose Tools. 47 . Miscellaneous. If ―Create Test Class‖ does not appear.Unit testing with BlueJ Let‘s create a series of unit tests for the class Student. Right-click Student in the class diagram and choose Create Test Class. BlueJ names test classes by taking the name of the class being tested and appending the word Test.

One possibility is to create the objects anew in each test.. before the default constructor and its comments. enclosed in guillemets. My preference is the latter. to mark the beginning and end of speech. StudentTest will follow along. In this context s is a meaningful variable name. Unit tests are green. adding author and version information. s2. or we can create then once and then use them in all the tests. And so are s1. In the unit test class. These declarations are of the form private datatype variableName. click on the Student class and drag it down a little.This may not look exactly like what you see. Yes. including French. These objects will exist during all of the tests. These symbols have been adopted in the UML. A class is clearly shown as a unit test by the words unit test. much as English uses the double quotation marks. we need some objects. Open StudentTest in the editor. when that happens. Note that BlueJ continues its practice of colour-coding parts of the diagram. enter private Student s. and s3 if you need several objects! As a general 48 . These symbols are used in some languages. declare the objects you‘ll be using. To do the test. You can‘t do the same thing by dragging the test class. In our case. I know that I previously insisted on meaningful variable names. My unit test was drawn too close to the top of the window. Document it properly.

49 . Here‘s a sample test for the getStudentNumber method. and then did the unit tests in varying orders. and place the result we expect in the test. If we initialized the object when we declared it. If I need several tests for the same method. This sounds an unusual way to do things. o Has a name that consists of the word test followed by the name of the method being tested. Here we give it a value. o Returns nothing (or void). a digit. Note the use of the word ―beforehand‖ in the middle of the previous paragraph. we could change the state of the object. but that is not necessary. In the setUp method. we are guaranteed to know the state of the object before each test. We would not know for sure its state (the values of the instance variables) before a test and so we would not be able to forecast the results of the test beforehand. we describe any processing which must take place after each test. we need to write nothing in tearDown. ″Richard D. By doing the initialization in the setUp method. public void testGetStudentNumber() { assertEquals(″123456789″. o Carries out some processing and produces a result. Every test: o Has public visibility. we need to create a Student object. Gee″). ″Dennis″. I capitalize the first letter of the method being tested.rule. By initializing the objects in the setUp method. generally initialization. for example. in unit tests. In this test.getStudentNumber()). the outcome of one does not affect the outcome of another. This unit test class skeleton contains three methods. deciding if it is correct. when necessary. s. In the tearDown method. but it doesn‘t have an area of memory associated with it. Thus. which must take place before each test. to distinguish between objects. I will generate variable names by taking the first letter of the class being tested along with. ″Gee″. We will not run a test and then look at the result. o Uses an assert statement to check that the result matches the expected result. I place a sequence number at the end of the method name. We will determine what the result of the method should be before testing it. Generally. once for a student with a preferred name and once for a student without a preferred name. The variable was declared. ″Rick″. s = new Student(″123456789″. we will need testToString1 and testToString2 since we need to test that method twice. Then create the tests you wish to perform. but you will see that it works. we describe any processing. we need to write nothing in the constructor. Each test is similar. ″Richard″. so it has no value. the tests are independent of each other. That is. Generally.

we can test that the setStudentNumber method also works correctly. } While this test seems overly simple. Then we use the assertEquals method (with the expected value coming first. so there is no confusion. assertEquals is a method provided as part of JUnit. public void testSetStudentNumber() { // change the student number s.TestCase { private Student s. Since the attributes have private visibility. we use the getStudentNumber method on an object whose student number we know. public void setStudentNumber(String stuNumber) { this. /** 50 .studentNumber and studentNumber refer to the instance variable. Consider the following method. and then the actual value coming second) to check that the student number returned is the expected value. s. If there is no confusion.studentNumber = studentNumber. Once we are sure that the getStudentNumber method is working correctly. } This will compile but will not give the correct result since the value of the parameter is never saved. this may be omitted. // confirm that the change took place assertEquals(″678678678″. /** * The test class StudentTest * * @author rick gee * @version 2006 04 20 */ public class StudentTest extends junit. Both this. so we need to test the getter first. In the method shown. The test for the setter involves the getter as well.In this test. To retrieve them from outside the object we use a getter.getStudentNumber()). When there is confusion between the name of an instance variable and a parameter. the instance variable must be prefixed with this.setStudentNumber(″678678678″). the parameter and the instance variable have different names. Here is the complete unit test for the studentNumber getter and setter. To modify them from outside the object we use a setter. we can only access them from inside the object.framework. We use the actual name of the object followed by a period and the method we wish to use. you may find it fails if you made a typing mistake which nevertheless was correct Java.

* * Called before every test case method. JUnit will indicate that very clearly. Gee″). the second is a String containing the actual value. This method comes in many forms. */ protected void setUp() { s = new Student(″123456789″.getStudentNumber()). ″Gee″. */ protected void tearDown() { } public void testGetStudentNumber() { assertEquals(″123456789″. } public void testSetStudentNumber() { // change the student number s. // confirm that the change took place assertEquals(″678678678″. That is. they should be the same. we change the student number and then retrieve it. so we test that the correct value is returned. the first parameter is the answer we expect. the assertion will fail.* Default constructor for test class StudentTest */ public StudentTest() { } /** * Sets up the test fixture. Of course. s. ″Dennis″. ″Richard D. the second is what the program gives us. If they are not the same. } } As part of each test. The first is a String containing the expected value. we use the assertEquals method. * * Called after every test case method. In testGetStudentNumber. returned from a method. ″Rick″. the one we use takes two parameters. Technically this is perhaps better 51 . In testSetStudentNumber. s. we know the student number we used to create the student. ″Richard″. } /** * Tears down the test fixture. We know what the expected value is.getStudentNumber()). and the test will fail. so we test that the value returned by getStudentNumber is the expected value.setStudentNumber(″678678678″).

called an ―integration test‖ since we are combining different methods and seeing that they work together. When we use JUnit in more advanced situations, we‘ll see some other assert methods. These include assertNull, assertNotNull, assertTrue, and assertSame. For details on all the assert methods, look at the documentation at http://www.junit.org and follow the link to javadoc. Notice that when you compile a class, the corresponding unit test class (if it exists) is also compiled. Unit testing – the results
StudentTest is on the class diagram, so we can right-click its symbol. The resulting menu offers

the possibility of running all the tests, or just one. When you choose to run all of the tests (usually a good idea), a window (shown below) appears showing the results of all the tests, one per line. (Of course a scroll bar appears in the upper portion of the window when there are many tests.) A successful test is shown with a green tick beside it. An unsuccessful test, one that failed for some reason, is shown with a black X beside it, if there is an error message available, or a red X is there is no error message available. For a failed test marked with a black X, you may click the message in the upper pane and abbreviations of the expected and actual values are shown in the lower pane. Note that a test may fail because the test was created incorrectly or because the method it is testing is incorrect. For example, in my test for setLastName, I changed the value of the lastName instance variable but retrieved the firstName instance variable in the assertEquals call of my test. I was sloppy when I cut-and-pasted. Of course the assert method failed. You want to see a green line across the middle of the test window; this tells you that all of the tests were successful. When any tests fail, the line is red.

52

Below the line, is the number of tests run, and the number of errors detected or tests that failed. We wish to test each method in the Student class. There are six getters, one for the student number and five for the parts of the name, and six setters. Thus we need to create 12 unit tests and ensure each test works successfully. Cut and paste, and be careful as you make changes! To test the toString method, we need thirteenth and fourteenth tests, one applied to a student with a preferred name, one applied to a student without. As noted above, these could be called testToString1 and testToString2. If you prefer, you could use the names testToStringWithPreferredName and testToStringWithoutPreferredName. Testing toString is a little challenging, since you need to remember all the literals which are added to the instance variables. Thus you need to implement 14 tests to ensure your class behaves correctly in all cases. Make it so.

Smoke testing
These simple unit tests are exhaustive. That is, they test everything an object can do. An alternative type of testing is ―smoke testing‖. A simple definition of smoke testing is ―Smoke testing is non-exhaustive software testing, ascertaining that the most crucial functions of a

53

program work, but not bothering with finer details. The term comes to software testing from a similarly basic type of hardware testing, in which the device passed the test if it didn't catch fire the first time it was turned on. A daily build and smoke test is among industry best practices advocated by the IEEE (Institute of Electrical and Electronics Engineers).‖, provided by http://searchvb.techtarget.com/sDefinition/0,,sid8_gci930076,00.html JUnit allows us to create many tests, and run only selected ones. When we run only a few of the tests, we are doing smoke testing.

The Professor class
In a similar manner, we must create the Professor class and unit tests for all the methods in the Professor class. Make it so.

The College class
In a similar manner, we must create the College class and unit tests for all the methods in the College class. You created the College class earlier. Ensure that all methods are tested and pass the tests.

Summary
That‘s it for your introduction to BlueJ. As I stated earlier, my approach to teaching programming is to model something and then implement the model. BlueJ and unit testing are crucial to building the model. An untested model is a useless model. No architect would build a structure without creating a model first. Of course the model may show flaws. That‘s better than building the structure and then finding its flaws. A Wikipedia article on the Tacoma Narrows Bridge shows what can happen when your model has flaws which you do not catch. http://en.wikipedia.org/wiki/Tacoma_Narrows_Bridge#Film_of_collapse Did you see how strange the output of toString looked when a student did not have a preferred name? We need to fix that. Thus, the next feature we need is some way of taking one of two branches, depending on some condition. This will also allow us to deal with some of the unit tests mentioned, checking if a value satisfies some conditions.

54

Exercises
1. Develop unit tests for all the methods in the Student class. Ensure that your code passes all the tests. My style is to develop the tests for the getters first, since they do not depend on the setters. The values of the instance variables are all set by the constructor. Test the toString method. It also does not require any setters. 2. Develop unit test for all the setters in the Student class. Ensure that your code passes all the tests. Note that the unit tests for the setters will require the getters. Thus you create the getters first, test them, and fix any errors they contain before you begin to write the setters. Create the Professor class. As you do so, develop unit tests for all the methods in the Professor class. Download (from bluej.org) and install BlueJ on your laptop or other home computer. Download (from java.sun.com) and install the Java SE Development Kit. Download (also from java.sun.com) and install the Java class documentation so that you do not need to be connected to the Internet while using BlueJ, unless you want to be, of course. Use Tools, Preferences from the main menu, and then the Miscellaneous tab to tell BlueJ where the documentation is installed locally. Use BlueJ to create a Student object on the workbench. Inspect it and see how the attributes are stored. In particular, what is stored when you provide an empty String for a parameter? When you write a book or make a presentation, you want everything to look as good as it can. One way to do this is to associate a Font object to each piece of text. http://en.wikipedia.org/wiki/Typeface gives an interesting background on type and its terminology. Read it. A Font class will need to provide the typeface, the point size, and an indication of whether the font is to use bold, or italic, or superscript, or subscript. Implement the Font class. To do this properly you may need to use int and boolean datatypes (what are they?) in addition to the String datatype. 7. One of the standard examples of a class is a bank account. Without downloading a BankAccount class from the Internet (yes, there are lots of them there!), design and implement a simplified BankAccount class. A bank account should know about its number, owner, balance, and the service charge per transaction. Test all the methods. The account should contain methods to make a deposit and to make a withdrawal. It is a

3.

4.

5.

6.

55

simplified bank account since it does not yet contain a record of all the transactions, so deposits and withdrawals affect the account balance only. In subsequent chapters, we will implement the record of transactions.

8.

A playing card is another example of a class. Different cultures have different playing cards. One type of card, a card used in the USA or United Kingdom, and countries in the Commonwealth, knows about its suit (hearts, diamonds, spades, and clubs) and its value within the suit. Images for the suits are available in Unicode. A playing card also knows how to draw itself.

Leaving the drawing for much later, create an AngloAmericanPlayingCard class, along with its associated getters and successors. Test all its methods. As an alternative, create a playing card class from your culture. In subsequent chapters, we will use this class to play card games. Where did the four suits arise? A possible answer is available at http://www.straightdope.com/columns/read/276/whats-the-origin-of-the-suit-designationson-playing-cards .

9.

―Die‖ is the singular form of the word ―dice.‖ Dice are used in many games. Model a die. What does a die know? It knows how many faces it has. Don‘t jump to the conclusion that a die always has six faces. There are five convex regular polyhedra (the Platonic solids) which can be use as dice. These regular polyhedra have all their faces identical; that‘s the ―regular‖ part of their name. The tetrahedron has four triangular faces. The cube has six square faces. The octahedron has eight triangular faces. The dodecahedron has 12 pentagonal faces. The icosahedron has 20 triangular faces. A die also knows how to determine the value that appears when it is thrown. To implement that we need to know a little about random numbers, something we will see later. For now, implement a Die class, having only a constructor and a toString method. In subsequent chapters, we will use this class to play a board game.

56

10.

Dominoes have a relationship to dice, as described at http://en.wikipedia.org/wiki/Domino. Design and implement a Domino class. Birders are people who watch birds and record the details of their watching. Every bird species has a common name (American Robin, as an example) and a scientific name (Turdus migratorius, for example). Design and implement a Bird class. Include all appropriate unit tests. We will explore the world of birding in the exercises of subsequent chapters. Consider the websites http://www.natureinstruct.org/dendroica/ and http://birding.bc.ca/ if you are interested in Canadian birds.

11.

57

58

Chapter 3 – Making decisions
Learning objectives
By the end of this chapter, you will be able to:  Describe situations when your program may need to make decisions  Use boolean variables  Write if statements  Use the online Java documentation to find out about classes

The if statement
As we noted at the end of the previous chapter, the output of the toString method may appear rather strange when you output someone without a preferred name, displaying () at the end of the name, instead of (Rick), for example. How do you suppress the printing of the parentheses when there is no preferred name to display? There are several ways to do so, all involving checking conditions. First, let‘s look at what we mean by conditions. Boolean algebra A statement like ―Today is Tuesday.‖ is either true or it is false. A statement like ―It is raining.‖ is either true or it is false. (Yes, there are statements like ―This statement is false.‖ which are neither true nor false. We will not deal with them here.) When we are dealing with conditions, we are dealing with statements or expressions which are either true or false. True and false are called Boolean values. The Java datatype containing Boolean values is, not surprisingly, boolean. ―Boolean‖ is a tribute to George Boole, a British logician (1815-64) whose life and work are described at http://www-history.mcs.st-andrews.ac.uk/Mathematicians/Boole. There is an algebra associated with these Boolean values, describing the rules under which they may be combined. You have seen one algebra already in your mathematics classes in elementary school, when you studied integers and the addition, subtraction, and multiplication operations. If you add two integers, you get an integer. If you subtract two integers, you get an integer. If you multiply two integers, you get an integer.

59

since there are many cases where you divide one integer by another but the result is not an integer. These statements are usually summarized in the following tables. That is. but only one with not. or. or zero. and not) and the values true and false. two with the or. and not false is true. The first two operations are binary. Not true is false. o A program may need to do different processing when a specified number of pieces of data have been processed. Boolean algebra is based on three operations (and. Not True False False True And True False True True False False False False Or True False True True True False True False What relevance does George Boole have to programming? To have computer programs do anything interesting. 60 . Two true conditions combined using and make a true. any other combination of two Boolean conditions combined using and produces a false. You may need to place footer on a page once a specific number of lines of data have been displayed. you need two Boolean values when you use the and operation. Two false conditions combined using or produce a false. as do a true and a false (in either order) combined with or. Think of a missing preferred name. the third is unary.Division is a problem. negative. Two true conditions combined using or make a true. o A program may need to do different processing if a string is empty or if it contains characters. o A program may need to do different processing when a number is positive. Think of printing text on a page. they need to be able to examine the data they are processing and make decisions about what to do next.

o A program may need to do some special processing when a data file is missing. The result of this combination is either true or false. so that Daylight Savings Time now begins three weeks earlier. The same way that two Boolean values anded together produce a true result only if both are themselves true. Most programming languages have an if statement which allows for these decisions. do so now by adding an hour to the time. and the time is 0200 or later. combined using the three Boolean operations. then several Boolean values anded together produce a true result only if all are true. if false. you have one or more conditions. and this is the first Sunday in April. for a net increase in energy usage. This is an attempt to save energy on the assumption that it‘s light outside longer so people don‘t need to turn on their indoor lights. depending on the result of the conditions being true or false. An if statement is a programmer‘s way of writing conditions and executing one of two different scenarios. This example contains four conditions. Most computers did this automatically by the following logic. All of these situations require evaluating conditions. whose results are either true or false. one series of statements will be executed. o A program may need to do some special processing when there is no more data to be processed. In an if statement. If today is Sunday. If it is true. Boolean algebra – an example For example. and this is the first Sunday in April.o A program may need to do different processing depending on a number being even or odd. Note that much of North America changed the rules in 2007. a different series will be executed. and the time is 0200 or later. 61 . Early indications were that people didn‘t go home but drove around. and doing different processing depending on the value of the condition.     Today is Sunday. and we have not already switched to Daylight Savings Time. thus saving some electricity but using more gasoline. and we have not already switched to Daylight Savings Time They are combined using the and operation. and remember that we have done so. We just switched to Daylight Savings Time. this paragraph is being written in early-April 2006.

Otherwise (as described in a clause beginning else). choose Help from the main menu. you have found that the constructor requires values for all its parameters. there is no preferred name. How do we know that such a string is empty? Its length is 0. You 62 . so simply return the number and full name. else return ″Student number: ″ + studentNumber + ″ Student name: ″ + studentFullName + ″ (″ + studentPreferredName + ″)″ . The relational operators are what we use to create simple conditions.‖ The double equal sign is an example of a relational operator. When that number is zero. and results in an error message. with the latter enclosed in parentheses. full name. (In the main BlueJ window. Using the Java documentation The Java language is well-documented. We combine simple conditions with the Boolean operators to produce more complicated conditions.length() == 0) return ″Student number: ″ + studentNumber + ″Student name: ″ + studentFullName. with three frames visible. and preferred name.A revised toString method Here is a possible revision to toString. It involves only one condition. The frame in the top left corner contains a list of all the Java libraries. Thus. Should they be identical.) I prefer the online version. then Java Class Libraries. Assuming you are using the online version of the Java documentation. your browser opens. you are looking at the output of javadoc (when online).) When you look at details on the String class. public String toString() { if (studentPreferredName. the number of characters between the quotation marks. one which checks the relation between its two operands. We determine its length by using a method of the String class. as it is always up-to-date. we had to provide a null string. When creating an object in BlueJ. } The logic used in this method is: Check the number of characters in the preferred name. The pair of adjacent equal signs is shorthand for ―Check the values on each side and see whether or not they are identical. or at an edited version of the output of javadoc (when using the dead-tree form of documentation. How did we find that there was such a method? By looking in the Java documentation for the String class. in some textbooks and online. the result of the comparison is true and otherwise it is false. which we represented as ″″. of course. Missing data is a problem. return the number.

Thus. Thus. If the condition is true (meaning there is no preferred name). Scroll down that list until you find String. the if statement allows us to distinguish between the two cases. Further details on the method are in the Method Details. To check if the length of a string in Java is zero. click it. return the value ″Student number: ″ + studentNumber + ″ Student name: ″ + studentFullName + ″ (″ + studentPreferredName + ″)″. we use the name of the variable followed by a period and the name of the method. find the length method. the second contains none.lang and then clicking it. (Why is that section of the documentation not in alphabetical order? I have no idea. Warning: there are many classes listed in this frame. The statement or statements describing the action(s) to take if the result is false begins after the word else.length() is the number of characters in studentPreferredName. When a string contains many characters but only blanks. ― ‖ is different from ―‖. This is the same way we used the name of a variable followed by a period followed by the name of a getter or a setter. simply return the value ″Student number: ″ + studentNumber + ″Student name: ″ + studentFullName. or it is not empty and its length is greater than zero). and thus its length is zero. The first contains two blanks. The large frame on the right of the screen now displays the javadoc output for the String class. If the condition is false (meaning there is a preferred name). The bottom frame would then show all the topics available from the java. studentPreferredName.‖ Since there are only two possibilities (the string is empty.could start there (if you know the name of the library which contains your target). In particular. In either case. We use this method to determine how many characters are in the string.) A value of 0 tells us we are dealing with an empty string. a value greater than 0 tells us there are characters in the string. an int. Scroll through it to find descriptions of all the methods this class supports. This is probably the best solution until you know which classes are in which libraries. public String toString() { 63 . it will have a non-zero length. and scroll down until you see String. The statement or statements describing the action(s) to take if the result is true begin(s) immediately after we test the condition. Look in the section of the documentation entitled Method Summary. Or you could use the frame in the bottom left corner.length() == 0) Recall that the pair of equals signs is shorthand for ―check the values on each side and see if they are identical. To determine the length of a string in Java.lang library. once you have found the String class. by looking at the value it returns. we write if (studentPreferredName. by scrolling down the list until you see java.

In that case. } return result. result = result + “Student name: “. Note that not is represented by the exclamation point. the braces are not required. If there is only one. without adding the braces. Therefore a common style is to enclose the statement(s) for true and the statements(s) for false in braces. if (studentPreferredName.length() == 0) { result = “Student number: “ + studentNumber. or you may use one if statement within another. and you may use || for or. It may take several statements to describe the action. result = result + studentFullName + “(“. else return ″Student number: ″ + studentNumber + ″ Student name: ″ + studentFullName + ″ (″ + studentPreferredName + ″)″ . enclose the statements in braces. result = result + studentPreferredName + ″)″ . } 64 . We will see these possibilities later on. public String toString() { String result. even if there is only one statement.if (studentPreferredName. result = result + “Student name: “. if it does compile. You may wish to do several things when the condition is true instead of just one. it may not produce the correct results. } If you wish to combine more than one simple condition in a larger condition. your program may not compile and.length() == 0) return ″Student number: ″ + studentNumber + ″Student name: ″ + studentFullName. result = result + studentFullName } else { result = “Student number: “ + studentNumber. If you add another statement. Programming style – if statements if statements are usually much more complicated than the one we have seen. you may use the symbols && to represent and. but having them there may save some problems later. Some authors suggest you should always use braces when working with if statements. The pipe symbols used to make || are typically on your backslash key. This alternative toString method illustrates this use of braces.

BlueJ extensions are features which have been added to BlueJ. but nothing if it is false. a jar file may contain . and the . Now is a good time to introduce a BlueJ extension called Checkstyle. but not by the BlueJ development team. but has a wrapper around it that allows it to operate within the BlueJ environment.sourceforge. do a little more processing. Click it. Then open BlueJ and choose Tools. the text early on the page notes that Checkstyle was not written for BlueJ. You can see this by opening a . On the left is a list of the classes in your project. move it to the extensions folder within your BlueJ installation. A window appears containing two panes.doc. but I‘ll leave it to you to explore them. As you click each. Follow the Download link. There are many different style files available. 65 . .java files. Click the latest .) and save the file. A . look at the ―Code Conventions for the Java™ Programming Language‖ document.net/. For Sun‘s standards.jar file in an unzipping program.html files which document the classes. an open-source project described at http://jcsc.sun. Thus. Consider the following alternative version for toString. Here is another tool which can check if your Java code meets coding standards. This program comes with a collection of rules for standards you may accept and it allows you to set your own rules.org/extensions/extensions. The Checkstyle extension will appear on the menu. you may wish to explore the Java Coding Standard Checker. available at http://java.bluej.jar.html.html Simpler tests Sometimes you have processing in which you do nothing if the condition is true but do something if the condition is false. but don‘t unzip it. or you do something if the condition is true. if so. the right pane lists the style violations found in that class.com/docs/codeconv/html/CodeConvTOC. Once it has been downloaded.class files. Visit that site and scroll down until you find Checkstyle. To create this version. You can find a list of the extensions which are currently available at http://www.Braces are necessary in this method since several statements are processed when a decision is made of which path to follow. We do that processing and then we use the relational operator greater than to see if there is a preferred name and.jar file (as I review this in May 2010 the link is labelled Checkstyle-extension4.jar file is a Java archive.3-0. a zipped collection containing all the files necessary to use a collection of Java classes. we first notice that some of the processing in the previous version is the same whether there is a preferred name or not.

} return result. everyone has a number. 66 . At Okanagan College. Does your solution look like this? public boolean isInternational() { char firstDigit = studentNumber. Use the charAt method in the String class to extract the first digit of the student number as a char. Not surprisingly. which will examine the student number and decide whether the student is an international student. for testing equality. <= (less than or equal). if (firstDigit == '9') return true.charAt(0) == '8' || studentNumber. isInternational. } The first relational operator we saw was ==. Anyone can have any number. there are other relational operators. } Or does it look like this? public boolean isInternational() { return studentNumber. More complicated tests The chapter began with an example that combined four conditions and mentioned that conditions could be combined with && and ||. result = result + “Student name: ″. whether they are students or professors or any other employee of the college. But it hasn‘t shown how. return false. except that students whose permanent residence is outside Canada are given student numbers which begin with an eight or a nine.length() > 0) { result = result + “(″. Pause for a moment to create a method. result = “Student number: ″ + studentNumber. it appears. Let‘s remedy that deficiency right now. Now we have greater than.charAt(0). result = result + studentFullName if (studentPreferredName.public String toString() { String result. a single character. and != (not equal).charAt(0) == '9'. result = result + studentPreferredName + ″)″ . These include >= (greater than or equal). if (firstDigit == '8') return true. < (less than). or >.

you could compile Example. } public void testIsInternational2() { assertTrue(s2. } All the solutions are correct.isInternational()). then right click it and choose the constructor. To test this method. and one for numbers beginning with any other digit. you should create new project called Testing and a class within it called Example. public void testIsInternational1() { assertFalse(s1. public boolean isEven(int n) { return (n % 2) == 0. The second and third solutions use the || operator to test if the first character is an eight or is a nine.isInternational()). Add the following method to Example. while s2 should be. How many unit tests did you need to test this method? You should have used at least three: one for numbers beginning with a nine. since the examples have nothing to do with students. } You can see that s1 should not be an international student. n is even. If the remainder is zero.} Or does it look like this? public boolean isInternational() { char ch = studentNumber. one for numbers beginning with an eight. Which solution is best? That decision is up to you and your teacher. Or. Which did you choose? 67 . For the next examples. The method calculates that remainder and compares it to zero.charAt(0). you could create unit tests. An integer n is defined to be even when the remainder when you divide it by two is zero. Now write an isOdd method. Right-click it there and choose the isEven method. Here are two of my tests. return ch == '8' || ch == '9'. } The modulus operator (%) gives the remainder when you divide the first value (in this case n) by the second (in this case two). This places an Example object in the object tray.

a century but not divisible by // 400 so not a leap year result = false. There are a couple of different definitions for ―evenly even. You should be able to write isEvenlyEven quite quickly. // check the centuries if ((year % 100 == 0) && (year % 400 != 0)) // oops. There is a mathematical concept called ―evenly even‖. it will only be a leap year if it is also divisible by 400. return result. The simplified rule is that a year is a leap year if it is evenly divisible by four but if it is divisible by 100. That is. public boolean isLeapYear(int year) { boolean result. Create an isLeapYear method and then come back and look at mine. 2000. } public boolean isOdd3(int n) { return !isEven(n). } In this method you see that we can nest one if statement within another. This example uses the && operation. } The first two are modelled on isEven. and 2004 were all leap years. 2200. 68 . if (year % 4 == 0){ // divisible by four so might be a leap year result = true. Thus 1996.public boolean isOdd1(int n) { return (n % 2) == 1. But 2100. we evaluate a second condition only if a previous condition is true (in this example). and 2300 will not be leap years. ones which use && and ||. Note that we also use the != relational operator.‖ Let‘s use the one that says an integer is ―evenly even‖ if it is evenly divisible by four. Within a single if statement we can write compound conditions. } public boolean isOdd2(int n) { return (n % 2) != 0. Do it! Leap years in the western calendar are an interesting challenge. } else // not divisible by four so not a leap year result = false. but the third is based on the mathematical idea that an integer is either even or odd. there are no alternatives.

It has also introduced Boolean algebra. It has also shown you how to use the Java documentation to answer questions about classes which are part of the Java libraries. or.Summary This chapter has introduced one of the fundamental features of programming: using the data you are processing to control the flow through your program. 69 . the Boolean operations and. and various relational operators. and not.

Instead of separate PST and GST. being a student. This discount may be zero. A coin has two sides. Starting in July 2010. This is because random is a static method.org/wiki/Coin_flipping. How would you implement your class to allow for biased coins. flip. Assume that a Coin class implements the idea of heads and tails by using a random number between 0 and 1. typically called heads and tails. it is a class method. Until now we have used the name of an object. A simple object to model is a coin. 3. and Newfoundland and Labrador. (Check the documentation to see how.lang. if the number is less than 0. Of course the discount might also be based on being a neighbour or friend of the owner. ones which come up with either heads or tails more than expected? Recently I read that when you flip a coin it ends up the same face up as it starts with 51% of the time. For a fair coin.random. Anyone who purchases something may need to pay the provincial sales tax or PST.Math contains a random method which you could use. Each customer also has a discount rate. but we will ignore that detail for now. Some goods are exempt from taxes. Here we use the name of the class.wikipedia. That is. each province has its own provincial tax rate. 2. Prince Edward Island.) Create a method. Note that you will use Math. java. he/she will be granted a discount. purchases there are subject to an HST. that is. 70 . when the customer makes a purchase. Ontario and British Columbia adopted an HST as well. or it may be a positive percentage (or a positive amount) based on his/her previous purchases. otherwise consider it to be tails. New Brunswick. Each customer has a number and a name. not an instance method. How would you model such a discount scheme? In Canada. followed by the period and the method name. followed by a period and a method name. Stores have customers.5 consider the coin to be heads. This is mentioned at http://en. which may be zero.Exercises 1. There is also a federal Goods and Services Tax (GST) whose payment is required in all provinces except Nova Scotia. In those four provinces. there is the Harmonized Sales Tax. The names of these two methods are based on practice which says that methods which return a boolean value should have names beginning with the word is. isHeads and isTails will examine to decide if the coin is heads or tails. Such methods are also considered to be getters. which generates a random number which two other methods. or being an employee.

edu/~shipman/z/nom/6home. 71 . 6.Math to create a roll method. The second. you modelled a die. given the common name. To extract the first character from the postal code.edu/sora/NABB/v003n01/p0016-p0025. not public. The first. use the charAt method from the String class and provide the value zero as a parameter. In it. What modifications would you need to make to your class if the bank changed the rules to allow some number of free transactions before it began to charge for transactions? What modifications would you need to make to your bank account class if the bank changed the rules to allow free transactions as long as your balance stayed above a specified amount? 5. you designed a Bird class. you may wish to use the startsWith method from the String class. Create a method to determine the abbreviation. Note that common names change over time. write a method which has parameters amount and postalCode. and returns the tax (PST plus GST. Note that http://www. Use a separate method to determine the abbreviation. third. In an exercise in the previous chapter.unm. In many parts of the word. fourth. 7.Create a Purchase class. The larger provinces may use several postal codes. 4.ca/personal/tools/pg/manual/PGaddress-e. we mentioned modelling a bank account. See exercise 1 of this chapter for further information on the random method.lang. birders often use abbreviations for the bird name. In an exercise in the previous chapter.asp#1380608 contains a map showing all the provinces of Canada plus the first character of the postal code for that province. Use the random method in java.canadapost. so the setter for the common name will use this separate method to determine the abbreviation. Different people prefer different abbreviation systems. In the constructor. or HST) necessary for a purchase. but one person will always use the same system.nmt.pdf) or six (http://infohost. and fifth characters (counting from the left) must be letters. as we did when determining if a student number represents an international student. The Canadian postal code is a six-character string. Common systems use four characters (http://elibrary. Add the abbreviation as an instance variable of the Bird class. Alternatively. and sixth characters (counting from the left) must be digits. In an exercise in the previous chapter. Since the method to determine the abbreviation is called only by methods within the Bird class. We will explore the world of birding in subsequent chapters.html). the only parameters will be the common name and the scientific name. that method will be private.

charAt(loc)). described at http://en. Canadians have a national identification number called the Social Insurance Number or SIN. Not only does the first digit indicate the region of Canada in which the number was issued. you extract single-character substrings from the SIN using the substring method in the String class. Recall that Java numbers its characters starting at zero while English refers to that character as the first character. returning the appropriate boolean value.isDigit methods from the Character class.isLetter and Character. There are two possible approaches to solving this problem.valueOf and then use the modulus and division operators to extract individual digits. which accepts a String as a parameter and decides if it represents a valid SIN. and then use the Integer. 8. 72 . To check that the character in position loc of a string ess is a letter.isletter(ess. isValidSIN.wikipedia.wikipedia.Create a method. Assume that the input contains only digits. In the first. but the SIN can be validated through the use of the Luhn Algorithm. You will need to use the charAt method from the String class. and the Character. The SIN itself is described at http://en. you convert the nine-character string into an int using Integer. which accepts a String as a parameter and decides if it represents a valid postal code.valueOf method to convert the single-character substring to an int.org/wiki/Social_Insurance_Number. Either technique will work. The SIN is a nine-digit number but it‘s not just any nine-digit number. Create a method. isValidPostalCode. use Character. In the second approach. returning the appropriate boolean value.org/wiki/Luhn_algorithm.

entered as Strings. both are nine-digit numbers. So how can we use this information? We can create a new class. Student has a studentNumber. Commonality usually implies that there is a better way to deal with the classes than what you have first decided. Are they really different? No. common on the basis of function if not name. the students and the professors. the steps you should do before you start writing code) your ears will perk up at a statement that says ―classes are similar‖ and intuition will kick in whenever you see such commonality. Student has studentFirstName. for both. we divided the people in the classroom into two groups. Professor has a professorNumber. We noticed that the Professor and Student classes looked very similar.) This is shown in the following class diagram. (The name of a class is usually a singular noun. Since number is not a very descriptive variable name. you will be able to:  Define abstract class and inheritance  Use abstract classes to implement inheritance Abstract classes Before we go any further with the Student class. But we are all people! So why not create a People class? That class can contain all the common fields in Professor and Student. we should think back to a comment made earlier. Thus we used Person rather than the initial suggestion of People. right now there are none since the attribute names are different. called Person and derive the Professor and Student classes from it. for both.Chapter 4 – Inheritance Learning objectives By the end of this chapter. I will use identifier instead. In this case. 73 . After you gain more experience with object-oriented programming (and object-oriented analysis and design. What common fields are there? Well. Professor has professorFirstName. but think a little deeper. Professor and Student have several common fields. Are they different in structure? Not in this example. so I will use firstName instead.

Note the arrow from the Student class to the Person class. a word which appears in the class header and signals to Java that we won‘t be instantiating (creating instances of) the class. remembering to change the variable names.). This is read as ―a Student is a Person‖ or ―Student is derived from Person.‖ (That‘s the way I responded. there is an arrow from Professor to Person. One diagramming style. If we try to instantiate an abstract class we will get an error. Student and Professor are both derived from Person. we must declare the class as abstract. is that the two arrows share a common path whenever it is reasonable to do so. but the derived classes may have features which make them different. BlueJ does not do this. which I have used here.‖ Similarly. Both derived classes have features in common with the base class. You can copy the code from your Student or Professor class. Person is referred to as a base class for both Student and Professor. we don‘t wish this. Enter the appropriate instance variables and constructor. But wait a moment! Do we wish to be able to create instances of the Person class which are neither students nor professors? If you respond that ―No. This is a good way to learn the Replace function in BlueJ. We‘ll see this in a few moments. 74 . The Person class Create a new project and create within it a Person class.

} To calculate and save a string. The only difference is that one toString method places the word Student at the beginning of its result. the area of memory will contain a reference to a String. there are other types of people we wish to model besides students and professors.length() != 0) result = result + " (" + preferredName + ")". and when I need the contents of that area of memory. middle. Thus the methods are not identical. we should place methods as high up the inheritance tree (as close to the base class) as we can. Perhaps we wish to model alumni and the recipients of honorary degrees. return result. as a general design rule. result = "number: " + identifier + " First name: " + firstName + " Middle name: " + middleName + " Last name: " + lastName + " Full name: " + fullName. But you could also argue that the following solution works as well or better. In this case. I can see the arguments behind both answers but. The saving is done in the statement beginning result =. What about the toString method? Both Student and Professor contain that method. public String toString() { String result = new String(). and save the result. last. if (preferredName. for the model we are creating (and it‘s my model!). public abstract class Person Notice how the class diagram shows that Person is an abstract class. So I concatenate them. (A variable is a piece of memory with which I associate a datatype and name. and. Perhaps there are the administrative deans. Create a toString method in the Person class. so you could argue they should remain where they are. I need to concatenate the identifier and the first.) Whether or not there is a preferred name. I need a variable of type String. Its code is below. I‘ll use the name result. So I will declare Person as an abstract class.If you respond that ―Yes. Examine the two methods you created and you‘ll see that they are almost identical. The way to interpret this statement is to say ―Calculate the value to 75 .‖ then you do not wish to declare Person as an abstract class. the other places the word Professor. which I have named result. we won‘t have anyone other than a professor or a student. and full names. toString in an abstract class We have placed the common instance variables in the abstract class.

Since it is a String. super.the right of the equals sign.toString() asks the parent to represent itself as a String. we will include the following methods in the appropriate classes. But the resulting code looks strange to my eyes. and that could cause some strange code.length() == 0) // do nothing else result = result + ″ (″ + preferredName + ″)″. Tests for inequality or greater than are both acceptable and are preferable. and then. Thus == means equals. There are no executable statements between the if and the else. which we will do in a moment.toString(). public String toString() { return "Student " + super. to my eyes. we prepend a word to that String. Now I need to check whether there is a preferred name.‖ This is exactly what we have been doing in our constructors and previous toString methods. as appropriate. we test for inequality.toString(). if (preferredName. When we create the Student and Professor classes. there is nothing to be done. Note that we could have used the symbol > (or greater than) instead of != since the length cannot be negative. As we have seen earlier the exclamation point is used to indicate not. 76 . Note that we are overriding the toString method in the parent class by creating a toString method in the derived class. if (preferredName. Most people would wonder what is missing so we place a comment there to indicate we have not forgotten something. use result to remember where the value is stored. to testing for equality but having an empty section of code. } The reserved word super refers to the base or parent class. and != means not equal. } public String toString() { return "Professor " + super.length() > 0) result = result + ″ (″ + preferredName + ″)″. So we do not test for equality. When there is no preferred name.

simply by calling super as the first step in the Student constructor. But the constructor is not exposed! That is. String lastName. String firstName. Right-click the class and choose the constructor from the menu. lastName. middleName. fullName. That method. } Attempt to compile Student. String middleName. it can use the constructor of its base class. as we showed earlier. Create two new classes within this project. String fullName. and Professor.The Person class. It will not compile. Student. Person. String preferredName) { super(identifier. You can tell which classes need to be compiled since they appear striped in the diagram. Compile all the classes. Then double-click the Student class to open it in the code editor. protected instance variables (and methods) may be accessed directly within the class in which they are declared as well as in any derived classes. Student and Professor. Draw the arrow from Student to Person. Then create toString methods in Person. Without a method after the word super. That is because the class is abstract. Notice the statement that says public class Student extends Person. the effect is that the Student object essentially says ―I don‘t recognize that message.‖ 77 . Do you need to create a getFirstName method in the Student class? No. As noted above. That is. look at the class diagram. super is the word Java uses to refer to the parent class. it does not appear on the menu. They may not be accessed within derived classes. you are executing the constructor in the base class. Student(String identifier. and the other getters and setters should be in the Person class. firstName. I‘ll ask my parent to respond to it. indicating inheritance. You created this statement by drawing the inheritance arrow from Student to Person. if you have changed both Student and Person. Simply click the Compile button beside the class diagram and all will be compiled in the appropriate order. How do you create a Student object? A Student object needs a simplified constructor. preferredName). where s is an instance of Student. since the constructor in the derived class is trying to use private instance variables of the base class. will be compiled first. continued Compile the Person class and see what happens when you attempt to instantiate it. If we use the expression s. Change the visibility on the instance variables of Person to protected. for that matter) may be accessed directly only within the class in which they are declared.getFirstName(). private instance variables (and methods. Hint: If you are unsure which classes you have changed and thus should be compiled. Thus we cannot create a Person object. the parent class.

String middleName. preferredName). } /** * An international student is one whose identifier * begins with an eight or a nine * @return true if the student is an * international student */ public boolean isInternational() { char firstDigit = identifier. middleName. firstName.toString(). if (firstDigit == '9') return true. if (firstDigit == '8') return true. String firstName. The Student class – a derived class My implementation of the Student class is shown below. return false. fullName. } /** * @return a Student. String preferredName) { super(identifier. } } // end class Modify the unit tests for Student to take into account the different instance variable names we are using. String lastName. /** * A Student * * @author rick gee * @version september 2007 */ public class Student extends Person { Student(String identifier.charAt(0). as a String */ public String toString() { return "Student " + super. String fullName. lastName. 78 .Set up your Student unit tests to ensure that they still work.

The Professor class Now that we have the Student class created and tested. This simplification is the essence of abstraction and model making. This exploration begins in the following chapter. since we have tested them as part of the Student class. It is currently similar to the Student class. The only method we need to test is toString. we can create and test the Professor class. A model is a representation of something ―real‖. The unit tests here are simple. It is just a model and omits many aspects of real students. but does not need the isInternational method. we can explore them in more detail. our class and its instances do not represent actual. Note the phrase ―simplified classes‖ in the previous paragraph. students. an abstraction. 79 . Summary In this chapter we have had an introduction to inheritance. It represents a simplified student. we have seen how to create classes which inherit instance variables and methods from their parents. But it is just an introduction. Of course. identifying missing instance variables and behaviours. We have also gained more experience with unit testing. Like the Student class. Now that we have created well-designed Student and Professor classes. living. we are referring to the process of eliminating non-essential aspects of objects which model real things. When we speak of abstraction. We will see inheritance again in later chapters. albeit simplified classes. In particular. students in this case. it is a derived class. We know that the getters and setters work.

4. including the Blackbrowed and the Black-footed. There are also administrators. 2. I don‘t think a real bank would have account types called Nickel ‗n Dime. Warblers too come in many varieties.Exercises 1.edu/class/cs108/982handouts/14%20Inheritance%20Examples. One of its inheritance examples is the bicycle and the different types of bicycle. At Okanagan College there are not just students and professors. Objects of the SupportStaff class need to know the local to which they belong. Note that the biological classification into kingdoms. orders. and support staff. Song. High interest accounts allow only a few withdrawals in a month. and the Gambler. Sparrows come in many varieties. and there are many types of albatross. Extend your model of the bank account to accommodate some of these variations.html. and Kirtland‘s. including Herring. the people without whom the institution would not run. Sun provides a Java tutorial on its website. For historical reasons. An interesting collection of bank accounts are described at http://cse. Objects of the Administrator class need to know their salary. Model these in the simplest way possible. and California.stanford. etc. I discussed birding. but you may be able to understand much of it. and there are many types of Gulls. including Harris‘.com/docs/books/tutorial/java/concepts/inheritance. The programming in this example is in C++ rather than Java. A second section of the page referred to above contains an interesting perspective on the role of Instructors at a teaching institution. In a previous chapter. 80 . Birds and all other living things provide interesting examples of inheritance. Savings accounts don‘t allow cheques. who provide management and direction. including Yellow. is a fertile source of modelling exercises.sun. Part of its attraction is that there are so many types of bank accounts. and House.pdf. In a previous chapter. Implement Administrator and SupportStaff classes using inheritance from Person. A gull is a type of bird. families. Model the inheritance described. Swainson‘s. An albatross is a type of bird. http://java. 3. Mew. Support staff are unionized. I discussed the use of a bank account as a common class for modellers. there are three separate locals of the union on campus.

Use inheritance to model these three room types. 81 .How would you change the model to accommodate unicycles? Is a unicycle a bicycle? 5. chairs. use inheritance to model these different types of furniture. How would you model a graduate student? In a previous chapter. Assuming that the different types of furniture include tables. There are actually several types of rooms. and filing cabinets. In a previous chapter. 7. I discussed modelling Furniture at a college. 6. desks. people who have already completed one degree and are studying for a higher degree. I discussed modelling a Room at a college. A GraduateStudent is a Student. including lecture rooms and laboratories. Okanagan College is a four-year college so has no graduate students.

82 .

An Address class is the focus of this chapter. So what is an Address class? What makes up its state and its behaviour? 83 . a college also needs to know its own address. Email addresses are not so interesting. or they may be the same. A phone number is not so interesting. Stop! Do not pass go! What is wrong with the statement? We do not need to add an address to both classes. The interesting discussion is around a person‘s mailing address. It‘s just a String. Adding an address Let‘s now add an address to the Student and Professor classes. this time to the Human Resources Office.Chapter 5 – An Address class Learning objectives By the end of this chapter. Given the problems with violence on campuses. Professors also need to provide an address and contact information. (A transcript is an official record of the marks a student earns in the courses she takes. Let‘s begin there. many institutions also want email and/or cell phone (mobile phone) numbers they can use to contact students in case of emergencies. you will be able to:  Create more complicated classes  Explain when and why to use cloning  Use the online Java documentation to find out about classes. In addition.) The Library will use that address to send notices of library fines. We can add an address to the Person class and both Student and Professor will have access to it. They too are just Strings. including transcripts. It may have a mailing address and a separate street address. Introduction A college needs to know the address of students. so the Registrar‘s Office can send written communications.

the details of the constructor.  City.  Postal Code. you should also add an apartment (or unit) number to the address. To see where the ideas for these fields arose. but. are examples.The Address class What fields do we need to form an address? You could use one long String. This reminds me of the old question ―Why do we drive on a parkway and park on a driveway?‖ or ―If a train stops at a train station. named Address. and a toString method. it would be a very good idea to create a Name class. Road. you may wish to have two constructors. Perhaps you live in a suite in a house and have an A after your address. or Crescent. one with an apartment number.  Name. and one without. as we have seen earlier when we looked at names. What statements are those? In addition to the ones BlueJ creates for you. I would suggest the following fields:  Number. Some towns are divided into sections. In fact. Different countries use different formats for their codes. consider the Canada Post postal code lookup page at http://www. if you have some spare time.  Province (or state) or other subdivision of the country. Of course.  Type. giving addresses like 8743 12 St NE.asp We could add all these fields to the Person class. it may be more efficient to decompose the address into smaller fields and combine them to form larger combinations as needed.mailposte. Parkway. you also need the comments that are appropriate. but don‘t you think it would be better to create an Address class (especially since the college may need this class to hold its address) and then allow the Person class to contain an instance of the Address class? Yes. We will not deal with that here. For complete generality. If you do include the apartment number. 84 . what happens at a workstation?‖ Isn‘t the English language wonderful?  Direction. 1703A Yates Street is an example.  Country. you need private instance variables. My example will not do so.ca/tools/pcl/bin/advanced-e. you could make the same argument about a Name class. Return to the BlueJ drawing pane and create a new class.  Number suffix. Double-click Address and enter the Java statements that it requires. Street.

String name. etc. private String suffix.suffix = suffix.the number on the street * @param suffix . * @param city . String province. SE.name = name.type = type. * @param direction . this.two-character abbreviation * @param country – the country * @param postalCode . String country. // NW.a suffix to the number (1702A) * @param name . // 1702A. this. this. * excluding internationalised postal code * @author rick * @version 1 – april 2006 */ public class Address { // instance variables private String number. private String country.number = number. /** * Constructor for objects of class Address. town. private String province.postalCode = postalCode. String suffix. for example private String name.city = city. street.The Address class – the code My code is below. crescent. this. private String direction.direction = direction. * @param number .country = country. String postalCode) { this. this. private String postalCode.the city.the name of the street * @param type – road. or village * @param province .province = province. this. for example private String city. this. String city. String direction. private String type. */ public Address(String number. } 85 .for a city divided into NW.the postal code. this. /** * a class to contain a street address. String type.

result = result + province.convert the address into * something suitable for a mailing label. Isn‘t that a nice piece of documentation that appears? And you didn‘t have to do anything special to have it appear. result = result + " " + postalCode. If you prefer not to use the keyboard to see the documentation. } } If you think documentation is not worth writing. simply use the dropdown box at the top right corner and choose between Source Code and Documentation. Press J again to return to your source code. result = result + city.length() > 0) result = result + suffix. result = result + " " + name. result = result + " " + country. if (direction. press -J while viewing the Java code of the Address class. // end of line 2 result = result + '\n'. but there are some interesting things in toString. The constructor contains nothing new.length() > 0) result = result + " " + direction. Some people write fewer and longer statements. instead of result = result + ″ ″ + name. The Address class – the code – in detail Let‘s look at my code in some detail. First. 86 ./** * toString . * * @return . For example. // end of line 3 return result. each person develops a different programming style. I prefer to write many short statements while concatenating Strings. // end of line 1 result = result + '\n'. result = result + " " + type. Despite what you see in some of my examples.a String containing multiple lines */ public String toString() { String result = new String(). if (suffix. result = number. other than provide a few statements in your code.

and saving the resulting String in the variable named result. A line feed moved you down one line. compile it. and test it. a String may be overkill. Concatenating a char onto a String creates a new String. a blank. one which. is shorthand for x = x + y. A tab is a character.wikipedia. http://en. So ‗\n‘ is the representation of the carriage return and linefeed combination. the value of name. you could write result = result + ″ ″ + name + ″ ″ + type. each digit of a number is a character.) So Java contains a character datatype. Since the carriage return didn‘t move down a line. contains the command to display the rest of the String on a new line. a carriage return moved you from the current position on a line to the beginning of the line. x += y. When you display an address. There are other shorthand operations including -=. represented by \t.org/wiki/Typewriter Some operating systems treat a carriage return and a linefeed as two separate characters. but that detail is hidden from us when we are using Java. A String may contain zero or many characters. each punctuation mark is a character. 87 . The effect is the same. I have used a single-character String for the space between fields. And what is this ‗\n‘ that appears in two places in toString? A String is delimited by double quotation marks. *=. My toString method produces a three-line address that is suitable for printing on a mailing label. not ―1702AFifthStreet‖. concatenating the current value of result. called char. This allowed you to produce some interesting effects. and /=. See the Wikipedia article on ASCII art for some examples. you could type over what you had typed. Why the blanks? So the output is ―1702A Fifth Street‖.org/wiki/ASCII_art You may even wish to see the article on typewriters if you don‘t know about them. and a carriage return and linefeed combination is a character. In the days of the typewriter. and the value of type. http://en. Adopt what you like from my toString method. a blank. (Yes. Some people are even more terse.wikipedia. If you want a single character.result = result + ″ ″ + type. Each letter of the alphabet is a character. BlueJ shows the \n character instead of moving to a new line. They will write result += ″ ″ + name + ″ ″ + type. in this case. represented by \n. Single characters are enclosed in single quotation marks.

one pair at a time. out output appears in the top of the Terminal Window. and run unit tests as you do so. and displays its output on the requested device. declare an instance variable. Person uses Address Now that the tests are complete and all pass muster so we know that Address objects work properly. Accept the suggested name of address1. I will sometimes display the result in the Terminal Window rather than using an assert statement. how do we add an instance of Address to Person? It‘s simple. in this case. In that window. Add. the output would have appeared in the upper portion of the window. protected Address addr. err output appears in the bottom. choose View. println is a method which calls the toString method of the object it is given. and press . Compile the class. the cursor moves to the following line. and. Then. compile. editor windows open on your screen at once. Did you notice how a ―uses‖ arrow appeared on the class diagram when you insert that statement. After displaying the output. A small window appears at the bottom of the BlueJ window. Hint: you can have many. in this case two. type System. The Address class – getters and setters Add the first of the getters and setters. I don‘t care which ones they are. and save the file? 88 . address1. but appearance may be part of its correctness. Compile the class after you make each pair. from the dropdown menu. The output to the screen is through either the err device or the out device. When I am testing a method which produces a long String as output. Now create the unit test for the getter and setter. showing the output of the println command.println(address1). I have to look at the output to decide whether it is correct. System is a class which allows your program to communicate with the keyboard and the screen. Ensure you compile and run the tests after you create them Now create the other getters and setters. If we had used System.err. Use one to create the class and the other to create the unit tests for the class. with different parts on different lines in the lower portion of the window.out.To see the output as it is meant to be seen. Recall that using the word protected means that derived classes may access this variable. from the main menu.println. create an Address object on the workbench. ready to display more output. choose Show Code Pad. A Terminal Window opens.

It is a special kind of Object since most can be changed. it cannot be changed by adding or deleting a single character. this. rather than waiting until you have fixed the problem. Be aware that your program will contain an error which should be fixed. In particular. If you are going to do that exercise. Making copies (cloning) Note: This section (and others later) deals with an advanced topic. perhaps when you are more comfortable with Java. the method does not receive a copy of the Object. it is possible to use methods of the Object to change its contents.addr = addr. so may need another address. It is included here because this is the correct place to talk about it. one of whom later moves. Does everyone have an address? They should have an address. But there is a subtle problem here. a home address.A ―uses‖ arrow is an indication that objects of one class (the one at the blunt end of the arrow) contain objects of another class (the one at the sharp end of the arrow. so we add the address as a parameter to the Student and Person constructors. and a String is a special type of Object. called immutable. But students often do not live at home. Consider roommates. Exercise 1 provides directions to see how this can happen. That means it cannot be changed without totally rewriting it. When you have a reference to an Object. But you may skip it should you wish. do it now. a Person will contain only one Address object. it receives a reference to the Object (essentially an address in memory). At the moment. The parts of a person‘s name are Strings. We are saying that a Person object contains one or more Address objects. @param addr the address Then we save the value provided to the instance variable. any change to the Address object will affect both Student objects. The implication of this is that we do not need to clone the parts of a name. when two Student objects refer to the same Address object. since they both contain references to the same Address object. We are not saying that an Address is a Person. When an Object (and every parameter we have seen so far is an Object or is derived from an Object. 89 . At least that is what you may have guessed from everything we have seen so far.) This is quite different from the ―extends‖ arrow. including documentation. but we do need to clone an address.) is passed to a method.

println(s1 == s2). The idea behind the computer technique called hashing is similar.err. Thus s1 and s3 refer to different areas of memory.println(s1. Several Person objects now have a reference to the same Address object. we do not change the contents of the area of memory associated with it. String s2 = “and here is another string”. producing a single number. and the tests I describe. we allocate another area of memory.equals(s2)). and System. That number is an indication of the contents of the Object. Two Objects with identical values should give the same hash code. After this statement. changing his/her address. nor are they equal when you use the logical operator == (which compares hashcodes. You can enter them. The food called hash is a mix of a variety of different ingredients.Consider the following statements. containing the different contents. Making a copy of an Object is called cloning the object. You can see this by using System. When we change its contents. often implemented as addresses of memory) since their contents are in different areas of memory. it can be changed quite simply. even though they have not moved! 90 . If one of the roommates moves away. Some people say it looks like pet food. But s1 is immutable. Exercise 1 in this chapter asks you to explore the following scenario. Before executing this statement. and the same Address object is used to represent that address for each of the roommates. String s1 = “here is a string”. we should make a copy of it when we store it as part of a Person. Thus. s1 and s3 will compare as equal using the equals method (since their contents are identical) and when using the logical operator == (since they both refer to the same area in memory. Take the value of the Object and mix it up some way. The two Strings are not equal when you compare them using the equals method (which compares contents of strings) since their contents are different. An Address is not an immutable Object.) Now consider the statement s1 = “this is a different string”. s1 refers to an area of memory which contains ―here is a string‖. Now consider the statement String s3 = s1. Suppose a group of students share an apartment. s1 and s3 will compare as not equal when using the equals methods (since their contents are different) and when using the logical operator ==. in the CodePad window. that address change will be reflected for all the other roommates as well.err.

Assume the getAddress method returns an Address. suffix. If any instance variable did not know how to clone itself. In that case. direction. public final Object clone() { return new Address(number. Create the unit test for the Address instance variable in the Student and Professor classes. we must resort to a little deception. postalCode). } catch (CloneNotSupportedException e) { return null. This is a security issue.To clone an Address object. it cannot create a clone method. the method would not work. city.addr = (Address) addr. the following method also clones an Address object. Now that we have the code to clone an Address. but you must promise not to ask how it works. I‘ll show you the code you need. The word final in the method definition simply says that should any class use Address as a base class. // can not happen } } This method works since all the instance variables are Strings and know how to clone themselves.clone(). 91 . we would implement a clone method for the class to which those instance variables belong.clone().com/javapro/2004_04/online/rule5_04_07_04/ If you are uncomfortable about using code which you do not understand. at least not for a while.ftponline. /** * @return a copy of the Address */ public final Object clone() { try { return super. of course. type. name. this. province. } // end clone() The Address class – unit testing Create the getter and setter methods for Address. Open the Address class in the editor and modify the class declaration to read public class Address implements Cloneable Then create a new method in the class. country. See more details at http://www. we can use the correct statement in the Person constructor.

Most of the values you provide are Strings. Thus the solution is to use assertTrue(a.I had some difficulty with assertEquals when checking the equality of objects. o Create a Person object by right-clicking the Person class and choosing the constructor. but you can change the name if should you wish.). One solution. place the line result = result + “ Address: “ + addr. does not. but the last is the name of the Address object you created earlier. You have to check that the corresponding parts are equal. and provide values of its instance variables. o Create an Address object by right-clicking the Address class and choosing the constructor.toString(). When we allow null addresses.toString())).equals(b. 92 . like the address. the name of a variable.toString(). o Note the name of the object which is being created (probably the name is address1. thus creating a complicated test. we should modify the toString method of the Person class to display the address. is to place many assert statements in one test. Once the Student objects have been created. to use in this case. Strings need to be surrounded in quotation marks but the address. Recompile everything. check their addresses. What happens when someone does not have an address or does not wish to provide it? What do we provide to the constructor in that case? Java contains a reserved word. How do we create an Address object to pass into the Person constructor? One way is to use the Object Workbench. The simplest way to do this is to use the toString method in the Address class. which I do not like. Before the last line in Person‘s toString. In particular. where a is the variable containing the expected value and b is the variable containing the actual value. A second way is to modify the unit test for the toString method in Person. The test passes if all pass. But I prefer to have one assert statement per test. Testing Address cloning Before we create the Address and Student objects. what happens when there is no address available? The reserved word null We have assumed that everyone has an address which they are willing to provide. null. we need to be sure that we neither clone a null object nor should we attempt to convert a null object to a String.

A second constructor is one which provides both addresses. if (addr != null) result = result + '\n' + addr. One is its street address. The other is its mailing address. providing the actual location of the college. one with an address. fix it.Thus we must make two changes to our code. You‘ll need separate tests for addresses which are missing and for addresses which are provided. We will not add parameters to the constructor.addr = (Address) addr. recompile your classes and test your work by creating two Student objects. and one with a null address. You need to decide which is the most likely to be provided. A third constructor is one which provides only one address. 93 . This applies in both the constructor and the setAddress method. if (addr != null) this. we must check it is not null. (Just provide the word null instead of name of the Address object. The constructor will simply set both addresses to null. Instead of simply calling the toString method of the instance variable addr. Yes. We will see this later when we explore ways to save the contents of objects.clone(). else this. four unit tests in all. a college may have two addresses. After making the changes to allow for null address. Create unit tests for both addresses. Modify the College class so that it has instance variables for both the street address and the mailing address. we need to check whether addr is null.addr = null. I would suggest that the street address may be the one you wish to use.toString(). a class may have several (more than one) constructors. which may or may not be the same as its street address. The College class and addresses As noted earlier. Before cloning the address. We will use the setStreetAdress and setMailingAddress methods to set the appropriate values.) Does your toString method work properly? If not.

Summary While an address appeared simple. 94 . and then we‘ll start to look at their differences. There is no difference in the structure of the two types of object. And there are complexities we have omitted! Note that everything we have said about a Student object so far applies to a Professor object. Let‘s look at one more structure they have in common. it turned out to be quite complex. There certainly is a difference in the roles they play at the College.

Suppose you are dealing with a culture in which not every home has an address. Design and implement such a class. you‘ll need to add a country instance variable to the Address class. Student. Use the setNumber method of the Address object to change its number. or a description. The effect is that whenever one student moves and updates the address. It may just have a name. Is s1 equal to s3 or not? 3. First. s1 = “here is a string”. Create an Address object on the Object Bench. Identify some of the different ways in which postal codes differ from country to country and write code to verify that the code entered matches the country. Create a unit test that verifies that Strings do not need cloning. That is. Internationalization is becoming more and more important. 4. What happens when you do the tests? Then do another test. both of which contain references to the same Address object. Then use the getAddress methods for both Student objects to see that both now contain the new number. 5. a program is not necessarily used in the country it is written. How would you modify the Address class to support this? Make it so. Use the CodePad window to verify that Strings do not need cloning by repeating the tests described in this chapter. Use the getAddress methods in each Student object to see that the addresses are both the same. of course. Since we created a class for Address. Create two Student objects on the Object Bench. Add another statement. 6. Internationalization is becoming more and more important. perhaps we should do the same for Name. Confirm the need for cloning by the following procedure. and Professor classes we have developed all use instance variables to represent the different parts of a name. the other student will appear to have moved as well.Exercises 1. 2. 95 . The Person.

United Kingdom. or some other countries which are different from your own. 96 . USA. explore the postal codes for Canada.Then.

All of these involve the use of dates and. you will be able to:  Create more complicated classes  Work with dates  Use the online Java documentation to find out about classes. What facilities does Java offer to deal with dates? 97 . At Okanagan College. times. Perhaps professors who have been there the longest have first choice on middle-of-the-day teaching times. You will explore that idea in the exercises at the end of the chapter. you need information about the age of a person. Mandatory retirement was in place when this chapter was first written.Chapter 6 – Dates Learning objectives By the end of this chapter. Thus professors need to know the date on which they were hired. It would be better to store the birthday and calculate the age whenever it is required. To do that you need to be able to store a date. But the example is a good one. Since that time. This chapter will explore dates. a professor is required to retire on the June 30 following his/her 65th birthday. because it changes every day. perhaps. so I‘ll continue to use it. In some other situation. it has been abolished. How old is a person? In many cases. for example. But you don‘t want to store the age. We will explore this in a later chapter. Introduction Many things at a college are based on seniority. Sections of a course have specific times for meeting. Perhaps students who applied first will be allowed to register for classes first. Perhaps students who have been registered the longest are allowed to register first for a new semester. an employee may not be required to pay a certain type of tax or make contributions towards a pension if he/she is too young or too old.

in the package java. is hour 0. appears much more useful to us.  A date (day of month) is represented by an integer from 1 to 31 in the usual manner. One. or are they more complicated than we need? Details about calendars Calendar is an abstract class (in the same way we have developed Person as an abstract class).Date appears to be used with databases. although most of its methods (again including the constructor with year. 0 is January.util. so it is best not to use them. and so forth. used to derive other classes.1900.m. the hour from midnight to 1 a. thus 11 is December. 98 .Date. The documentation describing GregorianCalendar provides an interesting. Rather than doing that derivation ourselves.sql.  An hour is represented by an integer from 0 to 23.m. (Package is a Java term referring to a collection of classes. but brief.) Many of this Date‘s methods (including the constructor which accepts year. you will find two Date classes. the term package is all files in your folder. The other Date class.  A month is represented by an integer from 0 to 11. In this case. in the package named java. Did you ever wonder why some countries and religions celebrate Christmas on December 25 and others celebrate it on January 6? It‘s a result of the change to the calendars and the reluctance of some people to switch. review of the way dates have been changed in the past. Reading the documentation closely. though. That means that they have been superseded by better methods in other classes. Have you noticed that BlueJ displays the hint ―Compile all uncompiled classes in this package‖ when you hover your mouse over the Compile button beside the class diagram? In this case. moving from a Julian calendar to a Gregorian one (for some countries) in 1582 or some other year.Dates When you look in the Java documentation. and the hour from noon to 1 p. we find that this Date class is derived from the other Date class. we should explore GregorianCalendar. month. Would one of these be what we need. Thus. Thus the Date class is within the sql package. There are suggestions to use the Calendar or GregorianCalendar classes. is hour 12. The conventions in GregorianCalendar regarding values used for instance variables are as follows  A year y is represented by the integer y . future releases of Java may not include deprecated classes or methods. and day arguments) have been deprecated. There is a hierarchical structure to these packages. month. 1 is February. guidance is given on what to use in its place. day) are deprecated.

99 . we‘ll create our own class. and needs a constructor and a toString method. it is extremely unlikely that two leap seconds will occur in the same minute.‖ That makes it easier to decide when 10 days in the future is. and day instance variables? The documentation quoted above gives limits on the values. The MyDate class needs instance variables for year. November. tenth. MyDate. We can always create a birthDate instance variable of type MyDate but it would not be sensible to create a graduationDate instance variable of type BirthDate. Instead. the names of some of the months represent older calendars. but it is an interesting inconsistency that the month variable starts at 1 while everything else starts at 0. and December begin with the Latin words for seven. we will use none of the provided classes. but this specification follows the date and time conventions for ISO (International Standards Organization) C. I (and others) have to wonder why the day of the month starts at 1 but all other fields (including month) start at 0. How do we use all this information on dates and calendars? Can we use this information? The MyDate class – a simplification For now.  A minute is represented by an integer from 0 to 59 in the usual manner. What data type should we use for the year. we may be able to use other types of dates. September. if you cross from one month to another. and ten. arguments given to methods for these purposes need not fall within the indicated ranges. and these values are small integers. and twelfth months of the current calendar. and the date an employee was promoted. for example. month. a date may be specified as January 32 and is interpreted as meaning February 1. Why not just create a BirthDate class. the values 60 and 61 occur only for leap seconds and even then only in Java implementations that actually track leap seconds correctly. month. and day. I know January is the first month. eight. the date an employee was hired. Because of the manner in which leap seconds are currently introduced. despite being the ninth. October. ―In all cases. Why might this be? Who had a year that was 10 months long? The documentation on the first Date class also includes an interesting note. In English. eleventh. they are more powerful than we need and introduce complexity we do not need. since that is what introduced this section? Thinking ahead. including the date a student graduated. Yes. A second is represented by an integer from 0 to 61. Having a more generic type of date appears to offer more opportunities for reuse. nine.

 There are several instance variables. you should use an uppercase L instead of a lowercase l. Representing numbers. it can represent four values. If you wish to provide a long value as a literal or constant. we‘ll use a number between 1 and 12. as long as your number is no larger than 263-1 and no smaller than -263. you must follow it with the letter l. 10. and a long contains 64 bits (representing integers from -263 to 263 – 1). But why do the names of these integer types not begin with a capital letter? The names of all the other classes we have seen have begun with a capital letter. and numbers not used in calculations) are stored as eight bits (allowing 256 values). a bit is the smallest unit of memory. They differ in the number of digits they can hold but programmers often choose long. 01. Primitive types Java supports many types of integers . Thus you might see a statement like this. 00.  There is a setter for each instance variable which it makes sense to be able to change. long numberOfDays = 1000L. and 11. depending on how you look at it. the longest of the four. a short contains 16 bits (representing integers from -32768 to 32767). int. one or zero. Recall that we talked about bits earlier. Everything is stored as a collection of bits.  There is a constructor (and maybe more than one constructor. In many languages. We‘ll store the day of the month as a number between 1 and the maximum number of days in the month. In a computer. also known as a byte. characters (letters. a byte contains 8 bits (representing integers from -128 to 127). 100 . short. punctuation marks. A bit has only two values.Programming style – a skeleton for a class The MyDate class is like all other classes we have seen and like the vast majority of classes we will see. we‘ll store the actual year. Instead of storing the year as the actual year – 1900. or on and off. an int contains 32 bits (representing integers from -2147483648 to 2147483647). and long.  There are unit tests. When the collection contains two bits. Instead of storing the month as a number between 0 and 11.)  There is a getter for each instance variable. Due to possible confusion between 1 (one) and l (ell).  There is a toString method.byte. It wastes a little memory but you won‘t lose any digits. Java stores its characters using the Unicode standard of 16 bits (allowing for 65536 values).

For those which are objects. including the toString method. There are some primitive types in Java which are not objects. /** * A date on the Gregorian calendar. like toString. Digression When you create a variable of a primitive type. The phrase ―encapsulates a long‖ means that a Long contains. We discussed some of this. If you go to that address. BlueJ shows this when you inspect an object. For primitive instance variables. you find the address of another location in memory. as its instance variable. Right-click an object and you will see a list of all the instance variables. * * @author rick gee * @version 1 . /** * Constructor for objects of class MyDate * @param year 101 . The MyDate class – the code Take a shot at creating your own MyDate class before looking at mine. you associate a location in memory with the name of the variable. and we have just found the names of four more of them. When you inspect that location in memory. but not in such detail. there is also a wrapper class called Long which encapsulates a long. As a class. You will sometimes run across the word ―wrapper‖ describing a class. though. and gives it some of the methods of other classes. But when you create an object and inspect the associated memory location. you will find the object.april 2006 */ public class MyDate { // instance variables private long year. Of course. below. private long day. this means we have a class encapsulating some value.The answer is simple. Name. Create your unit tests as well. a long. and String objects. there is another Inspect button which is enabled. Long supports additional useful methods. including its instance variables. in a previous section in connection with cloning Address. private long month. you will find the value of the variable. this second Inspect button is disabled.

I have used the constructor of the Long class to convert a primitive type to an object. group the bits into groups of four (starting from the right). a lowercase a is 0061. When interpreted as a number.unicode.year = year.org/charts/PDF/U0000. this. thus allowing me to use the toString method to display it. Thus when you add a slash to a year you get (It is 2010 as I write this) 2010 + ‗/‘ is 2057.day = day. this. 102 .toString().toString() + '/'+ (new Long(day)). } /** * convert a MyDate to a String * * @return the date as a String */ public String toString() { return (new Long(year)). Java interprets the character as a number. Thus. in hexadecimal (or base 16). and translate each group of four into one of the hexadecimal digits from 0 (0000) to 9 (1001) and A (1010) to F (1111).* @param month * @param day */ public MyDate(long year. Try it. } } You can‘t send a toString message to an instance of a primitive type. To interpret the table. You can see this at http://www. What would happen if I used return year + „/‟ + month + „/‟ + day. (An uppercase A is 0041. The bit pattern for a slash is 0000000000101111. and explain what happens. In an expression which involves a character being added to a number. How you interpret those bits depends on the datatype you have specified. 002F. Hint: Characters are stored as bits. you can only send such a message to an Object..pdf. and so are numbers. That is.month = month.toString() + '/' + (new Long(month)).) To convert from binary to hexadecimal. When interpreted as a character it is a slash. giving 0000 0000 0010 1111. long month. the pattern 0000000000101111 is 47. find the symbol you wish and create its hexadecimal value by using the three-digit column heading followed by the digit at the left. long day) { // initialise instance variables this.

6. day. 2. 6. 4. A. year). They would all have the same name and the same parameters. 1. 1. 4. These two methods cannot be named toString since there would be no way to distinguish between the three methods. If 123 is a hexadecimal value. 10. 5. hexadecimal. a bad thing which would prevent your program from compiling. 7. we find it is equal to 1 * 162 + 2 * 161 + 3 * 160 or 256 + 32 + 3 or 291. etc. 6. B. 5.) Such numbers are the one you use all the time – 0. Thus the octal number 10. 123 is a valid. When you use its constructor. month. 103 . 3. The MyDate class – unit tests Use your unit tests to see that MyDate creates and displays dates correctly. But what about 08? It begins with 0 but not 0X so it must be an octal number. 2.) They begin 0. Similarly you get an error if you enter September as 09. year) and one to return the date in the British format (day. D. C. 11. What happens when you specify August as month 08 instead of just 8 (or September as 09). 9. Larger octal numbers are preceded by 0. 8. 10. 1. and day if you wish. 4. Note that I have used the international ordering (year. you will use Integer in place of Long in toString. Java also allows you to specify integers as octal numbers (base 8. representing the decimal value 8. Its value is different from the decimal number 123 and the hexadecimal number 0X123. 6. Larger hexadecimal numbers are preceded by 0X. 5.You may wish to modify the separator. 3. The decimal. we find it is equal to 1 * 82 + 2 * 81 + 3 * 80 or 64 + 16 + 3 or 83. and day) in this method. number in decimal and hexadecimal. so you do not need to enclose them in quotation marks as you did for Strings. representing the decimal value 10. 2. enter it as 0X123. Note that you could use the int datatype for year. 0123 is acceptable as an octal number. etc. E. but different. 8. 3. 7. The numbers 0 through 9 are the same in the decimal system and in the hexadecimal system. You may wish to create two extra methods. 3. Thus the hexadecimal number A. their signatures (the name and the type and number of parameters) would be identical. etc. you are specifying integers. in the constructor? Java allows you to specify integers as decimal numbers (base 10. month. month. When we translate 0X123 to a decimal number. 9.. 10. is written as 0XA. and octal numbers 0 through 7 are identical. I chose to use a slash (/) but you may prefer to use a hyphen (-). one to return the date in the American format (month. 1. 10. F. 2. too. 7. Hexadecimal numbers begin 0. When we translate 0123 as an octal number to a decimal number. So 08 is not an octal number and you receive an error when you attempt to use it. 4. 5. Java also allows you to specify integers as hexadecimal numbers (base 16) of which we just saw a few. is written as 010. 7. But octal numbers go 0. In that case.

do you want the first nine months of the year to appear as single digits (as happens with the code above) or as two digits? Do you want the first nine days of the month to appear as single digits or as two digits? If the answer is ―two digits‖.toString(). so changing dates there could be a problem. But you can create unit tests for Professor and Student. if (day < 10) result = result + ″/0″. Student. Create a getBirthDate method in the Person class. result = (new Long(year)). What the reminder meant to say is that you cannot directly call the constructor of the Person class. you can‘t create a unit test for it. This is because we need to keep dates with no possibility of changing them accidentally. you create a Person object. While you should understand that statement. and add it to the constructors for Person. In a different application. return result.Since the Person class is abstract. else result = result + ″/″. Using MyDate objects Create a birthDate instance variable in the Person class. it is wrong.toString(). and Professor. How? Since the Person class is abstract. Because a Student object is Person object as well. if (month < 10) result = result + ″/0″. as we did for the Address class. Can you imagine an example where such changes would be very bad? Seniority matters.In the toString method. result = result + (new Long(day)). modify toString as shown below. and test it. 104 . checking that they process birthdates properly. result = result + (new Long(month)).toString(). A reminder . } Make the MyDate class cloneable. you can‘t create a Person object and then test its methods. public String toString() { String result. else result = result + ″/″. keeping track of when parcels arrived could be important. whenever you create a Student object.

/** @return birthDate as a MyDate */ public MyDate getBirthDate() { return birthDate. How do you test that birth dates and hired date are handled correctly? On the Object Workbench.In BlueJ. rather than these ad hoc tests. and then choose getBirthDate. 105 . Then right-click the Student object. Execute its toString method or its unit tests. but now we see that derived classes may also have their own instance variables. My diagram now has ―uses‖ arrows from the Person. but different behaviours. one for birth date and one for date hired. using the birth date object you just created. My getBirthDate method is shown below. perhaps with the same names in the different classes. choose Inherited from Person. Both these classes are derived from Person. But Student and Professor do not directly use the Address class. This is an instance variable which Student does not have. } Now modify Professor to contain a dateHired. so I deleted those ―uses‖ arrows as well. and Professor classes to MyDate. you can create an Address object and then a Student object. and thus contain all the Person instance variables. Create a Student object. The Student class does not directly use the MyDate class. Create a Professor object. Does toString display the birthdates properly? Remember that it‘s better to have unit tests. We will need to insert additional code at a later time to prevent this from happening. Student. Create a second Student object. BlueJ may be creating a very complicated class diagram. My diagram has ―uses‖ arrows from the Person. and Professor classes to the Address class. We will also see that derived classes may also have their own methods. specifying null for the birth date. While the constructor will accept a null date. It is creating superfluous ―uses‖ arrows whenever one class includes instance variables of another class. so I deleted that ―uses‖ arrow. getPhoneNumber may return the home number for a student but an office number for a professor. Student. and thus it must be an instance variable in the Professor class. create two MyDate objects. Unit testing is easier. This is the first time we have had different instance variables in Student and Professor. it makes no sense to have a null date here. Simplifying the class diagram By the way. As an example.

since we can calculate the retirement date once we are given the birth date. the professor retires on June 30 of the following year. Whenever we set the birth date. Here is my current diagram (omitting the unit tests for simplicity). private void setRetirementDate(MyDate birthDate) { long retirementMonth = 6.You may find that you can make the class diagram more readable by moving the classes around with your mouse. the professor retires on June 30 of the year in which he/she turns 65. we calculate the retirement date. we can create the following private method. 106 . that is the only way the retirement date is calculated – it cannot be set through a public setter. Thus. and a getter method. You have created all your unit tests. so I can‘t run them until I recompile them. We don‘t have a setter method. When the month of birth is June or earlier. I‘ve made some changes to them. Retirement of a professor Recall that I mentioned earlier that a professor at Okanagan College is expected to retire on the June 30 following his/her 65th birthday. Let‘s create an instance variable for the retirement date. haven‘t you? The diagonal shading indicates that I need to compile all my classes. When the month of birth is July through December.

setBirthDate(birthDate). public void setBirthDate(MyDate birthDate) { super. Student objects don‘t have a retirement date. Professor objects do. the setBirthDate method in Professor overrides the setBirthDate method in Person. We do not want to cut and paste statements from that method into this one. My tests are below.setBirthDate (the setBirthDate method in the parent class) ensures we do everything the Person setBirthDate method does. if we did that.  We use the getters from the MyDate class to extract the year and month of the employee‘s birthdate. But setBirthDate is inherited from the Person class. we do the additional processing which the setBirthDate method in the derived class specifies. Retirement of a professor .long retirementDay = 30. whenever we changed the Person setBirthDate we would need to remember to do the same for the Professor setBirthDate. } Notice some things about this method:  It is private so that only another method within the Professor class may call it.getMonth() >= 7) retirementYear++. dateRetirement = new MyDate (retirementYear. Technically. Once the processing in the setBirthDate method in the parent class is completed.‖  We use the constructor for MyDate to create the retirement date. The first is for a person whose birthday is in the first half of the year and the second is for a person with a birthday in the second half of the year. ++ is shorthand for ―increase by 1. and will also calculate the retirement date. So too will the setBirthDate method.getYear() + 65. But which method calls this one? The constructor for Professor will certainly need to call it. } The call to super. setRetirementDate(birthDate). retirementDay). if (birthDate. 107 .unit tests Create two unit tests for getRetirementDate. The best way to handle this quandary is to create another setBirthDate method in the Professor class. retirementMonth. It will do everything the Person setBirthDate method does. long retirementYear = birthDate.  We use the ++ operation to increase the year when the birthday is in the second half of the year.

retirementDay). What is the retirement date for a person whose birthday is exactly June 30? From carefully reading the contract. Here. The details of the retirement date are in a contract between faculty members and the college. retirementMonth. if ((birthDate. assertTrue(″2016/06/30″. 11. these last two conditions are combined using the && operator and then the result is enclosed in parentheses. } Many people will argue that unit tests for single-line setters and getters are a waste of time. the tests succeed.toString())). and one of the parts consists of two parts (joined by the symbol for and. retirementDate = new MyDate(retirementYear. Every if statement begins with if (some condition). 10)).setBirthDate(new MyDate(1950. June 30 of the following year.) To ensure there is no ambiguity. but there is a subtle error here.Note that unit tests are very important here. ||).getYear() + 65. Modify setRetirementDate and create a third unit tests to ensure this occurs correctly. we need to be able to confirm that the calculations are being done correctly. public void setRetirementDate(MyDate birthDate) { long retirementMonth = 6. Oh. long retirementDay = 30. &&. 108 . the condition consists of two parts (joined by the symbol for or. Here is my setRetirementDate method.getDay() == 30))) retirementYear ++. equals(p.getMonth() == 6) && (birthDate. we need to test if the month is June (a condition enclosed in parentheses) and if the day is 30 (also enclosed in parentheses. is true. equals(p. 05. We finish by using the || operator to decide if either of the two conditions.getRetirementDate(). assertTrue(″2014/06/30″. public void testGetRetirementDate1() { p. the month is greater than or equal to seven or the birthday is June 30.) Either the month is greater than or equal to seven (a condition enclosed in parentheses) or the birthday is June 30. 10)).toString())).setBirthDate(new MyDate(1949. long retirementYear = birthDate. } Note the parentheses. } public void testGetRetirementDate2() { p.getMonth() >= 7) || ((birthDate. But this test is definitely not a waste of time since we need to be 100% sure that the retirement date is correctly calculated.getRetirementDate(). the answer appears to be. To test if the birthday is June 30.

) == or =. It‘s on the Tools menu. but everything it flags detract from the readability of your code. the mistakes may cause it not to work. What are some of the common errors you have made? What are some of the common error message you have seen and what causes them to appear?    Spelling misteaks. Bernstein from Software Engineering Notes. && is done before ||. I find it helps to type the opening brace.     If you have installed the Checkstyle extension which I mentioned in an earlier chapter. so don‘t forget it. and then go back and fill in what should be between the parentheses. Class names are capitalised. BlueJ helps by indicating the matching opening brace when you type the closing brace. Missing braces is a more common problem than missing parentheses. Programming style – common errors A quotation which I believe is ―It is okay to make mistakes. Capitalisation mistakes. Mismatched parentheses. For every opening parenthesis there must be a corresponding closing parenthesis BlueJ helps by indicating the matching opening parenthesis when you type the closing parenthesis.‖ This is by L. now might be a good time to use it and check the code you have generated so far. It is good to admit them. If the program compiles.Logical operators have a priority. In my programming style commas appear only when you are defining or using a method (or when you want them to appear in the output of a toString method. Common problems it finds are missing javadoc statements. The double equals is also used when you are checking whether two objects both refer to the same area of memory. then the closing parenthesis. problems with parentheses and braces. and then go back and fill in what should be between the braces. A double equals sign is used when you are checking that two variables (usually primitive data types) have the same value. July 1993. In particular. Every word in a class name is capitalised. They don‘t hurt. Missing or superfluous commas. due to confusion between variable names. Commas are only used to separate items in a list. Spelling mistakes in variable names may cause your program not to compile. Missing or superfluous semi-colons. they just mark you as inexperienced or careless. For every opening brace there must be a corresponding closing brace. A single equals sign is used when you are assigning a value to a variable. I find it helps to type the opening parenthesis. then the closing brace. A semi-colon marks the end of a statement. The first word in an object name begins with a lowercase letter but other words (if any) are capitalised. and don‘t add unnecessary semi-colons. sometimes seems picky. The default style. Thus many of the parentheses in the method above are superfluous. 109 . problems with indentation. and is still true today. It is best to learn from them. Spelling mistakes in comments are annoying. Mismatched braces. It is bad to repeat them. one with which I agree. But I have put them there to clarify how the tests are being done.

Doing this well will be crucial to your success as a programmer. accessing variables and methods in the parent class. and adding variables and methods to the derived class. But we have reached a plateau in what we can do with single-valued variables. the topic of the next chapters. overriding methods as required. We need to consider collections.Summary In this chapter we have created two more classes. 110 . and explored how we derive classes from a base class.

Exercises 1. You could even create a MyTime class. 5. 2. Modify the MyDate class to display the name of the day of the week. simply use the English-language names of the days of the week. For now. That is. you will need to add the time of day to the class. 4. but do not eliminate the clarity. The Java libraries contain a DateFormat class. and the number of young. number of males and females. and a note about the sighting. create a Sighting class which contains the species of bird. or you will need to derive a MyDateAndTime class from MyDate. Explore that class more fully and use GregorianCalendar objects to replace MyDate objects. Rewrite the setRetirementDate method to eliminate some of the parentheses. we talked about birders and the sightings they make. 111 . Using either MyDate or GregorianCalendar. 3. Part of a sighting is the date on which it occurred. Are you thinking that the note would best be represented by several separate instance variables? Good. The Java libraries contain the GregorianCalendar class which we briefly considered. In a previous chapter. Use it to display a date with two-digit months and days. the date and time of the sighting. use it to eliminate the comparisons in the toString method of MyDate. bird behaviour. weather. If you use MyDate. This note may include location.

112 .

the same department may have a different number of professors at different times as professors retire or resign. All of these remind us that the world contains objects in multiples. by giving each Professor object a separate name. different departments have different numbers of professors. You may have noticed that a department at your college or university offers many courses. You may have noticed that a department at your college or university consists of many professors. containing within itself a number of different objects of type X. list. and a collection of occupations. First. lists. We can even have a 113 . how do we accommodate students taking varying numbers of courses? Some students may choose to take only three courses at one time. five. we have two situations. part 1 Learning objectives By the end of this chapter you will be able to:        Define collection. How do we accommodate varying numbers of professors in a department? That is. You may have noticed that your studies extend over more than one semester. list. and map Describe implementations of set. Similarly. commonly called collections. a collection of vacation destinations. Thus you can talk (in other examples) about a collection of automobiles. not as singles. Up to now. a collection of houses. set. or more. Second. Others may take four. A collection of X is an object. and map Compare and contrast the capabilities of set. we have been able to create two professors.Chapter 7 – Collections. and map Use sets. list. We need to look at data structures. You may have noticed that some of your courses have one section but others have multiple sections. and maps to represent complicated data Define iterator Use an iterator and a for-each loop to process elements in a collection Use a while statement Life is complicated You may have noticed that you are taking a number of courses. You may have noticed that a professor generally teaches more than one course. and new professors are hired.

114 . three of which are based on the unions and the locals of the unions to which they belong. you do not register as a student in a department or as a student in a course. there are at least four kinds of employees. you register as a student of the college. they form a collection. What follows is my opinion. I have done analysis (to understand the problem) and design (to find a good solution) in order to decide what I am asking you to implement. we‘ll be able to retrieve them. This collection of departments (in the College class) will be the only collection containing Department objects. This collection of professors (in the College class) will be the only collection containing Professor objects. we‘ll see that it is actually a collection of Department objects. This collection of students (in the College class) will be the only collection containing Student objects. Each department contains a collection of employees. The college model we are examining contains many collections. you can always find the object associated with that identifier. you will have a getter which accepts an identifier and returns the object which has that identifier. When you register as a student. When we implement this collection in an exercise. All other collections ―of professors‖ will contain only employee identifiers. from the college‘s collection of employees. Each kind of employee corresponds to a different collection. many of which will be in the College class. All other collections ―of departments‖ will contain only department identifiers. A college contains collections of employees. as long as we know the employee identifier. All other collections ―of students‖ will contain only student identifiers. rather than as a collection of Employee (or Person) objects. Thinking like this comes from courses in systems analysis and design. a different collection for each type of employee. These courses teach you the questions you should ask before you start to code. When we need Employee (or Person) objects. A note regarding the decision to have many collections of employees: At my college. I‘ve included a brief discussion of why I believe that collection is appropriate. we‘ll see that it is best to implement a department as a collection of employee numbers. provided you have the appropriate getter method for the collection. Collections the college model contains There are many possible ways to model the collections this college contains. The only employees we have implemented so far are professors. A college contains a collection of departments. a different type of organization. When we implement this collection in an exercise. A college contains a collection of students. For each collection. That is.collection of collections. The fourth kind is the administrators who are not in a union but are in an association. If you have an identifier.

we‘ll see that it is actually a collection of Meeting objects. There will be only one Student object representing each student at the college. This collection of meetings (in the Section class) will be the only collection containing Meeting objects. Next we have an interesting collection. the collection of sections. For past sections. We will also ensure that when an object is updated. one consisting of sections in which the student is currently enrolled. There are several such associations. While a course may appear to be offered by a department. Whenever any method needs information about a student. we‘ll see that it is best to implement a collection of section identifiers. All other collections ―of courses‖ will contain only course identifiers. This collection of sections (in the College class) will be the only collection containing Section objects. it will lead to problems later when we attempt to model the associations between students and sections. the update needs to happen in only one place. Each section contains a collection of students. This collection of courses (in the College class) will be the only collection containing Course objects. 115 . By having only one object corresponding to each item in the real world. Each student contains two collections of sections. When we implement these collections. When we implement this collection. and one consisting of sections in which the student was enrolled in the past. rather than a collection of Section objects. it is actually offered by the department on behalf of the college. rather than a collection of Student objects. While that may be reasonable. Why will some collections contain objects and some the identifiers of objects? The prime reason is that we wish to have only one copy of an object. one which represents the students in a section.A college contains a collection of courses. one which represents the sections in which a student is currently enrolled. we remember the marks the student earned at that time. Each section contains a collection of its meeting times. One possibility is that a course contains a collection of sections. All other collections ―of meetings‖ will contain only meeting identifiers. When we implement this collection. there will be only one Professor object representing each professor at the college. it will need the student identifier and can use that identifier to ask (by calling a method) the College class to search its collections and return the appropriate data. a better possibility is to have the college contain a collection of sections. and one which represents the sections in which a student was enrolled in the past. All other collections ―of sections‖ will contain only section identifiers. we will eliminate duplication of data. Rather than have the course contain a collection of sections. When we implement this collection. we‘ll see that it is actually a collection of Section objects. we‘ll see that it is best to implement a collection of student identifiers. When we implement this collection. we‘ll see that it is actually a collection of Course objects. That is. for example.

For example. but the number of courses a student takes may vary from student to student.      Is the size of the collection fixed.‖ Any course in database management will explain this in more detail. Many words have multiple definitions. The Java Collections Framework Collections may be categorised in many ways. Think also of the index of this book. let‘s see what Java provides to implement the collections. or may it vary? The number of months in the Gregorian year is fixed at 12. while a list has an order. But when you are creating a dictionary. the collection need only contain the words. the key might be a student identifier and the value might be a Student object. To check that an item is in the collection. or the list of items you need to pick up on the way home. There are very few words in the index that appear on only one page. the collection needs to contain both the word and a definition. The uniqueness is enforced by having unique identifiers. can they be placed in a different order? Does an item in the collection consist of a single value or is the item a pair. A map uses a key/value metaphor to store information. By asking questions such as these. These are lists as you may have two coins of the same denomination or two loaves of bread on your shopping list. The difference between them is that a set does not allow duplicates. Consider the coins in your pocket. and from semester to semester. is elegant. or are they unsorted? If they are in one order. but a list does. Sets and lists are collections of single values or of objects. Think again of the list mentioned above. (Another difference is that a set is unordered. The first column represents the key. Think of a table with two columns and many rows. We‘ll explore this in more detail later. consisting of a key and a value? If you are creating a list of the words used in a document. so each item of the collection may itself contain a collection. the second column represents the value associated with the key. the things you must pick up on the 116 . how many other items do we need to check? Is the collection designed to allow speedy searching? This matters when we are searching through large collections. since students are unique within a section and sections within a course are unique. chosen for no particular reason.These ideas are behind the practice of ―database normalization. Are the items in the collection sorted in some order. These would be represented by sets. One such word.) Consider the students in a section of a course or the sections of a course a professor teaches. we can determine the type of collection we should use in a particular circumstance. Now that we have an idea of what collections our model needs. Does the collection allow duplicate values or does it not? A rack of Scrabble® tiles can contain duplicate tiles but a hand of playing cards drawn from a 52-card deck cannot.

5. For example. HashSet is designed to allow speedy retrieval and insertion.google. 6. containing many of the core libraries used by Google projects. One collection type. 2. 2. But both allow an element to occur only once in the collection. These interfaces describe the characteristics of the collection without providing knowledge of the implementation details. 1. This is a project that Google has developed. a set is an unordered collection of items. Rather than reinventing these collections. we will use the Java Collections Framework in this textbook. We‘ll use some other Google libraries in a later chapter. since a word (the key) may have many meanings (the values). The Java Collections Framework also provides classes which implement the interfaces in varying ways. A third collection type (and interface) is Map. The key may be ―loaf of bread‖ and the value may be two. An implementation of this interface is HashMap. The Java Collections Framework provides collections via interfaces. is Set. We will look at some of the aspects of collections in this and the following chapters. a collection of data items with no duplicates and usually no order. {1. Guava contains many libraries.way home.com/p/guava-libraries/.google. More details on the Java Collections Framework are available in the Java tutorial. the same set as {3. 2}. This last statement shows that choosing the type of collection is not simple. However. Another collection type (and interface) is List. 3} is a set. 117 . A multimap is also called a dictionary.sun.com/docs/books/tutorial/collections/index. the key might be a course identifier and the value might be the professors teaching the course. 4. One interesting collection (of collections!) of them is available at http://code.com/p/google-collections/ if not from the previous URL. A multimap is a map in which the values are themselves collections. Implementations of this interface include ArrayList and Vector. and hence interface. TreeSet provides a sorting mechanism. a set. A set In mathematical terms. Implementations of this interface include HashSet and TreeSet. at http://java. with no duplicates. We will begin our discussion of collections by considering the simplest collection. which may be available at http://code. 4} is not a set because of the duplication of the number 4. {1. including the Collections library. there are other collections available.

Then. and one seminar section of the same course in a semester. There is no Java class for a multiset available as part of the Java Collections Framework. but none stands out as the predominant one. Even in this special case. They might be ordered by name. As noted above.Set. we can use sets in our model of the college. They might be ordered by employee number. 118 . At my college a student may be registered in two lecture sections of the same course at the same time only when the course is a Special Topics course and the two sections focus on different topics. we will sort the data structure before processing it. there are many possible orderings of professors. At my college a student may be registered in one lecture section. The collection of professors will be represented as a set since there are no duplicate professors. The Google project mentioned above does contain a multiset. Recall that this collection will be an instance variable of the College class. Use this import statement import java. nor will a professor teach the same section twice. one lab section. That ensures there are no duplicates. we need to import a Java library into the College class. Given these possibilities. Professors might be ordered by hiring date. we will impose an order. the order doesn‘t matter. We will assume no ordering on the elements. a student is not registered twice in the same section. What matters is that there are no duplicates in the collection. all of whom are employees of the college. should it be necessary. a person will not be registered twice in the same section of a course. This is very common and our model supports it since each section will have its own identifier. When it does. More correctly. To implement this collection. we will not impose an order until the time we need to process the collection. After all. They might be ordered by name within department.util. This is because every professor has a unique employee number or identifier. A collection of professors Let‘s consider how to implement a collection of professors. Does the order in which we store the courses in which a student is registered matter? Does the order in which we store the professors in a department matter? In general.There is a collection called a multiset (or a bag) which allows multiple occurrences of an item. but remains unordered.

Yes. Some people say it looks like pet food. If you look at the documentation describing java. BlueJ politely leaves a blank line at the beginning of the file when it creates the skeleton of a class for us. but one of javadoc‘s restrictions is that the comments describing the class must appear immediately before the class header. These are the classes which implement the capabilities of the Set interface. we need to know how to import it into our project. import java.HashSet. The idea behind the computer technique called hashing is similar. that it is an interface rather than a class. The food called hash is a mix of a variety of different ingredients. 119 . Now College contains two import statements.util. any import statements must appear at the beginning of the file describing the class.Set. that operation too is very quick. the hashcode. Why we choose HashSet is discussed below. we‘ll choose the HashSet.Set. Take the value of the Object and mix it up some way.Place this statement at line 1 of the class. import java.about. BlueJ will use javadoc to create the documentation for a class. The documentation lists All Known Implementing Classes. That is. Thus. so we need to import that package as well. we just need to know how to use it. Two Objects with identical values should give the same hashcode. All of this is described in the online documentation. and how to use those methods. Some hash recipes are available at http://homecooking. as expected. When you wish to use a class from one of the libraries (or packages). but one of the beauties of object-oriented programming is that we don‘t need to know the details of how a HashSet works. you must import that library or package.HashSet package.util. That number is an indication of the contents of the Object. An interface describes the capabilities of a data structure. Most of its complexity and power comes from its many libraries.util.htm. That is. you must import the portion of it which you need. but it does not describe how these capabilities are implemented. Of the several choices presented.‖ Java is actually a very simple language. what methods it supports. that retrieval is very quick. The Java documentation tells us that HashSet is in the java. When we need to place an element in the set.util. The word ―hash‖ refers to how the set keeps track of its members. producing a single number. HashSet A HashSet is a very efficient way of implementing a set. when we need to retrieve an element from the set. often chopped up. At least.com/library/archive/blhash. you‘ll find. there are other meanings for the word ―hash.

and its capabilities. That is. is independent of the type of data it contains. 120 . and thus place any type of object in it. While we could create a collection of Object. We are also asking the Java compiler and interpreter to let us know should we ever attempt to place some other type of object in the collection. It is much better to identify the type of element in the collection as precisely as we can when we first declare the collection. Miscellaneous. At least it will as long as we have gone through the BlueJ menu choices Tools. By writing HashSet<Professor> when we declare a variable we are saying we will be using a HashSet all of whose items are Professor objects. and checked ―Show compiler warnings when unsafe collections are used.Generic collections Java collections are generic. that is not a good idea since we might have to check the type of each object as we retrieved it. The compiler will display an error message when we attempt to compile a program including statements to add an object of an incorrect type.‖ Note that this will also cause the compiler to tell us whenever we declare a variable as just a HashSet without specifying the type of its elements. the collection. Preferences.

I have said that a set is unordered. This leads to variables called theProfessors. changing the first letter to lowercase and adding an ―s‖ to the end of the class. we are describing its general structure and capabilities. We do that in the constructor. Programming style When declaring variables which are collections. We have not yet indicated the specific implementation of Set we would like to use. and theMeetings. A different naming convention. I would name a collection of Meeting objects as meetings. HashSet<Professor> Note the details in the documentation that says that any Object placed in a HashSet must implement the equals and hashCode methods. To see this.theProfessors as there is no confusion possible between an instance variable and a parameter. all of whose elements must be instances of the Professor class. By declaring theProfessors as a Set. Thus I would name a collection of Student objects as students. and 121 . four. How do you name a collection? Sometimes I will often name a collection after the class of object it contains. When we add elements to the collection. Its declaration is private Set<Professor> theProfessors. hashCode is used to determine the location in the set which the Object will occupy. This creates a collection which is initially empty. when two Objects have the same hashcode.We need to name the collection of professors at the college. We do not need to use the name this. But there is nothing wrong with using it. and equals is used to detect collisions. theStudents. but the HashSet implementation needs to determine where in the set to place a particular object. prefixes the name of the class with the word ―the‖ and adds an ―s‖ to the end of the class name. Note that the order of elements using the hashcode may have no connection to the order you might expect. That is correct. and then use a specific implementation when the variable is instantiated. It uses the hashcode of the object to do so. Let‘s use theProfessors. I would name a collection of Course objects as courses. theProfessors = new HashSet<Professor>(). declare the type as an interface. suppose the hashcode is the number formed from digits two. the one I‘m using here.

In that case.equals(p. and 725.seven of the professor identifier. to check them for equality we use the expression p1. the definition of equality using names we have proposed won‘t be appropriate because it would say everyone is identical. If you have professors whose identifiers are 193456789. and 193456789 comes last. The equals method The equals method provides a way to signal when two objects have identical content.familyName. this definition wouldn‘t work in the John Smith Society. We have seen a similar use of the equals method while comparing Strings in the unit tests. 122 . This method returns a boolean whose value is true when the objects are both Person objects with the same name and false when either the objects are not both Person objects or they are both Person objects. We show this possibility later in this chapter. we could define equality to mean that the names are identical. This method examines two Objects.otherName. we can place the equals method in Person and it will be available to professors. Of course. A different way to calculate the hashcode would result in a different order. but some part of the names are different.equals(p2). They will be placed in the set in the order of the hashcodes. In the case of people. /* * test for Person object equality using names. 487654271.getMiddleName()). exactly the reverse of the order you might have expected. their hashcodes are 947. an American pioneer. } If we assume we have two Person objects (p1 and p2). one provided via the reserved word this (in the example above that object will be p1) and the other provided as a parameter (in the example above that will be p2). and any other type of person we create.getLastName()) && this. perhaps we should use an alternative form of equals. others say it is limited to members named John Smith. one which examines the identifier. result = this.givenName. and 777234567. Since a professor is a person. students. so 777234567 comes first. In the latter case. } return result.getFirstName()) && this. if (o instanceof Person) { Person p = (Person) o. Some stories say this society is limited to descendants of John Smith.equals(p. * @param o The Object to be compared against the current Object * @return true if both objects are Person objects * and the names are the same */ public boolean equals(Object o) { boolean result = false.equals(p. 862.

} Recall our discussion of George Boole earlier.getIdentifier()). result = this. This is probably safer since schools have unique identifiers for Persons. This method manipulates the contents of the Object to determine an integer which characterises the Object. What happens when a professor takes some courses. we will simply use its hashcode as the hashcode representing the Person object rather than inventing our own hashing algorithm. as noted above. we will have a collision (That‘s the technical term. Their classification at the college was support staff. But we could. a type of person we are not modelling here. Several recent graduates from a degree program were working at the college while completing the degree. If it is a Person object. In that case. 123 . but this is an advanced topic which we will not pursue here. thus becoming a student? At my college. we could check that the identifiers are equal. other names. Thus a better equals method is: /* * test for Person equality * @return true if both objects are Person objects * and the identifiers are the same */ public boolean equals(Object o) { boolean result = false.We cannot compare apples and oranges. The hashCode method Recall the details in the documentation that mention every object added to a HashSet must have a hashCode method. } return result. Since the identifier is an Object. both students and professors. the comparison fails. if (o instanceof Person) { Person p = (Person) o. there is no problem since the identifiers are the same structure.identifier. Alternatively. It is possible that two Objects may hash to the same number. Collisions are dealt with by the collection in one of several possible ways. If not.) when adding the Objects to a HashSet or a HashMap. and family names are identical. and the method returns the value false.equals(p. Every Object has a hashcode. so the method first checks that the Object (p2) provided for comparison is a Person object. then the objects are equal when the given names. boolean variables have the value true or false. as we saw earlier.

to be able to display a collection./* * @return hash code for the Person object */ public int hashCode() { return this. Yes. public void testGetProfessorCountZero() { assertEquals(c.identifier. But first. Thus we look in the Set documentation (rather than the HashSet documentation) and find a size method which will give us that information. How many elements are in the collection is independent of the way the collection is implemented.getProfessorCount(). we need a way to visit all the elements in a collection.) We may find it useful to know how many objects are in the set at any time. Create a test for this collection now. /** * How many professor are there? * @return the number of Professor objects teaching * at the college */ public int getProfessorCount() { return theProfessors. 0). We need no setter. } How many items are in a set? Now we have a collection in which we can place Professor objects (but we don‘t know how to place them there yet. or style. even when the collection is empty. even though the collection contains no professors. 124 .size(). at the moment there are none. } We saw a getter with no corresponding setter earlier when we discussed a professor‘s retirement date.hashCode(). We can include this in a getter method with no corresponding setter. } What are the elements in the set? I realise that we don‘t have any way of adding professors yet. but I find it a good practice. since the value we are getting is calculated for us automatically.

Note the opening and closing braces. /** * Add a Professor as a new employee. like this for-each loop. add an object to the collection. For a Set. I use single.Traversing a collection with a for loop Recent versions of Java provide a very convenient way to do this. one per line. that collections support an add method which will. public String professorList() { String result = "Professors :". Then do something with p. Now that we can visit the elements in the collection.add(p). } Since the collection we are listing is an instance variable of the College class. Adding a professor Java libraries have generally been well-designed (but see the earlier discussion about dates. we have no control over the order in which these visits take place. professorList is a method in the College class. The name p is just an abbreviation of Professor. Note that you cannot update or delete p this way. Here is a method to create a String which contains all the professors in the collection. we can list the elements in the collection. this addition will take place only when the element is not already present. this code will not compile even when there is only one statement which you execute for each element of the collection.toString(). 125 . obviously. * @param the Professor object to be added */ public void addProfessor(Professor p) { theProfessors. copy it into a temporary variable whose name is the one we have provided.or double-letter names to represent temporary variables which are used only within a small piece of code. As you visit an object. this statement means visit all the elements of the collection in some order.) We will find. If you omit them. for (Professor p : theProfessors) { result = result + „\n‟ + p. since sets do not allow duplicates. by looking further at the online documentation. p. the for-each loop. } return result. but you can display it or count it or examine its contents. for (Professor p : theProfessors) { // do something with the contents of each p } In English.

The explanation is the list of professors working at the college. Within that package is an object named out. As we have seen in many places so far. false). This object exists to display messages on the standard output device. 126 . One is to replace the call to assertTrue with System. You may do this within your unit tests in several ways. System is a package which the Java libraries provide us. One. It is always imported. The name println is an abbreviation for ―print line‖ which itself is an abbreviation for ―print some text and then move down a line. That is. Before testing professorList. the screen or monitor you are using.out. Which is better (or best) is sometimes a judgement call. which it always does in this case. by placing an X beside the name of the test (and displaying the dreaded red line). when we want the professors listed in alphabetical order. but the professor is not added. When you attempt to add the same professor a second time.‖ Compile CollegeTest. admittedly clunky solution. a matter of personal preference. A window appears in which you will be able to see the output of the test. After all. you do not receive an error message.println(c. This is a form of the assert statement we haven‘t seen before. In what order are the professors listed? Run the test again. Show Terminal from BlueJ‘s main menu. The order may change as you run and rerun the unit test.professorList(). The order does matter. Is this a problem with our program? No.} Create a unit test which uses this method to add some professors to the collection and then use professorList to display the list of professors. choose View. The out object supports a method called println which displays the value we pass to it. But there are other solutions. of course. where c is a variable of type College.professorList()). is assertTrue(c. it does not determine the order. Then test professorList. there is often more than one way to produce a result. in this case the representation of a professor. To clarify a statement I made earlier. When JUnit tells us the test has failed. the definition of a set says there will only be one occurrence of each value in the set. the addition is silently rejected. In it we provide a message (the first parameter) which will appear should the assertion (the second parameter) fail. click the name of the test and see its more-detailed explanation. the order in which elements of a set are listed does not matter so it may change from test to test. the hashcode is used to help determine the order in the set.

add(p). If you wish to pay attention to the value returned. We cloned addresses. some may be collections. but we don‘t yet have a clone method. Now clone the Professor object when you add it to the collection.Actually. and addProfessor should become. dateHired). but it seems to be acceptable in this situation. public boolean addProfessor(Professor p) { return theProfessors. as the last statement in your constructor for Professor. Some of these instance variables may be primitive datatypes. addr. /** * clone. } // end clone() Note that as we create more instance variables in the Professor class. birthDate. we should clone it. you will see the add method returns true when the addition is successful. Why should we not clone professors? Actually. Let‘s remedy that right now. Modify the unit test as well. fullName. It is usually not a good idea to ignore values returned by a method. * @return a copy of the Professor */ public Professor clone() { return new Professor(identifier. then addProfessor should return a boolean. firstName. when you check the documentation closely. fix the problem. Modify the constructor to make it so. Hence you can say it silently rejects duplicates. It returns false when the addition is not successful. Do your unit tests still work? If not. 127 . we will need to modify the clone method to ensure all the instance variables are cloned. middleName. lastName. } When should you add a Professor object to the collection? I would argue that it should be done when the object is created. preferredName. Cloning a professor Note that we have not cloned the Professor object when we added it to the collection. The addProfessor method we have created discards the value returned.

we place another import statement in the College class import java. Every Iterator object has two methods. Depending on how the collection is implemented. associate it with a collection. But. It would set a flag (an instance variable with a limited set of special values) to show that the professor is inactive. There are at least two types of inactive. If we wish to do this. to remove a professor. The for-each statement is very handy when we wish to just display the elements in a collection. or she could have retired. you should check the result of the hasNext method to be sure there is an unvisited item. see the Java documentation on Iterator. we do not know the object. This method assumes that we know (have a reference to) the object we wish to remove. As we visit the objects we may change them (including delete them) should we wish. o next returns the next unvisited item in the collection. we need to look through all the elements in the collection until we find the correct one. Thus. and then use the hasNext and next methods. However. an iterator may be implemented in many different ways. she could have resigned and gone elsewhere. We have already created a HashSet instance variable theProfessors. An iterator is a concept.util.Iterator. If we were developing a more sophisticated model. we do know its identifier. we would probably not actually remove the professor.util. since we cloned the object. We would probably mark her as inactive. 128 . Traversing a collection with an iterator and a while loop An iterator is an object which allows us to visit all of the objects in a collection. For more details than we have seen here. Before using the next method. the one with the identifier we are seeking.Removing a professor By looking at the online documentation we see that many collections support a remove method to remove an object from the collection. But we wish to delete an element from the collection and the for-each statement does not allow that. o hasNext returns the value true when there are more unvisited items in the collection and returns the value false once you have visited all the items. and then we remove it. an Iterator is a class that implements the iterator concept. We need an iterator. removeProfessor would not actually remove the professor. But we won‘t worry about its details! It is sufficient to know that we import the Iterator class from java. To allow us to create its iterator.Iterator. should there be one.

In English. the loop is completed. o Step 3 – If there are no more elements. o Step 2 – If so. Instantiate the iterator (attach it to the correct collection and ensure it is initialised) when we need it. The hasNext method returns a boolean value.In any method in Professor which requires an iterator. it = theProfessors. When you are using an iterator. if any.iterator(). o Step 1 – check whether there are more elements in the HashSet. Cupertino. enclosed in braces) should be executed and then whether the statement (or statements) should be repeated. process the element which is available. This means that something inside the loop must change the value of the condition.hasNext()) { result = result + '\n' + it. there are no more elements to process. By the way. While the condition remains true. it = theProfessors. you often need a while loop as well. this while loop does the following. } Recall our discussions of George Boole earlier. We know no way to get out of an infinite loop yet. If it is false. California. Iterator<Professor> it. we have processed. public String professorList() { Iterator<Professor> it. to make sure it iterates over all members of the HashSet<Professor>. and repeat Step 1. while (it. 129 .iterator(). boolean variables have the value true or false. so resume execution of the method with the statement following the closing brace at the end of the while. Here is a version of professorList which uses an iterator and a while loop. A while statement (or while loop) uses a condition to determine whether a statement (or a block of statements. the loop continues processing data. place a statement to create but not instantiate an instance variable which is an iterator over Professor objects.toString().next(). String result = "Professors". Otherwise you have created what is called an infinite loop. Apple Computer has its headquarters located at 1 Infinite Loop. When it returns true there are more elements in the HashSet beyond those. ignoring any previous setting it may have had. } return result.

} else notFinished = it.equals(p. Each department contains a collection of professors. /** * remove a Professor from the collection.hasNext().getIdentifier())){ theProfessors.hasNext(). boolean notFinished = it. } } } The iterator provides the elements in the collection one element at a time. Since there is only one professor with the specified identifier.next(). The break statement is equivalent to ―terminate the loop immediately!‖ Some would say that a break statement is a harsh way to terminate a loop.iterator(). rather than a collection of Professor objects.remove(p). the identifier of the object we wish to delete. while (notFinished) { Professor p = it.In a similar manner we use an iterator and a while loop to create a removeProfessor method. we use the collection‘s remove method to remove the object. if (target. * @param the identifier of the Professor object to * be removed from the collection */ public void removeProfessor(String target) { it = theProfessors. Is this a better way? public void removeProfessor(String target) { Iterator<Professor> it = theProfessors. if (target. When we implement a department.getIdentifier())){ theProfessors. break. it is a collection of professor identifiers. we need look no further. and then we use a break statement to terminate the loop immediately.hasNext()) { Professor p = it. We compare the identifier (the employee number) of the element to the target. while (it. } } Does this method work when you attempt to remove a Professor object which does not exist? Another collection of professors – the department A college contains a collection of departments. notFinished = false. 130 . Once we have found the appropriate Professor object.remove(p).iterator().next().equals(p.

private String chairPerson.add(identifier). String chairPerson) { this. public Department(String departmentName.hasNext()) { String s = it.chairPerson = chairPerson.next(). theMembers = new HashSet<String>().equals(s)) { theMembers.remove(s). for (String id : theMembers) { 131 . } } } } Listing all the professors Now let‘s consider the problem of listing all the members in the department.Iterator. this. It is easy to list just the employee numbers.util.util.departmentName = departmentName.iterator(). } public void removeMember(String identifier) { Iterator<String> it = theMembers. while (it. } public void addMember(String identifier) { theMembers. import java. return result. public class Department { // instance variables private String departmentName.HashSet. private Set<String> theMembers. } public String toString() { String result = "Name: " + departmentName + " " + "Chair: " + chairPerson. import java.Set. public String departmentList() { String result = "Department:" + departmentName.Here is a portion of the code to implement a department. if (identifier.util. import java. break.

return theCollege. } This method is the access point for theCollege. theProfessors = new HashSet<Professor>(). It will have no parameters. this. private College() { this. but the best is to recognize that we will probably be modelling only one college at a time. } But how do we list the names of the employees? The only objects which know the names of the employees are the elements of the theProfessors collection within the College class. create a getInstance method which returns theCollege. make the constructor private. Consider these modifications to the College class.name = null. } return result.homePage = null. Whenever your program needs information about the college. this. so you will need to use the setters to specify its name.mailingAddress = null.getInstance(). Thus it may be possible to determine the College object which we are using by simply asking the College class itself. First. How do we access that collection? The Singleton pattern There are several solutions. this. It is null as it is not associated with any data yet.streetAddress = null. Second.phoneNumber = null. create a College object.result = result + '\n' + id. it uses College. It is static so that there is only one such object. private static College theCollege = null. phone number. // any other collections } Did you import all the correct classes? Third. public static College getInstance() { if (theCollege == null) theCollege = new College(). the method should create it and then return it. Your program will contain many statements that say 132 . If that variable does not yet exist. this. It is private so that it is accessible only through a method. etc. which we will create in a moment.

12). so we can be sure that any updates happen in only one place. 10. public String departmentList() { College c = College. } return result. Patterns will be covered in more detail in a later chapter. This particular pattern is called Singleton. } The unit test involves creating a college. Now we have all the pieces to produce a list of the members of a department. public void testDepartmentList() { // sample dates MyDate date1 = new MyDate(1999. creating some professors who work at the college. public String getProfessorName(String identifier) { String result = "". If we do not find the professor. MyDate date2 = new MyDate(2004. Listing all the professors. creating a department. and then listing the members of the department. but in every case the object c will refer to the same College object. given the employee‘s identifier.College c = College. continued Now that we have access to the College object.getInstance(). placed in the College class. showing the names of all the members.getFullName(). String result = "Department:" + departmentName. } } return result. The word pattern is used to describe such generally-useful techniques. for(Professor p : theProfessors) { if (identifier.equals(p. This method. we can use it to determine the name of an employee. } When we find the professor with the correct employee number we return the name. 133 .getIdentifier())) { result = p. we return an empty String. placing some professors in the department. for (String id : theMembers) { result = result + '\n' + c. That is the one place which contains a collection of the objects in the model. 8).getProfessorName(id). will do it. break.getInstance(). This technique is one which has been used in many circumstances. 12.

"F2 M2 L2". removeDepartment.out. this unit test appears to show that the department chair is not a member of the department. Use these // statements only if your constructor does // not add the professors to the collection c. date1. "M1".addProfessor(p3). You will need the statement theDepartments = new HashSet<Department>(). date2). date2).// sample professors Professor p1 = new Professor("111". null. c. null. 134 . System.addProfessor(p2). date1.println(d1. // the department Department d1 = new Department(“Gaelic Studies”. "M2". // professors work at the college. // professors are in the department d1. and departmentList methods. We will leave it as an exercise for you to implement the collection of departments. how would you modify the Department class? Collection of departments Now that we have a functioning Department class. p2.addProfessor(p1). "F1 M1 L1". date1. Professor p3 = new Professor("333". "M3". "F2".departmentList()). null. Professor p2 = new Professor("222". "F3". "p3". "L1".getFullName()). "F3 M3 L3".addMember("111"). } The department list appears in the Terminal window since this test uses System.out. we can modify College to contain a collection of Department objects. By the way. Is there a clone method for departments? There should be one. c. "L3". "L2". If it is not.println instead of assert. d1. date2). and the addDepartment.addMember("333"). "F1". Ask your professor to see if this is the situation at your college or university. "p1". "p2".

and studentList methods. the set. We have seen one type of collection. including lists and maps. and much of what we have said about departments.Collection of students As mentioned earlier. We will leave it as an exercise for you to implement the collection of students. Everything we have said about the collection of professors. and how to use it. You will need the statement theStudents = new HashSet<Student>(). removeStudent. and the addStudent. a college contains a collection of students too. also applies to the collection of students. they come in collections. 135 . Is there a clone method for students? There should be one. We noted that there are other kinds of collection. which we will see in subsequent chapters. Summary Things in the world do not come in singles.

and retired. we discussed modelling a bank account. Create a YardList class which contains a collection of all the sightings a birder has made in his/her yard. create a class which contains a collection of all sightings made at some specific location. In a previous chapter. That is. Bank accounts have transactions associated with them. Possible values are active. create an instance variable which contains the professor‘s status. Implement the collection of departments referred to in this chapter. The most-unusual was the birder who kept a list of all species seen reflected in the monitor of his computer. In a previous chapter we discussed modelling the sightings a birder makes. Then modify your BankAccount class to contain a collection of Transaction objects. The transactions come in many forms – withdrawals. If you imagine the birder does not live in a house. I have heard of birders who maintain lists of the birds seen from work. preauthorized deductions. 6. You should be able to produce a list of all the students registered at the college. Having a PlayingCard class allows you to model any number of card games.Exercises 1. Choose a card 136 . deposits. the College class will contain a collection of Department objects. To do this. 4. 3. or seen in the movies. interest payments. That is. Only active professors should appear in the output of professorList. the College class will contain a collection of Student objects. I imagine that list doesn‘t get much use now. or should there be a Bank class which contains the collection of Transaction objects? Why? 5. resigned. Model a Transaction class. etc. In a previous chapter we discussed modelling playing cards. Modify the college model so that a professor is not actually removed from theProfessors. or seen on the trip to and from work. but lives in a flat (or an apartment). Should you use a Set or a List? Why? Should the BankAccount class contain the collection of Transaction objects. With LCD monitors. 2. Implement the collection of students referred to in this chapter. which faced out the window. You should be able to produce a list of all the departments at the college.

Create a class. Implement a Multiset class. Examine the Google MultiSet class and see how your code differs.wikipedia.org/wiki/Dice_game. How would you model a game which uses several 52-card decks at once? 7. In bridge. consult http://en. which contains a collection of dice. For some possible games. 8. you may be holding many. In Go Fish.game with which you are familiar and create a class which contains a collection representing the cards you may hold at any time. you may be holding 13 cards. Many games use several dice. the skeleton for a game. In a previous chapter we discussed modelling a die. In poker you may be holding five. 137 . In this chapter we referred to a multiset.

138 .

the number of credits a student earns by passing the course (int). and abstraction. What is a course? What data do we need to remember about courses? The Course class At my college. whose title is ―Computer Programming I‖. and understanding of computer programs. algorithm design. this textbook was written to be used in COSC (the subject abbreviation) 111 (the course number). A collection of courses Not only does a college contain a collection of students. It also needs a course title (String). laboratory (double). we will examine more of the collections a college contains. The course title is a short phrase. a Course object needs a subject abbreviation (String) and a course number (int). and the number of hours each section of the class meets (lecture (double). This includes the production of complicated reports. including formatting numbers. part 2 Learning objectives By the end of this chapter you will be able to:      Describe the use of a comparator Implement a comparator and use it with ordered collections Use a TreeSet Format numbers Produce reports from collections Introduction In this chapter. and then focus on tools and techniques we need to be able to process collections. For example. and seminar (double)). the course description is a longer statement about the course. Topics include problem solving. and a collection of departments. a collection of employees. it also contains a collection of courses.‖ 139 . and whose description is ―This course is an introduction to the design.Chapter 8 – Collections. a course description (String). with the emphasis on the development of working problems. implementation.

For this course. at least according to the standards at my college.5. the triplet is (4. and find the Format class. with 3. The outputs should be (3. most programmers waste a few bits and use double instead of float. four lab hours. Thus (3.0) is two-thirds correct and (3. 2.5 lecture hours. 2. We will adopt that practice. including the constructor and the toString method. 2. the lab hours will be no more than five.5. 0). and seminar hours is slightly incorrect.0) is totally incorrect. Using the idea of ―formatting‖ numbers. You can see this by visiting http://www. in the order lectures.ca/calendar/coursedescriptions/university_studies/computer_science. the values will be no more than 50.html. didn‘t it? Different colleges display their hours differently. 0) and (3. We need a way to format the numbers as they are converted to Strings. What happens when you run the unit tests? Are they successful? Formatting the output Examine the output.‖ That sounds like what we want to do.bc.5. Everything looks fine until you notice that the triplet containing the lecture hours.0. 0. Larger hours will occur for courses which are taught in an intensive manner (all day for a week. and no seminar hours. In this example. As memory is cheap. Create unit tests to ensure a few courses are created correctly.0. 140 . and one seminar hour. lab hours. A double is a primitive datatype (hence begins with a lowercase letter) which stores numbers with a decimal point. Sample courses could include:  A course worth one credit. you look in the Java documentation. 2. messages.  A course worth three credits. with zero lecture hours.The hours will appear in the calendar as a triplet. 2.0 is a double. but we will use double rather than the smaller float datatype. Course – unit tests Create the Course class. This is ―an abstract base class for formatting locale-sensitive information such as dates.5.okanagan.5 lab hours. seminars. My college standard is that numbers with a zero after the decimal point should be displayed as integers. but we can‘t instantiate objects of an abstract class. if only so that we do not need to put the letter f after numbers. The double datatype allows numbers much larger than these. and no seminar hours. 0). 0. and numbers. two lab hours. Your toString method did display the hours. for example) before a semester begins or after it has ended. In our model. the credit hours will be no more than four. 2.  A course worth two credits. with three lecture hours. 1.0f is a float and 1. the seminar hours will be no more than two. labs. That is. usually the lecture hours will be no more than five.

sun. Notice that we are using a different Java package for this class. you‘ll see NumberFormat which is also an abstract base class. result = result + ″-″ + credits + ″-″ + myFormatter.util. totalHours = lectureHours + laboratoryHours + seminarHours.' + myFormatter. result = result + '\n' + title + '\n' + description + ″ (″ + myFormatter. you realise that this class will solve our problem. Thus. The ―see also:‖ section of NumberFormat includes a link to DecimalFormat.format(seminarHours) + ')'. to Course.text. Modify toString so it appears as follows. ―a concrete subclass of NumberFormat that formats decimal numbers.format(laboratoryHours) + '.' + myFormatter. return result. and that formatting consists of two steps. we add the statement import java. formatted according to the pattern you specified.#″ will provide the output in the correct format.format(lectureHours) + '. double totalHours. In our case. It will display the digit before the decimal point and will display the decimal point and digit following it only when that digit is not zero. Comments have been omitted in the interest of saving trees.  Second.In the ―see also:‖ section of the documentation. you create a formatting object using a specific pattern which shows how the output is to be formatted. which returns it. } 141 . String result. entitled Formatting.DecimalFormat. you provide a number to that formatting object.‖ Exploring this class eventually leads you to a chapter in the Java tutorial. http://java.  First.com/docs/books/tutorial/i18n/format/index After reading through the tutorial.#″). result = subjectAbbreviation + ″ ″ + courseNumber. specifying a pattern of ″#. public String toString() { DecimalFormat myFormatter = new DecimalFormat(″#. Previously we have imported classes only from java.format(hours).

This is so that a student who graduated many years ago can ask for details on the course. 142 . The index usually starts at 0. recent or ancient. At a small college or university. For the last element in the list. What happens if you create a class with 10 or more hours of lectures per week? A collection of courses. there is a next element. ever. a third-year course in any subject may have only one section. in which there is some ordering of the elements based on position in the list. For a circular list. we discussed which class should contain the collection of sections. the first element in the list. there is a first element and there is a last element. I decided that it would be the College class which contains a collection of sections. A first-year English course may have many sections. the first element in the list has a previous element.Create the unit tests for the getters and setters. moving other elements to subsequent positions. What type of collection will we use? Set? List? Rather than using a Set as we did earlier. we can resume discussions on a collection of Course objects. and we can base its implementation on our implementation of the theProfessors collection. you specify the name of the array and the index. That is. I simply would like to look at another type of collection. You may insert new elements at the end of the list. the last one in the list. each of which is associated with a position number or index. a List. Note that there is nothing wrong with a set. The Section class A course is offered in one or more sections. The collection will be part of the College class. Make it so. A set would be an acceptable implementation of this collection. For each element (except the first) there is a previous element. let‘s look at another type of data structure. For each element (except the last) there is a next element. except that we do not want to remove courses. or in the middle of the list. In the previous chapter. An array is a collection of elements. then create the getters and setters themselves. To retrieve an element from an array. An array is a type of primitive data structure found in almost all programming languages. continued Now that we have a Course class. A list is a collection of elements. a first-year calculus course may also have many sections.

143 . you‘ll see that you have created a data structure with room for 10 elements. Do we need to clone the Section when we add it? Yes. the object is added at the beginning of the collection rather than at the end. If that position is zero. so none of the code will even compile. we made an error in our original analysis of the problem and designed a class which omits an important feature. We will correct this omission in the next chapter. We want only one copy of the Section available so that when we change a meeting time of the Section. but we don‘t have a Section class yet. the collection will expand to hold the extra values. the position (or index) at which the object is to be added and the object itself. /** * add a section to the offerings of a course. private List<Section> theSections. import java.ArrayList. allocate some memory to the data structure this.List. * @param s the Section to be added */ public void addSection(Section s) { theSections. where we create a Meeting class. In the constructor. } The online documentation tells us that this method adds the section after already existing elements. we need only change it in one place. To College. use an alternative form of the add method.An ArrayList is an implementation of the List interface. And then declare the data structure. add the import statements import java. If you wish to add it elsewhere. one which has two parameters.theSections = new ArrayList<Section>(). If you add more than 10 elements to the collection. You said the Section doesn‘t contain a meeting time? Oops. By what amount does it expand? Create a method. Correcting this omission is another example of refactoring. addSection. we should. whose underlying implementation is an array. The code in the last few pages looks good.util. which will add a section to the Course. at the beginning of the list for example.add(s).util. When you read the documentation describing ArrayList.

for example. and  The day of the week. to indicate the winter semester of 2008. But what is ―winter‖? My college uses something similar. There are two aspects to ―when‖. So. This gives us another instance variable. and seminar sections begin with the letter S.What is a section? What information do we really need to model a Section? We have used unique identifiers for professors (employee numbers) and for students (student numbers). lab section numbers begin with the letter L. or a seminar section. the meeting details in the next. 20. plus something to indicate when the section is offered. one possible unique identifier is subject abbreviation. That sounds complicated. private int courseNumber. we need to know whether we are dealing with a lecture section. Summer as 20 and Fall as 30. For our reports. At my college. and 30. lecture sections will have a numeric section number. A section of a course offered this year is different from a section of the course offered last year. F2008 and S2008 might also be used. 144 . Let‘s create a unique identifier (a number) instead. One possibility is to store W2008. It has three semesters in the year. Thus a Section object also needs to contain instance variables defining the semester when it is offered. private int identifier. a lab section. even though we use the term ―section number‖ we will not represent it with a number. The semester beginning 2010 January 1 is 201010. private String sectionNumber. the start time on that day. course number. We will ensure this by having a Section object contain the subjectAbbreviation and the courseNumber. Thus we have the beginning of a Section class. and the semester beginning September 2010 is 201030. For sections. We will cover the semester in this chapter. numbered 10. We still need the course with which a section is associated. private String subjectAbbreviation. and the end time on that day during that semester. The combination of subject abbreviation and course number ensures uniqueness for courses so we don‘t need a unique identifier. We need to know when and where a Section object meets. the semester beginning 2010 May 1 is 201020. We have defined Winter as 10.  The semester in which the section is offered.

We need to modify the toString method so it shows the start and end dates. and month) as well as the end date (year. But remember that the month and day-of-the-week constants in the Calendar class all begin at zero. the winter semester (Calendar.AUGUST). and month). The Calendar class provides us with Calendar. we mentioned the Calendar and GregorianCalendar classes. We represent the day of the week (needed in the next chapter) similarly. Second. Warning – just because unit tests are ―left to the reader‖ doesn‘t mean they are unimportant. stored as at least four digits. or should that be Calendar. We need to modify the constructor to accept the values of those instance variables and we need setters and getters as well as creating and/or modifying the appropriate unit tests (an exercise left to the reader). the months need to be increased by one before printing. So long as we can remember to increment (increase by one) the value before we display it.SEPTEMBER through Calendar.DECEMBER?).A better. First.SUNDAY. Calendar. recall the problems we had displaying birth dates. Thus. We need to deal with two subtleties in toString. we used an if statement to display a zero if necessary. When discussing birthdates. private int endYear. A section of a course is different when it is offered in the fall semester (At my college that is September through December.JANUARY through Calendar. more-generally applicable. when you display Calendar. if necessary. etc. private int endMonth.APRIL). or the summer semester (Calendar. The author refuses to evaluate any classes which his students submit without a complete set of unit tests. As a solution. solution is to remember the start date (year. We can do that. private int startYear. But now we know how to use the DecimalFormat class to print that leading zero. that is. Another is that the Field Summary portion of the documentation describing Calendar says the values for the months and days of the week are ints and we are using its constants. with single integers less than 10 displaying with no leading zero.MAY through Calendar. we will be okay.JANUARY. you‘ll see zero rather than one. Why did I make these variables ints? One reason is that the values these instance variables will contain are small.MONDAY. also stored as at least four digits. We need to add some instance variables to the Section class. private int startMonth. 145 . The Calendar class has some constants representing the months of the year.

with the first one being zero if necessary. as when we wish to add. we need a method in the College class which returns a Course object. public Course getCourse(String subjectAbbreviation. a section.equals( c. The following statements form the body of the toString method. Sometimes we need to retrieve single Course objects.format(endMonth + 1) + ')'.getCourseNumber()) return c. Can you explain why the output is not what you expected? The Singleton pattern revisited The College class is acting as a gatekeeper to the individual Course objects. String result. int courseNumber) { for (Course c : theCourses) { if (subjectAbbreviation.getSubjectAbbreviation()) && courseNumber == c. } // no matching course found return null.format(startMonth +1) + ″ to ″ + endYear + '-' + myFormatter. } Using the object returned by this method. The pattern we have used (in the constructor) causes two digits to be displayed. or remove. when we provide its subject abbreviation and course number. What would the output be if we used result = result + ″ (″ + startYear + '-' + startMonth + 1 + ″ to ″ + endYear + '-' + endMonth + 1 + ')'. DecimalFormat myFormatter = new DecimalFormat(″00″). we are able to add sections to the courses the college offers. + ″ (″ + startYear + '-' + myFormatter.DecimalFormat actually lets us solve both problems simultaneously. That is. as it does for Professor objects. // details of the section result = identifier + ″ ″ + departmentAbbreviation + courseNumber + ″ ″ + sectionNumber. 146 .

Comparable Since we have used the word ―compare‖ several times. you may want only the month and the day. For example. The Comparable interface is interesting. there are several orders which matter for professors. we must have some way to decide whether one element of the collection precedes another. The mark may be for a semester. but that is not a solution to our problem. The closest match is ―Comparable‖. some values are more important than others. family name is more important than given name which is more important than middle name. In all comparisons. Of course.org/iso/date_and_time_format for more than you wanted to know about dates. This one way of sorting is sometimes called the natural ordering for the data. when sorting a group of people by name.iso. we need to be able to describe how to compare two Course objects. or perhaps by hiring date? 147 . or it may determine which of the graduates receive medals or scholarships. In the context of a college. When sorting by date. when you are producing a list of people in order by their birthday. the year is probably more important than the month which is probably more important than the day. we need to be able to describe how to compare one professor to another to determine which precedes the other. The natural order for Strings is alphabetic. To produce a list of the courses offered by the college in alphabetical order by subject abbreviation. To produce a list of the professors employed by the college in some special order. Let‘s begin by seeing how to compare Professor objects. mentioned earlier (by identifier. employee number. specified in a compareTo method. using the Unicode coding scheme. name. you may have gone to the online documentation and looked up ―compare‖. The international standards for dates. See http://www. the year may not matter. to determine who is on the Dean‘s List or receives scholarships. there are several orders which matter for students. But what is the natural order for professors . or average mark. To produce a list of the students registered at the college.Listing a collection in order Whenever we talk about listing a collection in order. The natural order for numbers is numeric. In the context of a college. so we make sure we compare them first.) We see that we need a technique which allows us to specify several different types of ordering for a class. mentioned earlier (name. by identifier.by name. hiring date). by salary. year/month/day reflects this view of importance. since Comparable only allows one way of sorting. we need to be able to compare two Student objects.

compare the given names. The capital letters were kept in the upper part of the storage area. They are named ―uppercase‖ from the olden days when printers had to make up lines of text by placing individual letters into trays. hence the term lowercase. When they are the same. and the lowercase 148 . We begin by having the Person class (after all. To use Comparator objects you need the statement import java. or you could notice that the String class has a compareTo method which returns the same values as a Comparator. All Comparator objects contain a method named compare. Uppercase letters are the capital letters. If the family and given names are the same.Comparator.pdf. you‘ll find that the uppercase letters we need are represented by hexadecimal values between 0041 (the first three digits are the column heading on page 2 of that document) and 005A. you know which is less. the other letters were kept in the lower part of the storage area.org/charts/PDF/U0000.unicode. We have used the terms uppercase and lowercase in previous chapters.What entry comes immediately after Comparable in the online listing of classes and interfaces? The Comparator interface! This is what we need. at http://www. The String class also has a compareToIgnoreCase method which you may choose to use if you wish to ignore the difference between uppercase and lowercase letters. the one commonly used in English-speaking countries. zero when their values are equal.util. Comparators The Comparator interface allows us to have many compare methods associated with one class. at the beginning of the Person class and any other classes which use them. hence the term uppercase. a professor is a person) create a Comparator object. The logic of an alphabetical comparison is: Compare the family (last) names. and a positive integer when the first is the larger. When you look at the Unicode description for the Latin alphabet. Similarly. You could write this using a series of if statements. When they are not the same. How are uppercase and lowercase letters stored in a computer? They are all just bit patterns. All compare methods behave in the same way: they accept two parameters and return a negative integer when the first is less than the second. compare the middle names.

* Both objects must be Person objects. How would you change the method to return false if the two objects are not both Person objects? 149 . When comparing characters. treat the characters as numbers. Any statement about what must be true after a method completes its processing is known as a postcondition. compareTo(p2.getFirstName(). and should be documented in the method. if (result == 0){ // family names are the same result = p1. It will not work if this assumption is not valid. Why would you want to ignore case as you compare names? Perhaps you want to have Von Smitz and von Smitz appear together on the list. given name. Person p2) { int result = 0. /** * Alphabetic comparison. Character. Interesting. That is. // compare family names result = p1. } return result. and simply subtract the hexadecimal number 0020 from the numeric equivalent of the lowercase character. which is less than any lowercase letter. * @return negative. positive if Person p1 is <.getMiddleName(). Note that this method assumes both objects being compared are of type Person. Any statement about what must be true before a method is invoked is known as a precondition. compareTo(p2. if (result == 0) // family and first names are the same result = p1.getLastName()). =. */ public static final Comparator<Person> ALPHABETIC_ORDER = new Comparator<Person>() { public int compare(Person p1.toUpperCase.getFirstName()).getMiddleName()). compareTo(p2. note that a blank is less than a digit.letters are represented by hexadecimal values between 0061 and 007A. But it is easy to convert from a lowercase letter to the corresponding uppercase letter. and other name.getLastName(). * or > Person p2 * based on the family name. which is less than any uppercase letter. Within the uppercase (and lowercase) category. } }. the uppercase letters have a lower hexadecimal representation than the lowercase letters. letters compare in normal alphabetical order. Fortunately there is a method. 0. to do this automatically for us. It too should be documented.

is just declaring an object (called ALPHABETIC_ORDER). That semi-colon must be there as this statement. there should be many unit tests. unit tests. and we can‘t create unit tests for abstract classes. "Dennis". "Richard D. and ―h‖ is less than ―k‖. and every declaration statement must end with a semi-colon. public void testComparator1() { Student s1 = new Student("123". and Professor classes. "". a. and there are three comparisons. "Gee". Gee". There is no need to test the first name when we know that the family names are different.ALPHABETIC_ORDER. But we note that both Student and Professor are derived from Person. or 27. including null. The first three letters of the given name are the same. d).Particularly note the semi-colon after the final brace. Unit testing the comparator How do you create a unit test for a comparator? This is particularly difficult with the comparator we have written. "Rick". This Comparator is declared to be static. For characters. Thus we need three tests 150 . following the convention that constants (declared using the reserved word final) are capitalised. "Rick". There may be many Person objects. they could have any value. Here is one such test. "Richard". since it is in an abstract class. The test will succeed. But some of the tests are unnecessary. } The variables a and d are the names of Address and MyDate objects. For this unit test. one for each possible path through the comparator. "Rick". but the fourth letters are different. "Gee". To fully test the comparator. lengthy though it is. d). so we can place our unit tests in the tests for either of those classes. a.compare(s1. The family names of the two students are the same but the given (or first) name of s1 is less than the given name of s2. Student. Compile the Person. Thus there are theoretically three (the number of outcomes per comparison) raised to the power three (the number of comparisons). s2) < 0). "Richard D. but they all use the same method when comparing two Persons alphabetically. How many? Each comparison can have three outcomes. from the Student class. Student s2 = new Student("125". The digit on the end of it is meant to imply there will be many such tests. Gee". alphabetical order translates into ―less than. This is only sensible.‖ Note the name of the unit test. The name of the comparator is capitalised. This means there is only one method with this name (ALPHABETIC_ORDER) within the Person class. assertTrue(Person.

we see an alternative form of the comparator. one which requires only three comparisons and hence only three unit tests. Producing an alphabetical list of professors How do we combine our knowledge of collections and comparators so that we can produce a list of professors at the college in alphabetical order by name? We find that we have a problem.getMiddleName(). Consider the two names Pauly Ian Smith and Paul Yian Smith.getFirstName() + „ „ + p2.getMiddleName().compareToIgnoreCase(name2). each of which may have three outcomes. But then I realised that there could be examples in which the space would matter. we will see comparators for different classes. we replace the compareTo methods in the comparator above with compareToIgnoreCase. Alternative versions of the comparator Note the comment above about the distinction between lowercase and uppercase letters. public static final Comparator<Person> ALPHABETIC_ORDER_ALTERNATIVE = new Comparator<Person>() { public int compare(Person p1. Thus we only need nine tests. You could also combine the parts of the name into one string and compare those. We need three more to deal with the middle name if the family and given names are the same.getFirstName()+ „ „ + p1. We need three more to deal with the given name where the family name is the same. We have implemented theProfessors as a HashSet because of its speed. } }. If we wish to ignore the case of the names (so that we treat Von Smitz and von Smitz as identical). String name2 = p2. or 81. return name1. But now we need a different implementation since a HashSet is not sorted and cannot be sorted. which will involve four or more comparisons. In the section which follows. 151 . When I first wrote that method I did not include the single characters between the parts of the name.getLastName() + „ „ + p1.to deal with the family name. This is yet another example that there are often many ways to accomplish the same result. unit tests. thus requiring three raised to the power four. Person p2) { String name1 = p1. That gives the following comparator.getLastName() + „ „ + p2. In subsequent sections.

First.TreeSet. creating a new set ordered as the Comparator prescribes. the normal follow-up to an introductory programming course.ALPHABETIC_ORDER). Most of the time. /** * produce a professor list. we leave the set in its unsorted state. Then we create a new method. If you want more details. } return result. we add an import statement.So we choose a different implementation of the Set interface. revisited Note that we have again used the for-each statement to visit all the elements in a collection. the TreeSet. 152 . prefix = "\n". alphaProfessorList. in alphabetical order.toString().util. for (Professor p: alphaProfessors) { result = result + prefix + p. We are not altering those elements so we do not need an iterator. but we will do the transfer only when we need the data in sorted order. we simply need to visit the elements of the TreeSet one after the other and we will visit them in alphabetical order. Once that is complete.addAll(theProfessors). The addAll method transfers all the elements of the (unordered) HashSet into the (ordered) TreeSet. The for-each statement. We will transfer the data from the HashSet to the TreeSet. To use a TreeSet requires the following two changes in the College class. How a TreeSet represents its elements in order is of no concern to us right now. } The statement that creates the TreeSet indicates what type of objects will be in the set and what comparator is used to compare two such objects. alphaProfessors. import java. String prefix = "". consider taking a data structures course. // traverse the Set (in alphabetical order) // and compute a String String result = "". */ public String alphaProfessorList() { // create the TreeSet Set<Professor> alphaProfessors = new TreeSet<Professor>(Person.

At that time. you are not debugging it. By the way.toString().org/wiki/Computer_bug.ac.String result = ″″. You are finding and removing the errors in your program. The reason is to get you reading code and understanding it. To fix the problem. Wikipedia points out the previous history of the term and notes there is some question about this story. } We could use an iterator to process all objects in the collection but this for statement provides a shorthand way of referring to individual elements in the collection. Having errors in your program is not funny! To get an idea of the problems that errors cause. 153 . It is available online at http://catless. they were very large!) to check out why. which we used in the beginning of this course but haven‘t used lately. Debug is a term that dates back to the beginning of computers. When you right-click a unit test on your class diagram. That link provides a link to subscribe. I suggest you become a faithful reader of the Risks Digest.wikipedia. but you need to understand what it does. This can be useful when we are trying to debug (fix the errors in) an object or class. they found a moth (colloquially called a bug) had become caught in the switch. the moth was removed. In any case. BlueJ revisited This may be an appropriate point to mention the Test Fixture to Object Bench menu option. String prefix = ″″ for (Professor p:alphaProfessors) { result = result + prefix + p. independent of the unit tests. one of the options on the menu that appears is Test Fixture to Object Bench. When someone went inside the computer (Yes. I prefer not to use the word debug as it has somewhat humorous connotations. The story is that one of these switches was behaving erratically. what is the purpose of that prefix variable? Sometimes I ask questions without answering them. and places them on the Object Bench. Hence. The ability to read and understand code is crucial in your career as a programmer. prefix = ″\n″. http://en.uk/risks or via email. the switch was de-bugged. This creates all the objects you need to run your tests. Many times you will see code which is undocumented. the memory was switches which actually moved.ncl. We can run individual methods of these objects.

* @return -1.getIdentifier())). and another unit test. Can we avoid having the same code in two places? Of course we can. /** * numeric comparison. 1 if Person p1 is <. but it has its problems. and you should. in the Person class of courses. /** * produce an employee list. and its courses. we need a second Comparator. } }.getIdentifier(). Sometimes it is more appropriate to have a list of employees ordered by identifier (employee number) rather than by name. Producing a professor list in numeric order But let‘s go back to the problem of modelling a college. in the order specified * by the Comparator. 0. for example. even worse.The errors are not just small. Person p2) { return (p1. * @param theComparator The Comparator to use in sorting * the employees 154 . either. and now that error is in two places. Or. To facilitate this. or > Person p2 * based on the identifier */ public static final Comparator<Person> NUMERIC_ORDER = new Comparator<Person>() { public int compare(Person p1. compareTo(p2. Perhaps the largest and most expensive was the spaceship that crashed into the Martian surface due to confusion between metric and imperial measurements. You will probably consider copying and modifying alphaProfessorList to create numericProfessorList. its people. You may forget to make a change in the copy. =. or I wouldn‘t ask the question! Passing a Comparator to a method Did I hear you say ―Why can‘t we just have one professor list method and tell it which Comparator to use?‖ You can. another method in College. the code you copy may contain an error. You will probably consider doing the same for the unit test. is much simpler than the first one we created. That would be the easy way. This Comparator. since this time we are comparing only the identifier values.

needsReturn = true. } Don‘t forget import java. c.addProfessor(professor1). 155 . ordered. Once again we see that there are many ways to accomplish the same task. } Remember to use View. c.addProfessor(professor2).addAll(theProfessors). Have you found out that you can display the terminal window after putting something in it? The output will still be available. A unit test for the alphabetic Comparator could look like this. public void testAlphaProfessorList1() { College c = College. perhaps you can do so now. Show Terminal so there is a place on the screen to display the class list. System. result = result + p. Boolean needsReturn = false. for (Professor p: ordered) { if (needsReturn) result = result + „\n‟. c.addProfessor(professor4).println( s.out.Comparator. } return result.professorList(Person. The coding in the method above is slightly different from that in alphaProfessorList.util.ALPHABETIC_ORDER)).*/ public String professorList(Comparator<Person> theComparator) { // create the TreeSet Set<Professor> ordered = new TreeSet<Professor>(theComparator).getInstance().addProfessor(professor3).toString() + '\n'. If you didn‘t figure out the use of the variable prefix in the previous version. // traverse the Set // and compute a String String result = ″″. // create some professors (code not shown // here) // and remember them c.

* @param s Student object to be added * */ public void addStudent(Student s) { theStudents. We designed them that way. 156 .getIdentifier()). Thus we need the following statements. In the clone method we need s. If we have a Student object. There is no compelling reason for one over the other.add(s. over. We need to add a student‘s identifier to the collection.theStudents = new HashSet<String>(). In our implementation. we need this. and up. sections do not contain Student objects. private Set<String> theStudents. So we are able to remove the alphaProfessorList and numericProfessorList methods from College. Registering students in sections A section contains students. /** * add a Student object to the section.theStudents). We can use either a set or a list. we need to decide the type of the collection we will use. and to remove their unit tests from CollegeTest. this method works. In the constructor. How do we create the collection of students in a section? First. There it goes.The unit test for the numeric Comparator would be the same.theStudents. and it comes down … set. Sometimes we may have the identifier. so that we only have one instance of a Student object for each student (in the theStudents collection in College) and we gain access to that instance by providing the only instance of the College class with the student number. That allows us to have a second addStudent method.addAll(this. and over. } Sometimes we may have the Student object to be added to the collection in a Section object. they contain student identifiers. Up. That is the English description. Flip a coin. replacing ALPHABETIC_ORDER with NUMERIC_ORDER.

But now we need a different implementation since a HashSet is not sorted. but only when we need the data in sorted order. Recall that the Section collection contains student numbers. in alphabetical order by name? We find that we have a problem. A much better way to accomplish a similar task is to give everyone access to an iterator. /** * given a student number.getIdentifier())) { return s. /** * @return collection of Student objects. We have implemented a set as a HashSet because of its speed. return the student object. which provides one Student object at a time. we will transfer the data from the HashSet to the TreeSet. the same problem we found earlier. As we did before. Producing an alphabetic class list How do we combine all our knowledge of collections so that we can produce a list of students in a Section. * @param a student number */ public Student getStudent(String identifier) { for (Student s:theStudents) { if (identifier. Most of the time./** * add a Student object to the section. */ public Set<Student> getStudents() { return theStudents. } But this is not a good method since it gives everyone access to all the elements in the collection. Once we extract an element from that collection. we must retrieve the corresponding object from the College collection of students. This calls for a getStudent method within the College class. } Soon we will need to access all the students in the collection. 157 . we leave the set in its unsorted state. Make it so. * @param sn the student identifier to be added */ public void addStudent(String sn) { theStudents. creating a new set ordered as described by a Comparator.equals(s. Instead. Here‘s a method to do that.add(sn). we choose the TreeSet.

retrieve the Student objects // and arrange them in alphabetic order for (String sn:theStudents) { orderedStudents. // for all student identifiers in the // section. Then we create a new method. We visit each element of the collection of student numbers.add(c. // create the TreeSet Set<Student> orderedStudents = new TreeSet<Student>( Person. thus ordering them alphabetically. we simply need to visit the elements of the TreeSet one after the other and we will visit them in alphabetical order. We insert each into the TreeSet. we ask the college Singleton to give us the appropriate Student object. The for-each statement. import java. we add an import statement. 158 . Once we have visited all elements. For each.ALPHABETIC_ORDER).util. } // traverse the Set and compute a String String result = "".} } return null. } The statement that creates the TreeSet indicates what type of objects will be in the set and which comparator is used to compare two such objects. alphaClassList.getFullName().getIdentifier() + „\t‟ + st. revisited Note that we have again used the for-each statement. boolean needsReturn = false.TreeSet.getStudent(sn)).getInstance(). result = result + st. } To use a TreeSet requires two changes in the Section class. representing the students who are registered in this section. twice in fact. public String alphaClasslist() { College c = College. } return result. for (Student st:orderedStudents) { if (needsReturn) result = result + '\n'. First. to visit all the elements in a collection. needsReturn = true.

Create unit tests for both comparators. for (Student sn:theStudents) { orderedStudents. This Comparator is much simpler than the first one we created.The first time. Producing a class list in numeric order Sometimes it is more appropriate to have a class list of students in a section.add(c. * @return -1. compareTo(p2. needsReturn = true. Person p2) { return (p1. since we are comparing only the identifier values. 1 if Person p1 is <. As we saw earlier.getIdentifier + '\t' + st. =. 159 .getIdentifier().getStudent(sn)). and so that it accepts a Comparator as a parameter. } }. 0. } We could use an iterator to process all objects in the collection but this for statement provides a shorthand way of referring to individual elements in the collection. ordered by student number rather than by name.getFullName(). /** * numeric comparison. Modify alphaClassList so its name is simply classList. result = result + st. } Then we visit all the elements in the orderedStudents collection. we can provide a comparator as a parameter to a method. we visit the elements in the theStudents collection.getIdentifier())). or > Person p2 * based on the identifier */ public static final Comparator<Person> NUMERIC_ORDER = new Comparator<Person>() { public int compare(Person p1. for (String st:orderedStudents) { if (needsReturn) result = result + '\n'. String result = ″″.

160 . In particular. We will do that in the following chapter. we are able to see how to model a college in much more detail. The challenges of producing a schedule will introduce us to the complexities and fun of string manipulation. Make it so. and the end time.Students enrol in sections Now that we have created a Section object which contains a collection of students (that is. a collection of student identifiers). we can focus on the daily meetings of the class. we can model the association between Student and Section where a student registers in a section of a course. Summary Now that a section knows the semester in which it is taught. the start time. The other side of the association is that a Section knows which students are registered in it by maintaining a collection of student identifiers. the details of which include a room number. We can model that by having a Student object contain a collection of section identifiers.

we discussed modelling the sightings a birder makes. usually in one section of each. A student enrols in many courses. a Professor object needs a collection of the subject abbreviations and course numbers of previously-taught courses. 3. we discussed modelling playing cards. in a semester. In what order should the sightings be recorded? Why do you suggest that order? Note that a birder will sometimes wish to have a list in order by species and sometimes in order by date and time. Each Professor object should be able to produce a previouslyTaught report listing all these courses. Each Student object should be able to produce a currentEnrollment report listing all these sections. A professor teaches many sections in a semester. A professor who has been at the college for more than one semester has a history of the courses which he/she has taught. a Professor object needs a collection of the section identifiers of the sections he/she currently teaches. How do those ideas affect your earlier answer? 6. Model that. a Student object needs a collection of the section identifiers of the sections in which he/she is currently enrolled. model that. In what order should the playing cards be stored in a collection? 161 . In a previous chapter. That is. Each Professor object should be able to produce a currentTeachingLoad report listing all these sections. In what order should the transactions be stored? Why do you suggest that order? How would you implement that? 5. In a previous chapter. we discussed modelling a bank account. That is. Using the techniques from this chapter. 2.Exercises 1. Sometimes a birder will only want sightings for a particular time period. That is. How can that report show when the professor taught the sections? 4. In a previous chapter. Using the techniques from this chapter. with a collection of transactions. model that.

Explore the DecimalFormat class to see what other capabilities it contains.Why do you suggest that order? 7. 162 .

along with the location (room number) of the meeting. we will assume the room number of the meeting is simply a String. we mentioned that we wish to model when a Section is offered and we mentioned there are two aspects to ―when‖. We will use the constants from the Calendar class to represent the days of the week. To simplify this model a little. followed by a recess. Thus the values range from 0000 to 2359 and the corresponding instance variables will be integers. The section in which this book was first used originally met in a 120-minute block. each separated with a 10-minute recess. including how it differs from String Use and manipulate the contents of a StringBuffer Describe and illustrate the difference between aggregation and composition Introduction In the previous chapter. This is an example of a course meeting several times in one day. the corresponding instance variables will be integers. we will call that a meeting. part 3 Learning objectives By the end of this chapter you will be able to:     Produce reports from collections Describe the characteristics of the StringBuffer class. Thus. We will use a 24-hour clock to represent the start and end times. We must make sure we do not make that impossible. We will indicate the date and time of each meeting. Can a section meet twice on the same day? That would be unusual. 163 . A Section object will contain a collection of Meeting objects. The Meeting class Whenever a section occurs. We begin this chapter by modelling the days and times within the semester. and the days and times within the semester.Chapter 9 – Collections. We changed that to three 40-minute blocks. but it is possible. the semester (which we have modelled by providing start and end dates).

or slash) to isolate the hours. state. In each of those statements we declare a variable and give it a value at the same time. and a Section object should contain a collection of Meeting objects. To determine the remainder discarded in the integer division. the remainder when you divide 830 by 100 is 30. also a duration of 50 minutes. and behaviour. but you cannot do this in the second case. 1050 / 100 is 10. int startHours = startTime / 100. 830 % 100 is 30. it may be useful to have a method that computes the duration of a meeting in minutes. Behaviours And what are the behaviours of a Meeting object? Aside from the obvious getters and setters. int startMinutes = startTime % 100.Instance variables Since a section meets many times a week. you can subtract the start time from the end time and calculate the length immediately. use the modulus operator (represented by %). An object has identity. what are its instance variables and how do they receive their values? private int dayOfWeek. any remainder in the division is dropped and no rounding takes place. a duration of 50 minutes. we should create another class. The first statement uses division (division is represented by the /. private int startTime. But it may begin at 0830 and end at 0920. A meeting may begin at 1000 and end at 1050. 1020 / 100 is 10. How do you separate a number like 0830 into its hours (08) and its minutes (30)? Probably the easiest way is as follows. private int endTime. and 955 / 100 is 9. What is the state of a Meeting object? That is. How do you calculate the length of a meeting? Time arithmetic There are many ways to calculate the duration of a meeting. 164 . the result is an integer. this one called Meeting. but all require you to have both the minutes and hours of both the beginning and ending times available. and we create the name through a declaration statement. That is. as we have already seen many times. For example. so there is no problem there. Identity is the name of the object. In the first case. private String roomNumber. When you divide an integer by an integer. 830 / 100 is 8.

int endMinutes = endTime % 100. return (endHours . In both cases. the calculation computes (12 – 11) * 60 + (20 – 30). For example. due to sloppy input handling. when a meeting runs from 0830 to 0950. int endHours = endTime / 100. we can calculate when the meeting ends. In our case. Parentheses indicate that the calculations within the parentheses should be done before any other calculations. It may have a start time of 1200 and an end time of 1030.startMinutes). Similarly. but we can‘t do that right now. *) has a higher priority than addition. the remainder when you divide 1020 by 100 is 20. garbage out. some calculations must be done before others. To decide what is done with those results. If a meeting runs from 1130 to 1220. It involves the idea that some calculations have priority over others. Should a calculation use more than one multiplication operation. Note that these calculations assume there are no errors (intentional or otherwise) in the times provided. 165 . More-complicated calculations could use more than one addition operation. but only after the multiplication and division operations had been completed. we don‘t know how to throw exceptions. Remember that the modulus operator is used only when you are doing integer division. This is one of the more complicated arithmetic calculations we have seen. it is a simple matter to calculate its duration. or 1 * 60 + (– 10). So too would division and so too would a mix of multiplication and division operations. they would be evaluated from left to right.‖ For example. the remainder when you divide 955 by 100 is 55. the calculation computes (9 – 8) * 60 + (50 – 30) or 1 * 60 + 20. We will eventually modify the class to prevent bad data being provided. we will calculate an incorrect value for the duration of the meeting. There is an expression ―Garbage in. or 60 + 20. Once you have the hour and minute when the meeting begins and ends. you need to know that multiplication (indicated by an asterisk.startHours) * 60 + (endMinutes . Subtraction and addition have the same priority so are done left to right. 1050 % 100 is 50. there are two parenthesised calculations which are done (the two subtractions) and the results saved in temporary storage. Thus the first saved result is multiplied by 60 and the result of that calculation is added to the second saved result. in minutes. or 60 + (-10).1020 % 100 is 20. or 80 minutes. or 50 minutes. a meeting may have a start time of 3456 and an end time of 6578. they would be evaluated left to right as well. 955 % 100 is 55. the remainder when you divide 1050 by 100 is 50. That is.

if (o instanceof Meeting){ Meeting m = (Meeting) o.endTime == m. and two meetings of a section cannot occur at the same time. or if something * is different between the two Meetings */ public boolean equals(Object o) { boolean result = false. We have seen a Set (of student identifiers representing students in a section) and we have seen two implementations (HashSet and TreeSet. and room match * @return false if not both Meetings.getRoomNumber())) && (this. In particular.getEndTime()). we need to specify a Comparator<Meeting> which describes how to compare one Meeting object to another. Thus that is a suitable collection. you‘ll find there are other types of collections as well. though. you could argue they are the same if the day and time match.startTime == m. we will produce a schedule showing when each section of each course is offered. The individual meetings will be in order from Sunday through Saturday. But which implementation should we choose? Either implementation might work. Why? A Set does not allow duplicates. we can attach a collection of Meeting objects to a Section object. regardless of the room. They are the same when they take place in the same room on the same day at the same time.) When you check the online documentation. What type of collection should we use? We have seen a List (of section identifiers added to a Course object.roomNumber. Why is that the normal order. Many religious groups and calendars from Europe seem to have it right. That one is easy. with the week beginning on Monday and ending on Sunday. In fact.) /** * is one meeting equal to another? * @return true if day. For now. 166 . equals(m. But a TreeSet is ordered and we will often want to retrieve the Meeting objects in order.dayOfWeek == m. times.getDayOfWeek()) && (this.Section uses Meeting Now that we have a Meeting class. result = (this. for example) and the ArrayList implementation. when Saturday and Sunday form the weekend? An ―end‖ implies it is after something. (And we need an equals method for Meeting objects. Since we are going to use a TreeSet.getStartTime()) && (this. following the normal North American week. I think a TreeSet is the most appropriate implementation to choose.

else { // both on same day of the week int s1 = m1. What does it mean that one meeting is less than another? Here is my understanding. we use == with the day of week and the times.} return result. Just because there are many ways to accomplish the same task. in this case a String. when the day. // compare day of week if (d1 < d2) // m1 is earlier in the week result = -1.getDayOfWeek(). then the meeting which ends first is less.getStartTime(). On to the comparator. using the ―and‖ operation (&&).  If both are on the same day of the week and have the same start time. I suppose you could use the hashcode method to determine the hashcodes for each String and then compare the hashcodes using ==. If you don‘t like using both equals and ==. start time. } Note that we need to use the equals method with the roomNumber. since they are primitive datatypes. they are not all sensible. start time. and then use its equals method. =. 0. Based on that understanding. We combine four boolean values. here is my Comparator<Meeting>. But that makes code that is overly complicated and hard to read. that is.  If both are on the same day of the week. int d2 = m2. 1 if Meeting m1 is <. Meeting m2) { int result = 0. else if (d1 > d2) // m2 is later in the week result = +1. but that would be silly.getDayOfWeek(). room number. and end time */ public static final Comparator<Meeting> TIME_ORDER = new Comparator<Meeting>() { public int compare(Meeting m1.  When the first is on an earlier day of the week than the second. /** * which meeting is less? * @return -1. you can convert an int to an Integer. and end time are all the same. 167 . the first is less. since it is an Object. or > Meeting m2 * based on the day of week. int d1 = m1. The only time this combination will evaluate to true is when all four boolean values are true. the one with the earlier start time is less.

the question mark (?). 168 . int e2 = m2. else result = 0. For example. I prefer not to use it.int s2 = m2. I feel that clarity is reduced by the use of that operator. If you really want to use the conditional operator. The basic structure of an if statement is as follows.getStartTime(). This comparator is longer than the others we have seen. if (e1 < e2) result = -1. although you may wish to use them to increase clarity. The if statement. Java still includes one. however. Many languages included special features to allow this. // end TIME_ORDER }. and would need to be enclosed in braces. In the old days. same start time int e1 = m1. Thus we cannot use the compareTo method we have used with Objects. revisited This Comparator contains several if statements. if (condition) Statement to do when the condition is true else Statement to do when the condition is false The ―statement to do‖ needs to be enclosed in braces when it is a compound statement. else if (s1 > s2) result = +1. }. We must use the less than (<) and greater than (>) operators instead. else { // same day. two assignment statements make a compound statement. programmers were considered better when they could write shorter methods to accomplish a task. so an if within an if does not need braces.getEndTime(). } // compare end times } // compare start time return result. nested within each other. containing several other statements. if (s1 < s2) result = -1.getEndTime(). explore its use on your own. else if (e1 > e2) result = +1. But an if statement is not a compound statement. The reason is that all the values we are examining are primitive datatypes. the use of the conditional operator.

The third assignment statement will be executed regardless of which path your program takes through the if statement. private Set<Meeting> theMeetings. so none of the if clauses in this example need braces because they all contain a simple statement. the rules of the Java language are well-defined. Indentation does not do that and can imply associations which do not exist. else grade = “F”. this. so you eliminate this ―does it or does it not‖ questioning. if (percentage > 90) grade = “A”. without knowing the actual times the section will meet. Despite that. Consider the following badly-indented statements. or is another if statement. But sections are often planned and created. Perhaps it is better to always use braces. message = “with distinction”. I have not modified my constructor other than to create an empty collection of meetings. Thus. else grade = “F”.) Some do need braces because the ―statement to do‖ combines several assignment statements and another if. Consider the following statements. Creating the collection of Meeting objects How does a Section create its TreeSet of Meeting objects? You might be inclined to add the Meeting objects to the constructor. Note that the braces help tell which else is associated with which if. This will not compile since there are two statements following the if which are not enclosed in braces.TIME_ORDER). if (percentage > 90) grade = “A”. 169 . message = “with distinction”. Note that the Checkstyle extension we are using expects braces even if there is a single statement in the body of the if or the else. setting the variable result to an appropriate value.Thus some of the else clauses in the Comparator do not need braces (because the ―statement to do‖ is a simple statement.theMeetings = new TreeSet<Meeting>(Meeting.

in the same room. One solution is to simply remove the old meeting and replace it with a new. /** * add a meeting time. I have created a new method addMeeting. Meeting m2) { theMeetings. but it is actually easy. one for each day. theMeetings.contains(m)) theMeetings. } How do you change the time of a meeting? Changing the time of a meeting may seem difficult. * @param m1 the meeting to be changed * @param m2 the replacement meeting */ public void changeMeeting(Meeting m1. Assume a section meets on Monday. 170 . */ public void addMeeting(Meeting m) { theMeetings. Wednesday. This is the format used at Okanagan College.remove(m). from 1030 to 1120 each day. perhaps your college or university uses a different format. Section uses Meeting – displaying the times Now we proceed to the challenging part. We have three separate Meeting objects.add(m). } How do you remove a meeting from the collection? /** * remove a Meeting object from the section. */ public void removeMeeting(Meeting m) { if (theMeetings. } It could be even easier by using the setters of the Meeting class. * @param m the meeting to be removed.add(m2). and Friday. assuming all three meetings are in the same room.To add a meeting to the collection. /** * change the time of a meeting. We wish to combine the information from these objects into a single String that reads M W F 1030 1120 XXX where XXX is the room number. Explore that possibility. how do you produce a neat summary of the meeting times? We‘ll do that in a method named meetingsList.remove(m1).

and the first two after F) and whitespace to make the output clearer (the third one after F. I once almost had a class that met three times a week in a different room each day. and it permeates computing. Why? Remember that the smallest non-negative integer is zero. Often that forces us into using a collection. one after W. since we are using the TreeSet implementation and our comparator. we can use an array. At the end of the method. The schedule will be two lines. That is. when classes meet at the same time on different days. it made sense to start numbering at zero. This time. Should a section meet five times a week. which will expand as needed. the first one has index zero. There may be two or more separate lines. the one after W. to some degree. but at my college. 171 . meeting at a different time (or in a different room). and one after 1120. and two meetings on the same day will be in order by starting time. we can determine an upper bound providing we assume no section meets more than five times a week. when you have an array containing five elements. We will be writing a method which will create all the lines of output. Back in the old days. we might need five lines of output. though. in which individual elements are referred to by means of an index. When the section meets at different times on the three days. and the one after 1120.) These spaces represent missing information (the one after M. Sunday (represented by the number zero) through Saturday (represented by the number six). Arrays So what type of collection should we use to store five Strings? The collections we have seen all can vary in size. the second has index one. and the fifth has index four.Note the spaces (one after M. Recently I have had classes that meet three times a week. There is a tried-andtrue collection type we can use. An array is a collection of data items. they usually meet in the same rooms. we can combine the (maximum) five Strings into one and return it. one after 1030. three after F. Using any of them is. We don‘t know in advance how many lines of output (Strings) we will need. We have seen the idea of an array mentioned when we first saw the ArrayList class. But not always. You should be thinking that a first step is to be able to extract individual Meeting objects from the collection. This is the same zero-based numbering we found in the Calendar class. once in one room and twice in a different room. or in different rooms. Note that these objects will be returned according to the days of the week. a matter of overkill. the one after 1030.) I don‘t know about your school. since we know that the size of the collection is small. then we wish to produce separate lines of output. depending on how many different times or rooms are used. when memory really mattered and machines were slow.

That means that once it is given a value. but can be modified. didn‘t we say in an earlier chapter that a String is immutable? Yes.format(seminarHours) result = result + ')'. result = result + ″ (″ result = result + myFormatter.format(lectureHours) result = result + '. You may be wondering a little about right now.So perhaps we should create an array of String objects. it can‘t be given a new value. Haven‘t we created a string by concatenating a number of values together? Haven‘t we done that in a series of statements? Consider. How about a StringBuffer? StringBuffer The online documentation states that a StringBuffer is a ―…mutable sequence of characters. but nothing is referring to it. String result. } Every time we add one string to the end of another we appear to be changing the value of result. or changing existing ones) when we read a different meeting detail. True.#″).format(laboratoryHours) result = result + '. result = departmentAbbreviation + ″ ″ + courseNumber. double totalHours. At any point in time it contains some particular sequence of characters. When we perform those statements in the method above. But wait. 172 . We then have result refer to that new variable. While summarizing meeting times. and return it to the pool of available memory. for example a slightly-modified version of the toString method in the Course class. Note that all the changes we made involved adding characters to the end of an existing value.' + myFormatter. but we do by being wasteful of memory. totalHours = lectureHours + laboratoryHours + seminarHours. we use the value of result to create another variable. result = result + '\n' + title + '\n' + description. I‘m thinking of a process in which we construct a String as we read meeting details.format(hours). We need something like a String but which one allows us to modify it. a process called ―garbage collection‖ will be used to identify the memory which is not referred to. A StringBuffer is like a String. return result.‖ That‘s what we want. The original value is left in memory. result = result + ″-″ + credits + ″-″ result = result + myFormatter. we did. But a String won‘t allow this insertion.' + myFormatter. but the length and content of the sequence can be changed through certain method calls. At some later time. perhaps modifying the String (by inserting new characters. public String toString() { DecimalFormat myFormatter = new DecimalFormat(″#.

other values we have considered (the subject abbreviation and the course number) may be different for other colleges too. row++) temp[row] = new StringBuffer(″ ″). to 5%! And now (summer 2010) the two rates are being combined into one.In fact. Thus each StringBuffer needs to contain 18 characters (seven plus one plus four plus one plus four plus one) plus the length of a room number (in the case of my college.) It is better to avoid such use. when you read the documentation on StringBuffer you‘ll find that the most recent versions of Java have included a new class. which might be even better. Then we need to initialize each element of the array to a string of 22 blanks. for a while we had two different sales taxes. a total of 22 characters. What if you ever have to change the number? Will you remember that every five is the same or do some mean something else? In Canada. Adjusting to different colleges But look.06. 173 . // assumption . a space (to make the result more readable). The length of a room number may vary for a different college. a space (to make the result more readable). int row = 0. four characters). and use it instead.07 and see whether it was the provincial rate (which didn‘t change) or the federal rate (which did.no more than five meetings a week StringBuffer temp[] = new StringBuffer[5]. Let‘s continue with the creation of meetingsList. I am thinking we should create five StringBuffers. a space (to make the result more readable). the four-digit end time. as shown in the example above. classes may occur on Saturday and Sunday). row < 5. each of which will contain seven characters representing the days of the week (yes. We‘ll use StringBuffers here and leave StringBuilders as an exercise. for (row = 0.) And then the federal rate changed again. the four digit start time. and create a constant. There are 22 spaces (blanks) between the quotation marks in the last statement. Now we need an array which we can use to access the individual StringBuffers. and the room number for the meeting. StringBuilder.07. For that matter. Then the federal rate dropped to 0. we have used the number five twice already (and the word five once.07. and the federal (national) rate was also 0. Imagine how many programmers had to look at each use of 0. The provincial rate where I live was 0.

private final int MEETING_START_TIME_LENGTH = 4. In an exercise at the end of this chapter. which we know they are since they are declared to be final. int maxMeetings = c. // assumption . I would suggest we place these limits in the College class. where? Since they are college-wide limits. Here are the additions to the College class. // college-wide constants private final int MAX_MEETINGS_PER_WEEK = 5. Now we can retrieve these constants wherever appropriate.no more than maxMeetings meetings a week College c = College. the length of a subject abbreviation. and the length of a room number. Since long sequences of capital (uppercase) letters are hard to read. } public int getMeetingStartTimeLength() { return MEETING_START_TIME_LENGTH.getInstance().While we are thinking about avoiding repetition of numbers. Since we have only one instance of the College class. we will explore how to use resource bundles to customise these values for different colleges. As constants. } public int getDeptAbbreviationLength() { return DEPT_ABBREVIATION_LENGTH. the length of a course number. public int getMaxMeetingsPerWeek() { return MAX_MEETINGS_PER_WEEK. private final int DEPT_ABBREVIATION_LENGTH = 4. spaces within the names are replaced with underscore characters. Can we define those lengths as constants? If so.getMaxMeetingsPerWeek(). their names are capitalised. let‘s deal with the other constants we have. } public int getMeetingEndTimeLength() { return MEETING_END_TIME_LENGTH. } public int getRoomNumberLength() { return ROOM_NUMBER_LENGTH. we can use getters as we have with all our classes. with comments omitted to save trees. We mentioned the length of the start and end time of a meeting. private final int MEETING_END_TIME_LENGTH = 4. private final int ROOM_NUMBER_LENGTH = 4. 174 . } Of course the instance variables are private.

Another for loop What‘s this for loop we have been using? It looks something like the for-each loops we‘ve seen when processing collections but it‘s different. } } The array is created properly. The logic here is:  Initialize the counter (row in the first loop.  Check that the continuation condition is met (row < maxMeetings in the first loop. 22 spaces. j++) { temp[row]. for (Meeting mt: theMeetings) { // do something } 175 . for (int row = 0.StringBuffer temp[] = new StringBuffer[maxMeetings]. 2. // each element of the array is empty // create an array of StringBuffers of the correct length. Then increase the counter as shown (increment by one). Processing all the meetings Now we need a way to visit all the Meeting objects and place them into the appropriate StringBuffer. j < lengthNeeded in the second). for now and for the future.  Whenever the continuation condition is met. // containing blanks. for the current college standards and for future standards.insert(j. the loop is finished.  When the continuation condition is not met. some of the blanks will be // replaced later int lengthNeeded = 7 + 1 + c. 4 and each corresponding element in the array is set to. 3. j in the second) to the value specified after the first equals sign. j < lengthNeeded. Thus row takes on the values of 0. in our case. row++) { temp[row] = new StringBuffer(lengthNeeded). for (int j = 0. 1. this for loop is controlled by a counter. A for-each loop is good in this situation. Rather than looping over all the elements in a collection.getMeetingEndTimeLength() + 1 + c.getMeetingStartTimeLength() + 1 + c. and loop back to the check.getRoomNumberLength(). row < maxMeetings. usually zero. perform the statements in the body of the loop. " ").

Right. 11. mt. 16. In these cases.getStartTime()). we need to modify the matching StringBuffer to indicate a meeting on a different day. and the index of the last one to be replaced. we need to store the day of the week. StringBuffers are objects.replace(8. and the room number for the meeting).getRoomNumber()). When there is no match to any of the existing StringBuffers. you can replace the comment // do something with the following. the four-digit start time. you begin to review the datatypes you know to find one that takes on only two values. we are replacing four blanks in the StringBuffer with the values returned by the Meeting getters. we need to place its details into the first StringBuffer. For each subsequent Meeting object. the four-digit end time. } else // do something different } From the description of the output we‘d like to create (seven characters for the days of the week. 176 . when there is a match of room and times. a space. temp[0]. What is the something we need to do? For the first Meeting object.replace(18. the start and end times. temp[0].Manipulating StringBuffers Placing data in StringBuffers The last snippet of code said we need to ―do something‖ as we process each meeting. we need to compare its details to the details already in the array of StringBuffers. We indicate which characters to replace by giving the index of the first one to be replaced. so the syntax we need is the name of the object. boolean variables! boolean first = true.replace(13. temp[0]. we need to begin building a new StringBuffer in the appropriate format. followed by the parameters of that method. a space. mt. 21.getEndTime()). mt. followed by a period and the name of the method we want to invoke. a space. and the room number. How do we know we are dealing with the first Meeting object? Alternatively. how do we know we are not dealing with the first Meeting object? In answering those two questions. for (Meeting mt: theMeetings) { if (first) { // do something first = false.

replace(p3a. we should use these statements. p3b. 16. mt. but they don‘t give the correct result. We should calculate those numbers so they reflect differences between colleges. uses it.1. The number eight is calculated as one more than the number of days in the week. Thus when we place the times and room number into the array element. myFormatter.But the numbers 11. temp[0].format(mt. temp[0]. 177 . myFormatter.format(mt.getRoomNumber()).replace(p2a. p2b.replace(p1a. 18. p1b. // p1a is the location of the first digit of start time // p1b is the location of the last digit of start time // p2a ditto for end time // p2b ditto for end time // p3a ditto for room number // p3b ditto for room number int p1a = 8.text.getMeetingEndTimeLength() . mt. and the length of the room number. 13. int p2b = p2a + c. int p3b = p3a + c. Thus the first digit of the start time will be position eight. (If we had stored the times as Strings we would not have this problem but would probably have others.getEndTime()).getStartTime())). Remember that the first position in the StringBuffer is position zero. Position seven will be occupied by a space.) We will use DecimalFormat (from the java. but early morning times will be only three. Thus the abbreviations for the days of the week will be in positions zero through six.DecimalFormat library) to ensure the times are all four digits in length. and 21 are calculated on the basis of the lengths of the start and end times of a meeting. roomNumber is already a four-character string. p1b. creates the DecimalFormat object and temp[0]. Recall that getStartTime and getEndTime both return ints.getRoomNumberLength() . int p1b = p1a + c.1. int p3a = p2b + 2.getStartTime()). p2b. temp[0].1 .getMeetingStartTimeLength() . The lines above will work. DecimalFormat myFormatter = new DecimalFormat(″0000″). temp[0]. int p2a = p1b + 2. mt. We are expecting the times to be four digits. In particular.getEndTime())). we would need to ensure that all times contained the same number of characters.replace(p2a.replace(p1a.

htm says ―The days of the week (i giorni della settimana) are not capitalized in Italian.setCharAt(mt. so we need a way of converting this to the appropriate character representation of the day of the week. Since we have mentioned resource bundles and customization. the website http://italian. The String class provides a method called charAt. setCharAt works with individual chars.getDayOfWeek(). dayAbbreviations. and how would they be provided? For example. You provide the position within a String and charAt provides the character at that position. replace works with Strings.getDayOfWeek())).getDayOfWeek())).Converting numbers to day of the week What about the day of the week? mt. Should that implementation change. will extract the appropriate day letter. we may wish to consider what would happen if the college we are modelling were in an area where English is not the spoken language. This is a situation we would normally avoid. We have used R to represent Thursday (eliminating confusion with the T representing Tuesday) and A to represent Saturday (eliminating confusion with the S representing Sunday). What would be the abbreviations for the days.getDayOfTheWeek returns an integer.charAt(mt. lunedì—Monday martedì—Tuesday mercoledì—Wednesday giovedì—Thursday venerdì—Friday 178 .com/library/fare/blfare109a. Suppose we have String dayAbbreviations = ″SMTWRFA″. and temp[0]. where one piece of code is very closely involved with another piece of code. Then dayAbbreviations.charAt(mt. This is an example of coupling. in this case by knowing and using the internal details of that other piece of code. The week begins with Monday. will place it in the appropriate element of the first row in the array. Note that this relies very heavily on the idea that the Calendar class uses the numbers zero through six to represent the days of the week.about. our program will cease working.

for (int row = 0. Declare a variable before the loop begins int rowsGenerated = 0. /** * produce a list of meeting times */ public String meetingsList() { College c = College.no more than maxMeetings meetings // per week StringBuffer temp[] = new StringBuffer[maxMeetings].getMeetingStartTimeLength() + 1 + c. row++){ 179 . Note that rowsGenerated is also the number of the next row which we might generate. we are developing code snippets that we will combine to create a method which will scan through all generated rows. row < maxMeetings. We should remember that. int maxMeetings = c.getMeetingEndTimeLength() + 1 + c.sabato—Saturday domenica—Sunday‖ What are appropriate abbreviations for Tuesday and Wednesday? Processing second and subsequent meetings What happens as we process subsequent meetings? Rather than developing a mammoth method.getMaxMeetingsPerWeek(). and give it a value after the first row has been generated. rowsGenerated = 1.getRoomNumberLength(). and room) to update. A lot of code Now we have an idea of what we need to do to deal with all the Meeting objects. we have one so far. Take a deep breath as there is a lot of code in the following method. // assumption .getInstance(). // containing blanks // some of the blanks will be replaced later int lengthNeeded = 7 + 1 + c. then it needs to create another row. This is because the array indexes start at zero. seeking ones (with the same start and end times. How many rows have we generated? Well. Should it not find one. // create an array of Strings of the correct length.

format(mt. and setCharAt for // a single char temp[0]. rt). // ensure times are four-digits DecimalFormat myFormatter = new DecimalFormat("0000").getMeetingStartTimeLength() .replace(p1a. // number of rows of output we generate int rowsGenerated = 0. // examine all Meeting objects for (Meeting mt: theMeetings) { // extract fields necessary for comparison // done mainly for efficiency. 180 . int p2a = p1b + 2. et).getRoomNumberLength() .format(mt. int dt1 = mt. j++) { temp[row]. String rt = new String(mt. dt).getMeetingEndTimeLength() . // days in the week plus 1 int p1b = p1a + c.1. // the first Meeting object is a special case if (first) { // simply place the Meeting details in the // appropriate positions of the first element // of temp.getRoomNumber()). // and remember that we are no longer // processing the first Meeting object first = false. temp[0].getStartTime()).1.getEndTime()). String et = myFormatter. p3b.getDayOfWeek().setCharAt(dt1. temp[0]. st). p2b. // remember that we have generated a row rowsGenerated = 1. int p3b = p3a + c.charAt(dt1). temp[0]. // abbreviations for days of the week String dayAbbreviations = "SMTWRFA". j < lengthNeeded. Note that we use the replace // method for Strings. char dt = dayAbbreviations.replace(p3a.insert(j. p1b. for (int j = 0.1 . " "). so we don‟t need // to extract the same field several times String st = myFormatter. int p2b = p2a + c.temp[row] = new StringBuffer(lengthNeeded). // p1a is the location of the first digit of start time // p1b is the location of the last digit of start time // p2a ditto for end time // p2b ditto for end time // p3a ditto for room number // p3b ditto for romm number int p1a = 8. int p3a = p2b + 2. } } // remember if we are processing first Meeting boolean first = true.replace(p2a.

p1b + 1). we need to create // a new row of the output. i < rowsGenerated. dt). boolean needsReturn = false. } // end match found } // end for // if we didn't find a match.replace(p2a. 181 . rt).substring(p1a. temp[rowsGenerated]. } // added new row } // end except the first }// end for all Meetings // and finallly combine all the generated rows into one // large string String result = "". boolean matchEnd = temp[i].equals(st). boolean matchRoom = temp[i]. p3b. // and exit the for loop early break. dt). temp[rowsGenerated]. rowsGenerated++.substring(p3a. st).setCharAt(dt1. i++){ // check things that need to match // IMPORTANT NOTE: // Substring has two parameters. // if everything matches. p3b + 1). update the // matching room to show another day of // the week if (matchStart && matchEnd && matchRoom) { // update the matching row temp[i]. The second is ONE // MORE than the end position you wish // to consider.substring(p2a. boolean matchStart = temp[i].} // end first else { // process all Meeting objects except the first // we‟ll be searching through the rows we // have generated and need to know if we // find a match boolean found = false.replace(p3a.replace(p1a. temp[rowsGenerated]. The // first is the start of the substring // you are looking for.equals(et). p2b + 1). p2b. // found will still be false if we didn‟t find // a match if (!found) { temp[rowsGenerated].setCharAt(dt1.equals(rt). // scan all existing generated rows for (int i = 0. et). // remember we had a match found = true. p1b.

Yes. I feel there is no need to decompose it into shorter methods. I would argue that this method is cohesive. The Checkstyle extension says it is too long. there is no point in continuing searching once you have found what you sought. the substring method for StringBuffers. } This is the longest method we have examined so far. If the name requires the word ―and‖ or the word ―or‖. Others suggest that a method should be cohesive. Programming Style Let‘s step back a minute and look at the style in which this method has been written. providing they are meaningful. An example of a useless comment is i = 3. then the method is probably not cohesive. Does it contain too many statements? Some people will suggest that a method should fit on a page. (See the discussion on composition and aggregation later in this chapter. It‘s a good idea to leave a note behind explaining subtleties in your code for those who follow afterwards. since it summarises a collection of Meeting objects into a String.) Since the method is cohesive. Note the comment in the code about substring. It uses a new method. there are several subtasks involved. some would say it is too long. this one takes several printed pages. A method is cohesive when it carries out one task. As in life. Thus cohesion is at least partly in the eye of the beholder.for (int row = 0. result = result + temp[row]. We have also used the break statement as a tool to exit a loop before it has completed its normal processing. Are there too many comments? Some would argue yes.length() > 0) { if (needsReturn) result = result + '\n'. } } return result. // assign the value of 3 to i 182 . row < rowsGenerated. This is often done while searching for something. the subtasks probably would not exist independently of the main task. We'll address that concern in a moment. or on a screen. This method allows us to access a portion of a StringBuffer. To check that a method is cohesive give it a name that describes what the method does. row++) { if (temp[row]. needsReturn = true. but I feel it is generally impossible to have too many comments. but they are all essential to the main task.

Other simple statements. I prefer a just-in-time style where I declare variables when I need them. which will return a String showing all the sections (but not the students in the section) in a course. That‘s what we‘ve done here. st. room. L02. Test it and examine the value it returns. =. dt and dt1 are both related to dates. Make it so. start. for example found = true. Did listSections list the sections in the expected order? What is the ―expected order‖? At my college. then the comment should say that. S02. Some would argue that all declarations should be at the beginning of the method. listSections.When you are using i to represent the month of March. 1 if Section s1 is <. but for longer methods. * @param s1 The first section * @param s2 The second section * @return -1. However. when it is a short method. /** * section number comparison. Sometimes I agree. should be commented as it is perhaps unclear what the effect of the statement is. Course contains Section Now we almost have a fully-functioning Section class. dt1. Fortunately sectionNumber is a String and Strings will sort into that order naturally. How do you know that addSection works? Create a method. and day of the week. dt) and could be better. And we can create a unit test to add some Sections. rt. or > Section s2 * based on the sectionNumber */ 183 . and 003. we use the same name but follow it with a digit. my justification is that the names are used only within this method (and within a small portion of this method) and they actually make sense. 002. We can go back and resume adding Section objects to a Course object. When tests are testing different aspects of the same thing. we need a Comparator<Section> to do the work for us. as we saw in the discussion on uppercase and lowercase letters. but it follows the pattern we have established in unit tests. Then lab sections are numbered L01. and should come first. the two-letters names are temporary (hence the ―t‖) values for end. Notice that declaration statements are scattered throughout the method. 0. lecture sections are numbered 001. However. dt1 does not quite follow that pattern. followed by seminar sections which are numbered S01. Are the variable names meaningful? Guilty! Some of the names are very short (et.

some more than once. plus the mark earned. How do we represent the courses a student took in the past? This presents an interesting problem.getSectionNumber(). The reverse association between Section (the whole) and Student (the part) describing the students enrolled in a section is also an aggregation. 184 . We will explore this Mark class a little later. some once.public static final Comparator<Section> SECTION_NUMBER_ORDER = new Comparator<Section>() { public int compare(Section s1. As an aside. Section s2) { return s1. This is a type of association between a whole (the Course) and its parts (the Section) where the part cannot exist independently of the whole. organized by semesters. the section exists whether or not students are registered in it. That transcript will list all the courses a student has taken. A collection of marks represents the courses taken in the past. the association between Student and Section describing the sections in which a student is enrolled is an aggregation. Consider the transcript that will be produced for a student. We also need to remember the mark the student earned in the course. at the end of a semester. A collection of courses represents the courses being taken in the current semester. This is a type of association between a whole (the Student) and a part (the Section) where the part can exist independently of the whole. Mark. note that it doesn‘t make sense to have a Section object without having an associated Course object. Thus the association between Course and Section is an example of composition. } }. On the other hand. One possible (poor) way to show this is to place a collection of Course objects in the Student class. at the end of the student‘s studies at the college. You would certainly need a different comparator if your college uses a different notation for the sections of a course. compareTo(s2. What happens when the name of a course changes after a student completes it? The old name should appear on the student‘s transcript. and Student contains Mark A student takes many courses at one time.getSectionNumber()). it appears a good solution is to create a Mark object. and the student‘s performance in them. or at some other time. which contains the information on the course as it was taken. the student exists even though he or she may not be registered in a section. Thus.

it started). we will be able to use TreeSets again. the course taken (subject abbreviation. both integers.  Use BlueJ to create the skeleton code for a new class. course name. The January semester comes before September.). course number. Credits will appear on the transcript and will be necessary to calculate the overall grade point average. but it does show what you can do with a little time and care. Then a Student object can contain a collection of Mark objects. courseNumber. This second collection could be summarised to represent the courses the professor has taught at any time in the past. Implementing this is left as an exercise for the reader. Follow our usual practice when creating a class. we expect to need a Comparator (don‘t forget the import statement!) and an equals method. and the mark earned. Professor contains Section As a Section object contains a collection of student identifiers. so a Professor object contains a collection of section identifiers. 185 . semesterYear. representing the Sections the professor has taught in the past. and credits. and semesterMonth all match.  Implement unit tests for the getters and setters. The coding was long and complicated.  Implement a constructor and a toString method. This represents the professor‘s teaching assignment during the current academic year. A Professor object could also contain a second collection of section identifiers. Summary That was quite a chapter. and may include courses in two or three semesters. The next chapter continues processing collections. The Comparator is based on the course and semester in which the mark was earned.  Implement the getters and setters Since we need a collection of Mark objects.Thus instances of the Mark class must contain the semester (perhaps the year and month. this time called Mark. the transcript shows semesters chronologically (oldest to most recent.). Implementing this is left as an exercise for the reader. The courses in a semester are listed alphabetically by subjectAbbreviation and courseNumber. What does it mean to say that two Mark objects are equal? We can define equality to mean the subjectAbbreviation. Since there is an ordering by date to these sections. regardless of when the student started his/her studies.

continue to chapter 11 and then chapter 12. and the professor has data which must persist over time (the sections and courses taught in the past). how do we save data so that it will be there when we run our program again? Persistence is the topic of chapter 12. That is. perhaps we should consider how to implement persistence.If you prefer to skip chapter 10. Now that the student has data which must persist over time (the marks he/she has earned in the past). 186 .

Implement the Student contains Mark association. we discussed modelling a bank account. 6. 4. Explore alternative ways of changing the time of a meeting. Create a method which will allow you to display all the transactions for an account which occur between two dates which you specify. The Java documentation tells us that ―Resource bundles contain locale-specific objects. where you specify the value for n. Create a method which will allow you to display all the sightings a birder has made between two dates which you specify. resource bundles can also be used for other customizations.‖ While used for internationalization. In this way. your program can load it from the resource bundle that is appropriate for the current user's locale. a String for example. 2. of the locale-specific information in resource bundles. When your program needs a locale-specific resource. Explore the use of the modulus operator when either one or both of its arguments are negative. In a previous chapter. Implement alphaClassList using an iterator. 7. 10. 3. if not all. Implement the Professor contains Section association. Implement the Mark class. you can write program code that is largely independent of the user's locale isolating most. How would these differences affect the code shown in this chapter? In a previous chapter. instead of a for-each statement. Use this method to create another method which will display the transactions within the last n days. 8. Explore the Java documentation to determine the differences between StringBuffer and StringBuilder. This chapter referred to different lengths for room numbers and course abbreviations. 9. Explore the use of the ? operator.Exercises 1. we discussed modelling the sightings a birder makes. 187 . Explore the ResourceBundle class and see how you could use a resource bundle to allow for these two customizations. Use this method to create another method which will allow you to list the sightings in the current year. 5.

188 .

We can calculate how many credits a student has earned in total by summing data in all Mark objects (eliminating duplicates) but we don‘t yet know the total by semester. Now. involving Mark objects.Collections. The first is the semester average. How do you calculate the average mark? When to calculate an average We have two types of average. the graduating average actually involves only the last 60 credits completed in a program. a record of a student‘s progress in a semester. I‘d like to return to another collection. In one case we have done more. The second is the graduating average. Usually. regardless of the marks earned. At Okanagan College. We processed all the meeting objects associated with a section and merged them into something suitable for a timetable entry. taking the higher mark in case a student repeated a course. Grade Average Recall that each course has a credit value associated with it. part 4 Learning objectives By the end of this chapter you will be able to   Use many of the String methods Summarize collections using a variety of techniques Introduction We have seen many collections so far. The graduating average involves all courses taken towards graduation. we have added elements to them. we will be calculating an average mark.Chapter 10 . When do we want to know the number of credits completed in a semester? The obvious time is when we are producing a transcript. and then converted them to a String for display. This has interesting issues in a program which consists of more than 60 189 . Let‘s see how to calculate those numbers. the average of all the courses taken in a semester. and eliminating failures. At the same time.

The transcript method . divide the numerator (433) by the denominator (six) and get a result of 72.credits and creates interesting programming problems as well. To do this. worth three credits. as are the credits. The result of the division is the grade average. worth two credits. the student earns a mark of 65%. /** * create a transcript. Add 352 and 81 and remember the result (433). calculate 2 * 65 and remember the result (130). worth one credit. the student earns a mark of 74%. Add five and one and remember the result (six). But the division below is not done as an integer division. add two and three and remember the result (five). For example. For the average. create a weighted sum of the percentages (the percentage earned in a course is multiplied by the number of credits the course is assigned) and divide the weighted sum by the sum of the credits. Calculate 3 * 74 and remember the result (222). Let‘s modify it to serve our needs.original version Recall that we have a very simple transcript method in the Student class. You‘ll be glad to know that we will not be pursuing this. the marks we submit are integers. In the first course. For the denominator. you must first evaluate the numerator. then the denominator.17. In the second course. You were asked to complete it on your own. the student earns a mark of 81%. The weighted average is calculated as 2 ∗ 65 + 3 ∗ 74 + 1 ∗ 81 2+3+1 To evaluate this expression. Add together 130 and 222 and remember the result (352). Calculate 1 * 81 and remember the result (81). assume that a student takes three courses at one time. Weighted average In either case. The priority of operations in a programming language is the same as the priorities in mathematics. * @return String representation of Marks */ 190 . In the third course. and then divide the numerator by the denominator. except in the exercises at the end of the chapter. we calculate a weighted average. At Okanagan College. This is what I have. For the numerator. This is not an integer division. so the result has decimal places.

we have a new semester. if ((currentYear != previousYear) || ((currentYear == previousYear) && (currentMonth != previousMonth))) { // semester has changed 191 . and the objects within that collection are stored in order by semester.public String transcript() { String result ="". int previousYear = 0. we will calculate an average of all the courses taken (which may be a graduating average) and we will calculate the semester average for each semester. int currentYear. the objects are stored by subject abbreviation and course number. To determine when we have changed semesters. } return result. currentMonth = m.) Transcript – a skeleton for changes Thus.getSemesterMonth(). we have the first modifications to the transcript method. If the years are the same. for (Mark m: theMarks) { curentYear = m. Should they be different. In this case. int currentMonth. for (Mark m: theMarks) { result = result + m. we assume the previous year is 0 (or some other impossible value) and the previous month is also 0 (or some other impossible value.getSemesterYear().toString() + '\n'. We need to be able to tell whenever a semester has changed. Within a semester. Whenever we produce a transcript. public String transcript() { String result ="". But what of the first Mark object? There is no previous Mark object. Should they be different. int previousMonth = ″″. we compare the (starting) month of the current Mark object to the (starting) month of the previous Mark object. we can calculate the semester average and reset various semester totals back to zero. we have a new semester. When a semester changes. we simply compare the value of the year in the current Mark object to the value of the year in the previous Mark object. } Knowing when a semester changes Recall that the collection of Mark objects is stored in a TreeSet.

semesterDenominator = 0. ―When the year has changed or the semester has changed‖ becomes ―If the years are not the same or the years are the same but the months are not the same‖ which becomes if ((currentYear != previousYear) || ((currentYear == previousYear) && (!currentMonth != previousMonth))) Since the years and months are primitive datatypes. and then the semester totals are reset to zero. // calculate grade average semesterAverage = (double) semesterNumerator / semesterDenominator. These English statements translate into the following Java statements. } Note the use of || to mean ―or‖. // calculate semester totals } return result. totalDenominator += semesterDenominator. When the semester changes What calculations are necessary when the semester changes? The grade average for the semester needs to be calculated and displayed. 192 . We need to remember the year and month of the previous semester. // display semester results result += "credits earned = " + semesterCredits + " average = " + semesterAverage + „\n‟. totalCredits += semesterCredits. // add semester totals to overall totals totalNumerator += semesterNumerator.// calculate averages and reset totals } // display current Mark result = result + m. The semester totals need to be added to the student totals.toString() + '\n'. we use == and !=. along with the number of credits earned for the semester. semesterCredits = 0. // reset semester totals semesterNumerator = 0.

change the previous digit to be even. A DecimalFormat object using the pattern ##0.98333 my calculator shows. Recall our discussion on splitting an integer into pieces. When you test this method. we cast (or convert) one of the integers to a double datatype and then do the division. drop it and increase the previous digit by one.766 seconds was mistakenly rounded to 9. rounding as appropriate. most students like to see at least one or two decimal places.76 instead of 9. When calculating an average mark.77 (second part of the rule). otherwise leave blank. When the first digit to be dropped is less than five. When the first digit to be dropped is exactly five. Integer division With the exception of the semesterAverage. Read the pattern as ―Display the digit in the hundreds column when it is not zero.77 (first part of the rule). When you have an expression involving a variety of datatypes. 9. the track and field world is discussing how a time of 9.766 rounds to 9. drop it and leave the previous digit unchanged. 4739/60 is 78.78 (third part of the rule). When you divide any type of integer variable by another integer variable.// remember the previous semester previousYear = currentYear. The rule usually used is ―When the first digit to be dropped is more than five. Wikipedia gives a good discussion of rounding at http://en. you will find that unfortunately the semester and overall averages appear with a varying number of decimal places.‖ As I write this (Spring 2006). all these variables are ints. it converts the other integer to a double and divides a double by a double. the third part of the rule is ignored or forgotten.wikipedia. To ensure that an integer divided by an integer gives a result with decimal places. In many cases. and 9. your result is an integer. giving a double.00 will resolve that. the Java compiler then takes over and converts them all to the ―highest‖ datatype.773 rounds to 9. Display the digit in the tens column when it is not zero or when it is zero and the digit in the hundreds column was printed. In this case. Always display the digit in the units column.org/wiki/Rounding 193 . previousMonth = currentMonth. Always display the decimal point and two digits after it. rather than the 78. You see this in the first statement.775 rounds to 9.77. otherwise leave a blank. semesterAverage = (double) semesterNumerator / semesterDenominator.‖ Thus 9.

double totalAverage. semesterCredits += credit. int totalNumerator = 0. 194 . Usually this means 50% is the minimum passing mark. String result ="". The declarations Of course. double semesterAverage. we need to omit courses which the student did not pass. the course is counted towards the semester average. int totalDenominator = 0. int totalCredits = 0.getMarkEarned(). semesterNumerator += percent * credit. String previousMonth = "".getCourseCredits(). int semesterDenominator = 0. The overall average Once we have processed all the Mark objects associated with the student. totalAverage = (double) totalNumerator / totalDenominator. To count this towards the graduating average. String currentMonth = "". How would we modify our model if different courses had different passing marks? Then we need to display the information about the current Mark. semesterDenomimator += credit. but it does not count towards the credits earned. int previousYear = 0. we can display the final average.toString() + '\n'. int currentYear = 0. int semesterNumerator = 0. int credit = m. When a student earns a mark of less than 50.When the semester remains the same We need to calculate and accumulate the totals for the current semester. as we did before. result += "total credits earned = " + totalCredits + " average = " + totalAverage. int semesterCredits = 0. int percent = m. result = result + m. all of this requires the declarations of the variables.

the method does not display the semester average of the final semester. for example). Third. the vertical spacing is not very good. the method attempts to display a semester average when it reads the first mark. We can use the same technique to avoid printing an unnecessary subtotal. That would not be sensible. First of all. 195 . Instead. Make it so. we will write a method which takes the String which the transcript method calculates and manipulates it so the details about the averages appear in the correct places.The transcript String – problems and deficiencies Like much code which people write. Adding a few „\n‟ characters to the output will solve that problem. That‘s an error. the summary comes first. What if we want to disassemble a string? Suppose we have a string String name = “Marmaduke Archibald Cholmondley”. but not wholly correct. The String class and its methods I find it is a great deal of fun to manipulate a String. and false when the resulting String should have the semester summary appearing first. You would be right in thinking these methods would repeat much of the code in the transcript method. There are so many methods available for manipulating and rearranging Strings that you can do almost anything you want to Strings. the transcript method we have produced is partly correct. We have already seen how to use a boolean variable to tell us when we are processing the first element of a collection. That makes no sense. Second. one for summary-first and one for summary-last. fix it. Nor does it add the marks and credits for the final semester into the total. but in some other order. A second way is to have two different methods. true when the resulting String should have the semester summary appearing last. for example. Fourth. How do we tell the transcript method that the summary comes first sometimes and last other times? One way is to pass it a boolean variable which is. This may be acceptable for a printed transcript but sometimes (in the online transcript my college provides. the summary for the semester follows the details for the semester. Let's look at some of these methods before we continue generating our transcript. since any errors in one method could be repeated in the other. resulting in a transcript that is hard to read.

If we wish to retrieve single characters. numbers. lastWord will be the string ―Cholmondley‖.println("]"). If we wish to retrieve substrings. \s. we use the charAt method. charAt does not remove characters from the original string. String[] names = p. String lastWord = name.compile("\\s"). firstInitial now contains the character ‗M‘. up to but not including the character in position nine. But there are alternative. String firstWord = name. a tab. Pattern p = Pattern.substring(0. i < names. a blank. That is. The regular expression we want to use consists of two characters. firstWord will be the string ―Marmaduke‖. 9). String middleWord = name. collections of consecutive characters. we use one of the two forms of the substring method. for (int i = 0.split(name).substring(20). System. What do we use to represent a backslash? 196 . The second retrieves the characters beginning at position 20 and extending to the end of the string. respectively. The first retrieves the characters beginning at position zero. possibly including wildcards.charAt(0). which refers to any whitespace character. Details of split The split method takes a string and returns an array of strings. of letters. How did we know which positions to use in the above statements? We counted characters. breaking the original string at places which match the value of a ―regular expression‖ which you specify.print("broken into strings.substring(10. etc.out. which returns an array of String. substring does not remove characters from the original string. " + name + " consists of ["). a newline. That is. The following statements will break the variable name into its pieces and display them. A regular expression is a pattern. Or we could use the indexOf method to help us find the blanks.print(" " + names[i]). Recall that previously we have used \n and \t to represent a new line and a tab. Since the characters which make up a string are numbered starting at zero. Of course.length.out. i++) System.out. We could use the split method. you can use a similar statement to determine the middle word. 19). and/or punctuation. System. char firstInitial = name.

for an input of ―here is a string‖. when the string we are seeking is not in the string we are examining. \\. In this form of indexOf. With any form of the indexOf method.Right. The first starts seeking a specified character.indexOf(„a‟. n = name. we can seek a string. since the first character ‗a‘ in name is at the second position. the String class supports a number of different lastIndexOf methods. we could look at each character and process it. Details of indexOf and lastIndexOf The indexOf method comes in several forms. Remember that we number the positions starting at 0. n = name.indexOf(„a‟). To get both the backslash and the s. the method returns -1. That is. returns the number 4. looking from the beginning of the string. One possibility is to reverse a string using an iterative algorithm. the first parameter. the second parameter is the position at which we begin seeking the specified string. 197 . Reversing a String As an exercise in using various String methods. the position of the next ‗a‘ in the string. More details on regular expressions and patterns are in the Java documentation describing the Pattern class. int n = name. Rather than seeking a character. returns the number 1. Why would it return -1? What is special about -1? If you wish to start at the end of the string and search towards the beginning. That is.indexOf(“duke”). We could also specify the position at which we begin seeking the string. we use \\s. as did substring. n). The statements n = n + 1. write a method which will accept a string and then generate the string in reverse. the output will be ―gnirts a si ereh‖. returns the number 5 since the string ―duke‖ begins in the sixth position of the string we are searching.

i < s.charAt(0). http://en. for which we know the answer. You may need to ponder this method for a while. it is its own reverse. it is the first time that we have seen a method call itself.length() <= 1) return s. tot. it is one. a) are palindromes. In this case.public static String iReverse(String s) { String result = "". as well. Both can be detected by looking at the length of the string.substring(1)) + s. } The method is declared static so that we can use it with any string. in the second case it is zero. since it is the first time we have used recursion. followed by the first character. We have seen many examples where one method calls another. then the reverse of the string is the reverse of all of it except for the first character. the reverse of the string is the string itself. That is. } The logic in this method is as follows: o If there is zero or one character in the string.wikipedia. and there is at least on smallest version. we formulate a problem in terms of one or more smaller versions of the same problem plus one or more smallest versions of the problem. else return rReverse(s. Palindromes While we are playing with strings. public static String rReverse(String s) { if (s. In the first case.length(). Why should a method not be able to call itself? Remember that recursion works because you are using a smaller version of the same problem.charAt(i) + result.org/wiki/Palindrome Can we write a method that tells us whether or not a string is a palindrome? 198 . A second possibility is to reverse the string using a recursive algorithm. Some English words (civic. there are two smallest versions. i++) result = s. Wikipedia has a discussion of palindromes in other languages and music. for (int i = 0. o If there are several characters in the string. When we use a recursive algorithm. You will see recursion again when we look at some mathematical methods in a later chapter. punctuation. level. a string which contains a single character and a string which contains no characters. return result. and case) reads the same forwards and backwards. In both these smallest cases. how about exploring palindromes? The simplest definition of a palindrome is a sequence of characters that (not counting spaces.

Try this method with some of the well-known palindromes. i++) { char ch = s. 199 .  Copy the contents of the memory to which result refers to another area of memory (call it area 1) and append ―total credits earned =‖ to the contents of area 1. The way the assignment statement above is implemented might be as follows. We use a method from the Character class. a String is immutable. isLetter. } As you can see.equalsIgnoreCase(rReverse(target)). a String is a reference to an area of memory which contains the contents of the String. Yes.Certainly. in less detail.charAt(i). a canal: Panama!‖ Others are given in the Wikipedia article cited earlier. Now that we have seen some of the String methods. Change result so its reference points to area 2. if (Character. public static boolean isPalindrome(String s) { String target = "". I‘m Adam.‖ ―A man. which changes a String. The transcript String – reordering But wait a minute! We‘ve said on many occasions that Strings are immutable. That is. Convert totalCredits to a String and append that to the contents of area 2. i < s. } return target. And now we‘ve seen how to disassemble strings. What‘s going on here? We explained this situation earlier. Determining that the string is a palindrome takes place in the return statement. // keep only those characters which are letters for (int i = 0. they cannot be changed.length(). to identify the characters which are letters. thus pointing to a different area of memory. Change result so its reference points to area 1. a plan. most of the method involves taking out the characters that are not letters.  Copy the contents of area 1 to another area of memory (call it area 2).isLetter(ch)) target = target + ch. we can go back to the original problem of producing a transcript. We have used statements like result += "total credits earned = " + totalCredits + " average = " + totalAverage. But the reference itself may change. It uses one of the reverse methods we just created. ―Madam. However. Those contents may not be changed.

even though Strings are immutable. Copy the contents of result to another area of memory (call it area 4). area 2. All others remain in the same order. * @return transcript with summary first */ public String transcriptSummaryFirst() { String result = "". Change result so its reference points to area 3. /** * create a transcript String in which the summary * comes before the details of the semester.indexOf("credits earned"). Change result so its reference points to area 4. // get transcript with summary last temp = transcript().) Only these substrings need to be moved. unreferenced) areas of memory are made available for reuse. Try to write the method transcriptSummaryFirst without reading on. How do we use this to manipulate the String that transcript has produced? First we note that there are some special substrings we need to identify and move. But what about the areas of memory I have called area 1. and area 3? They now have no references referring to them. so they are eligible for garbage collection. a process by which unused (that is.  Copy the contents of result to another area of memory (call it area 3) and append ″ average =″. // where the phrase ends String semesterDetails = "". String temp = "". startPhrase is // 6 when this happens while (startPhrase !=6 ) { // extract everything up to but not // including the phrase "credits earned" 200 . // where the phrase starts int endPhrase. Convert totalAverage to a String and append that to the contents of area 4. int startPhrase. you find // "credits earned" followed by // "total credits earned". String summaryLine = "". // repeatedly search for the // phrase "credits earned" startPhrase = temp. These begin with ―credits earned‖ and end with ‗\n‘. So now you see how we have been able to construct Strings from other Strings. Here is my transcriptSummaryFirst method. (Be careful that you do not find the substring beginning ―total credits earned‖. // at the end of the search.

// and look for next "credits earned" startPhrase = temp.indexOf('\n'). the problem is even more complicated. summaryLine = temp.indexOf("credits earned").substring(0. so we will ignore this problem. including the \n temp = temp. // remove that substring temp = temp. it may help to sit down in a quiet place and draw a series of diagrams to show the steps in the process. This will involve rethinking how the transcript method calculates the overall average. once we have examined all the marks. Actually.substring(0. continued The overall average is incorrect for a student who has repeated courses. Then.substring(endPhrase + 1).semesterDetails = temp. The transcript String – problems and deficiencies. when a student takes a course twice (or more). return result. } To understand how this method works. } // place the overall average first in the // output String result = temp + '\n' + result. 201 . its mark counts towards the semester average for each semester in which it is taken. // extract the summary line. At my college. endPhrase + 1). provided the topics are different. startPhrase). // remove the summary line. we‘ll calculate the average. This emphasises the importance of getting your model correct before you start implementing it. Rather than saving the credits and percentages we need to calculate the overall average. We have ―special topics‖ courses which may be taken more than once for credit. we‘ll create a collection that contains only the marks we‘ll need.substring(startPhrase). But only the highest mark should be included in the overall graduating average. +1 is to ensure // the \n is included endPhrase = temp. // build the result result += summaryLine + semesterDetails. Implementing this would require us to rethink our model quite seriously.

course number. course credits. we can. All the methods which we created for Mark will be available to HighestMark objects as well. m. Many datatypes allow this. the exact values we provide don‘t matter! That is all there is to the class. credits. h = new HighestMark(m. So what type of collection should we use as the basis of the collection of HighestMark objects? The order in which they are stored does not matter. i is -1 if (i == -1) // a mark for the course does not exist 202 . class HighestMark extends Mark { public HighestMark(String departmentAbbreviation. but we would like to be able to check whether there already is a mark stored for the course. // is there a mark for this course? int i = best.util. the child class HighestMark is derived from its parent class Mark. 1999. m. Mark. int markEarned) { super(departmentAbbreviation.getDepartmentAbbreviation().getCourseCredits(). HighestMark that does not concern itself with the year and semester. but we haven‘t used an ArrayList for a while.indexOf(h). ArrayList<HighestMark> best = new ArrayList<HighestMark>(). HighestMark h.We need a collection in which we can store objects containing a subject abbreviation. import java. we just provide some values. m. Since the year and month don‘t matter. so its methods are inherited from its parent. int courseNumber. markEarned). and mark earned. so let‘s use one now. We modify our transcript method by adding the following three statements.getMarkEarned()). except that Mark contains the year and month of the semester in which the mark was earned. But we already have a class like that. we convert it to a HighestMark object and compare it to other HighestMark objects. If not. int credits. That is.getCourseNumber(). Each time we process a Mark object. // if so. "SOMETIME". } } Since we don‘t care about the year and semester.ArrayList. courseNumber. We can extend it to create a new class. i is zero or more. can we use the Mark class? Yes.

This works because the indexOf method returns the position of the mark. else // a mark for the course exists if (best.getMarkEarned() < m. } totalCredits = totalDenominator. we need to talk about exceptions.getCourseCredits(). as much processing involves string manipulation. totalNumerator = 0. This is a practice called regression testing.getMarkEarned() * b. Some String methods also return -1 to indicate a lack of success. 203 . Summary This chapter has focussed on manipulating strings.getMarkEarned()) best.best.get(i). it is time to go back and cover some of the things that have been glossed-over. totalDenominator = 0. if it exists. an invalid position. This is an important skill. But to be safe. if it does not. for (HighestMark b:best) { totalNumerator += b.get(i).setMarkEarned(m.add(h). making sure that a change you made has not broken anything else. totalDenominator += b. so that we are not so dependent on BlueJ. run a unit test on it again. Now that we have experienced a serious amount of sophisticated Java code. And what if we wish the summary lines of the transcript printed before the details? Nothing we have done has changed that method. Then we will look at persistence and then developing a graphical front-end on our program. we compute the numbers we need for the overall average.getMarkEarned()). In particular. When we have processed all the Mark objects. We have seen this use of special values for invalid data when using Strings. Now we have a transcript method that calculates the overall average correctly. or -1.getCourseCredits().

What would happen if a program had a mix of one-. 3. In a previous chapter we examined bank accounts and the collection of transactions they contain. Make it so. Make sure that the list tells how many birds have been seen each month. two-. Create a method to list all the birds seen. so ―the last 60 credits‖ refers to 20 courses. Make it so. In previous chapters we have looked at the data a birder collects. 7. Of course class lists may be in order by the name of the student or by student number. showing the total number of transactions in each month. provide the number of species seen each month.Exercises 1. 6. 204 . and three-credit courses? 4. In addition. 2. Create a method to list all the transactions for a particular account. In fact. as long as she/he is registered in different sections. the student may take the same special topics course more than once in a semester. How would you modify the calculations of the graduating average if it was based on only the final 60 credits completed in a program? Many programs have only three-credit courses. How would you change the model to handle special topics courses? A student may take these courses more than once. You can use the ideas from creating a transcript to create a class list. and how many each year. Recently my bank has begun to show the account balance at the end of each day. 5. How would you modify the grade averaging process if your college assigned letter grades? How would you modify the grade averaging process if different courses at your college had different passing marks? This may entail rethinking more than a small part of the model. and each year. as well.

Before we see these exceptions. Exceptions are essential. which occurs during the execution of a program.Exceptions Learning objectives By the end of this chapter you will be able to:      Define exception Define catch and try Identify when exceptions are thrown and describe how to catch them Create. and catch your own exceptions Use exceptions to create programs which gracefully handle erroneous input and mistakes in computation Definition We have mentioned exceptions at least three times so far. IOException. and are described at http://java. available at http://java. but one of my favourites is Sun‘s Java tutorial. These include ClassNotFoundException. as viewed on 200605-19. 205 .html This section of the tutorial contains a number of quotations from the tutorial.com/docs/books/tutorial/.‖ ―Definition: An exception is an event. we have this introduction: ―What Is an Exception? ―The term exception is shorthand for the phrase ―exceptional event. The first was in the clone method where we had to handle a CloneNotSupportedException. For example.Chapter 11 . and FileNotFoundException.com/docs/books/tutorial/essential/exceptions/definition. There many other exceptions and we shall see some of them in the following chapters. One of the trails through the tutorial takes you through essential classes and features. The third was when we discussed preventing bad data getting into Meeting objects.sun. that disrupts the normal flow of the program's instructions. The second was when we discussed the need for a Professor object to have a hiring date. we should first answer the question ―What is an exception?‖ There are many sources that will answer the question. throw.sun.

consequently.‖ Examples When we attempted to clone an object. public SomeDataType clone() throws CloneNotSupportedException{ throw new CloneNotSupportedException (“Cloning is not supported by this object”). contains information about the error. ―The exception handler chosen is said to catch the exception. including its type and the state of the program when the error occurred. where we wish a collegewide policy to describe how percentages translate to letter grades. the method creates an object and hands it off to the runtime system. you could use this clone method. An example would be in the College system we have been modelling. ―After a method throws an exception. called an exception object. a CloneNotSupportedException may occur. However. The set of possible ―somethings‖ to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. you would want to be able to clone any object. the program) terminates. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler. 206 . there are some cases where you want to ensure there is one and only one copy of an object. Everybody follows the same policy. so there should be only one copy. } In this method we have created a CloneNotSupportedException with our own message attached to it. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. the runtime system (and. the runtime system attempts to find something to handle it. which we will have already seen. The object. ―The runtime system searches the call stack for a method that contains a block of code that can handle the exception. The list of methods is known as the call stack. We accomplish the same result by using the Singleton pattern. When an appropriate handler is found. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. the runtime system passes the exception to the handler.―When an error occurs within a method. Creating an exception object and handing it to the runtime system is called throwing an exception. If you want to prevent cloning an object. This block of code is called an exception handler. Normally.

such as trying to access an array element with an index that is too large or too small. or a missing hiring date. perhaps naming it MissingHiringDateException. 2507 is an incorrect time. For incorrect times.‖ The CloneNotSupportedException is a runtime exception. 0400 is a correct time. Exceptions come in two flavours: runtime and nonruntime. ―Nonruntime exceptions are exceptions that occur in code outside of the Java runtime system. indeed. When we developed the Meeting class. coming from a library used in compressing files. The Java tutorial states ―Runtime exceptions occur within the Java runtime system: arithmetic exceptions. check the documentation on Exception and its subclasses. they are also called checked exceptions.‖ Many of the Exception methods we use are actually derived from Throwable. To see a (lengthy) list of the possible exceptions available in Java. exceptions that occur during I/O are nonruntime exceptions. The exceptions reporting incorrect and inappropriate time. ―The Throwable class is the superclass (or parent class) of all errors and exceptions in the Java language. we might need IncorrectTimeException and UnlikelyTimeException but I would probably just use DataFormatException. Runtime and nonruntime exceptions As exceptions in Java are very important. such as dividing by zero. This exception. we wanted a way to ensure that a hiring date was specified. is one I find very useful when I don‘t want to create my own exception. Fortunately. once we create them ourselves. and indexing exceptions. That documentation contains the sentence ―The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. A method does not have to catch or specify runtime exceptions. we wanted a way to identify incorrect or inappropriate times for the meeting. Perhaps the class should throw a DataFormatException. The compiler ensures that nonruntime exceptions are caught or specified.‖ Reasonable. Perhaps we need to create our own type of exception. By the way. thus. When we were developing the Professor class. we have not seen one of those yet. 207 . you may wish to look at the class Throwable.Division by zero is another place that you may want to throw an exception. although it may. such as trying to access an object‘s members through a null reference. there is a class named Exception and a number of subclasses derived from it. will be runtime exceptions. but it may be inappropriate. We might have seen one if we tried to calculate a student‘s grade average for a semester in which the student was not enrolled in any courses. IOException is a nonruntime exception. pointer exceptions. For example.

We can detect that. To create an exception. 0100 to 0159. /** * Constructor for objects of class Meeting. this. along with the appropriate import statement."). roomNumber is a String It could be a String which does not represent an existing room. we would need a database of rooms. 208 . this. We can detect that. this. an existing type of exception. } This constructor assumes it has been given clean input. Thus. 2300 to 2359. */ public Meeting(int dayOfWeek. Nothing prevents an errant program or a malicious user from specifying a value like 0875 or 4500. if ((dayOfWeek < 0) || (dayOfWeek > 6)) throw new DataFormatException( "dayOfWeek may only be 0. int endTime) { // initialise instance variables this. …. startTime and endTime are both ints meant to represent time on a military clock. we have two choices. o When there is an appropriate type of exception already available. int startTime. from 0000 to 0059.roomNumber = roomNumber. String roomNumber. But what could go wrong? dayOfWeek could be an unreasonable value. Thus we can use the following statements in the constructor. When the String provided is not in that database. To detect this.. o When there is not an appropriate type of exception.endTime = endTime.dayOfWeek = dayOfWeek.6.Creating and throwing exceptions Consider the constructor for the Meeting class. and throw an exception. When a bad value is provided to dayOfWeek it makes sense to use a DataFormatException. The intent is that it is between 0 (Sunday) and 6 (Saturday) inclusive but there is nothing to force those conditions. inclusive.startTime = startTime. have the College class contain a collection of available rooms and ask the College class if it knows of the room. it may be negative or it may be seven or more. and throw an exception. We could. we create an object of that type. though. But we will have to leave that exception for another time since we don‘t have time in this textbook to see how to have a Java program talk to a database. due to some programming error or malicious input. we have a problem and should signal it by throwing an exception. we create our own exception.

int endTime) throws DataFormatException You already have a unit test for an appropriate value of dayOfWeek. * * @author rick * @version may */ import java. you throw it to some other section of your program which acknowledges the problem and fixes it.zip.util. * * Called after every test case method.framework. The tests should be something like the following. * * Called before every test case method. and one for dayOfWeek too large) to check that the exception is properly thrown. the Meeting object we desired has not been created and the portion of the program which asked to create it will need to determine the correct value for dayOfWeek before the Meeting can be created. */ protected void tearDown() { 209 . Now write two unit tests (one for dayOfWeek too small.util.import java.TestCase { /** * Default constructor for test class MeetingTest */ public MeetingTest() { } /** * Sets up the test fixture. */ protected void setUp() { } /** * Tears down the test fixture. public Meeting(int dayOfWeek. String roomNumber.zip. int startTime. public class MeetingTest extends junit.DataFormatException. we need one more modification to the constructor. Normally you don‘t create an exception and do nothing with it.DataFormatException. indicating that it throws an exception which must be handled in some other method. /** * The test class MeetingTest. Thus. In this case.

since it is a good idea to provide as much information as possible about errors which occur. } public void testMeetingLargeDay() throws DataFormatException { Meeting m = new Meeting(7.} public void testMeetingSmallDay() throws DataFormatException { Meeting m = new Meeting(-1. m). private methods are not exposed. callable only within the Meeting class.) But it may be better. "L322". This helper method is a private method. more meaningfully-named exceptions. Since we need the same sort of processing for both the startTime and the endTime. to create our own exceptions. 1000. 1000. But the same exception in thrown is both cases. assertNotNull("was created". BadMinuteException{ 210 . We identify the need to throw these exceptions by modifying the Meeting constructor a little more. since our programs will be simpler. we create a small helper method to do the processing. we can include the offending data in the message should we wish (and we should wish. but it may be better to create our own. 1030). or that it is too large. class BadHourException extends Exception { public BadHourException(String msg){ super(msg). } } We can also use a DataFormatException to indicate that the start or end times are incorrect or inappropriate. By providing our own messages (the parameter passed to the constructor). Note that the DataFormatException we have created can tell us about two problems – that the input is too small. "L322". (When you use javadoc to generate the documentation for a class. m).) /** * check if a time value is acceptable * @return true if okay * @return throw an exception if not */ private boolean isValidTime(int t) throws BadHourException. assertNotNull("was created". } } The statements defining these exceptions will be included in the same file as the Meeting class. 1030). } } class BadMinuteException extends Exception { public BadMinuteException(String msg){ super(msg). but after the closing brace for that class.

} How would you handle a time like 10:30 p. the constructor must indicate that the exceptions may be thrown. 1030). m). what happens if someone wanted to be able to provide military time as well as civilian time? Can you create a method to handle such times? Now we can create and throw exceptions. That is what catch clauses do. if (isValidTime(endTime)) this. int startTime. is expected to handle the exception. Since isValidTime may throw exceptions and the constructor doesn‘t handle them. int endTime) throws DataFormatException. BadMinuteException. int minutes = t % 100. return true. BadMinuteException Write unit tests to attempt to create Meeting objects with bad times.m. We invoke the isValidTime method as follows.startTime = startTime. 211 . BadHourException. or a method before it in the calling stack. hours too large. its calling method. public Meeting(int dayOfWeek.″ + " inclusive. You‘ll need three tests. But how do we handle the exception when it occurs. and minutes too large.? That is. if (isValidTime(startTime)) this. the processing in the current block of code ceases (unless there is a finally clause. hours too small. "L322". String roomNumber. DataFormatException { Meeting m = new Meeting(3. Why don‘t you need a test for minutes too small? The unit tests look like this. } When an exception is thrown. if ((minutes < 0) || (minutes > 59)) throw new BadMinuteException("For time " + t + " minutes should be between 00 and 59. assertNotNull("was created".endTime = endTime. described below) and the method.int hours = t / 100. 2500. if ((hours < 0) || (hours > 23)) throw new BadHourException("For time " + t + " hours should be between 00 and 23 inclusive"). public void testMeetingLargeHour() throws BadHourException.").

someone else catches it (unless you have scored a goal).Catching exceptions In baseball. That‘s the theory behind throwing and catching exceptions.clone(). when you throw the ball. Thus some piece of code must handle it. football. To repeat. That is not the case for the majority of exceptions. 212 . Since we know it cannot happen. in this situation the code in the catch block will never be executed. we show this as try { Some statements which can throw exceptions } catch (one type of exception) { } catch (another type of exception){ } CloneNotSupportedException You have already seen a catch clause in the clone method. } catch (CloneNotSupportedException e) { return null. In a general way. we place the code which could cause an exception inside a try block. // can not happen } } In this case. basketball. /** * clone * @return a copy of the Address */ public final Object clone() { try { return super. the processing we do is minimal. the CloneNotSupportedException may be thrown by super. and lacrosse. In this case. rugby. water polo. When the problem is something we can handle ourselves immediately.clone(). we handle it ourselves. It is repeated below.

you need to pass it back to the method which called this one. // do something with the course object } catch (anException) { // what can you do? // You need to have the person/method // which created the information correct it. try { c = new Course(information).Bad input data But suppose you have gathered the information to create a Course object. but there is some information which is missing or otherwise ―bad. // That can not be done here. 213 . Summary Exceptions are the powerful technique Java uses to handle errors. This process uses exceptions extensively.‖ Your program will look somewhat like this. // The exception must be handled elsewhere. We will see many more exceptions in the chapters that follow. // so there should not be anything in the // catch block here! } Rather than handling the exception yourself here. // gather information Course c. The following two chapters involve writing data to external devices.

His name was something like R B Jones. 3. many people go by just one name. Modify the constructor for Person so that it determines that both a first and a last name are provided and throws exceptions if either name is missing. So the data entry people entered the name as R(only) B(only) Jones. The payroll system threw exceptions for one-character names. In Indonesia. Modify the constructor for Person so that it throws one or more exceptions if there is a birth date provided but it is an inappropriate date. 2. 214 . Explore the Exception class to see what other types of exceptions are available to you.Exercises 1. A second story was about the person who didn‘t have a long first and middle name. How could you determine that you are in a country where people use only one name? There are many stories about programs that have difficulty with names. One story is about a payroll system in which last names with only one character were used for testing purposes. That worked well until a person with the last name A joined the organization. Thus R B Jones became Ronly Bonly Jones. The people who wrote the system stripped out unusual characters from the input.

In short. it is the ability to save an object and retrieve it at a later time. 215 . make it this one. We need a way to create objects and then save and restore them so we can use them again. you should be aware there is a small section in the mathematical chapters which you will need to omit should you omit the subject of persistence now. Of the two chapters.Chapter 12 – Persistence. If you need to skip a chapter. after we have ended BlueJ. If you prefer to skip this chapter. given the model we are building.‖ In computing. turned the computer off. Chapter 13 describes a technique which is being used more and more. persistence is closer to the second definition. perhaps the next day. but they exist only until you recompile the object or exit BlueJ. Suppose we wish to create several objects and have them available at a later time. Yes. this one describes an older technique which is becoming less common as time goes by. and the next. but only for the duration of the test. BlueJ allows us to place the objects it creates on the Object Bench. However. we need to investigate ways to ensure the persistence of objects. part 1 Learning objectives By the end of this chapter you will be able to:   Define persistence Implement persistence through object serialization Warning to the reader This chapter and the next explore some advanced concepts which many people would prefer to omit from an introductory programming course. Why persistence? Unit testing provides a way to create and destroy objects. ranging through ―doggedness‖ and ―a tendency to continue. and then restarted BlueJ. I feel it makes perfect sense to include the subject of persistence. Persistence has many meanings.

When an object is restored. and its state will be reconstituted from what was previously saved. perhaps including special characters. but is the origin of the type of serialization we are considering in this chapter. thus granting it persistence. state. Since an object has identity. we must consider the external devices we will use and their characteristics. floppy disks. Files have names. it is a topic for more-advanced study. The use of databases is possible as well. The terms used in Java are serialization and deserialization. written to (or read from). Notice that there are other ways of saving data. DVDs. Thus we have seen the use of non-volatile memory (punched cards. but we will not discuss that here.) There are programming languages (COBOL and RPG are examples) designed to simplify the processing of such data. when it loses power. local or somewhere else on the Internet. These files must be opened. supporting many types of processing of data.The random access memory (RAM) in a computer is volatile. Traditional file processing is possible. and memory sticks. We will not explore that option here. and then closed. Java allows us to serialize an object. It too requires the processing of data saved by other programs. what does saving an object mean? Saving an object involves converting the object‘s state (the values of its instance variables) to a stream (a continuous sequence) of bytes and writing those bytes onto a medium which will not lose its contents when the power is removed. The ability to save data has been required since the earliest days of computing. The external devices could also be other computers. it loses its contents. The external devices are mostly disk drives and the files they contain. CDs. in real time. 216 . You can use serialization to send objects from one computer to another. it will be given a name and will have behaviour (as specified in the class definition). magnetic tapes. but that is much more complicated and we will not discuss it here. Java is a more generalized language. Serializing an object involves writing it to an external storage device. You can think of streams as sequences of characters. Thus RAM is not suitable for persisting data. External devices Before we can look at serialization. Streams Writing to and reading from external devices is done through streams. you would need to ensure that the supply of electricity is uninterrupted. hard drives. Deserializing an object involves reading it back from that external storage device. and behaviour.

If not.  An Address object which is not yet serializable. ―A file output stream is an output stream for writing data to a File…‖ Remember that BlueJ helps you access the online documentation.io package. ―An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream.So we need streams to which we can write and from which we can read and we need a way to associate a stream with an external device. Looking from the operating system level first. before we can serialize a Person object. Similarly. it is serializable. A Person object contains  Several Strings which are all serializable by design.‖ Think of a graph as the instructions for recreating the structure of the object. If you prefer.com/javase/6/docs/api/.sun. look into the documentation and see if it implements the Serializable interface. you can download this documentation onto your own computer and then use Tools. As the documentation says. and the FileOutputStream connects that stream to a file on the underlying operating system. Associated with the FileOutputStream will be an ObjectOutputStream. we need to ensure that all its instance variables are serializable. Which streams will we need for object serialization? This technique requires writing objects to streams. Thus. Miscellaneous to provide the Java documentation URL.  A MyDate object which is not yet serializable. Methods in ObjectOutputStream allow us to translate the objects into a stream. Object serialization .io package which allows us to connect a stream to an actual file. Let‘s begin by considering the Address class and making it serializable. and Java Class Libraries. All the instance variables of Address objects 217 . we can use FileInputStream and ObjectInputStream to retrieve and reconstruct the objects.Address For an object to be serializable. its class must implement the Serializable interface as noted above and all its instance variables must be serializable. If so. Persistence via object serialization Note that we can only serialize (save) and deserialize (restore or rebuild) objects all of whose components are serializable. Click Help. it isn‘t. we find that FileOutputStream is a class in the java. Your default browser opens http://java. If you want to see if a class is serializable. Preferences. As the documentation says. Now we are ready to see how to do object serialization. another class available in the java.

// write one object and remember that oos. "AB".Serializable. public void testSerialization(){ int i = 0. "". "T0L0M0"). implementing the Serializable interface is all you need to do to make a class serializable. Address a. // write a second object and remember that oos. import java. Serializable That‘s it! Due to the simple nature of the instance variables of Address. Examine the Java documentation to confirm that String does implement the Serializable interface. below. To make Address serializable. and modify the class heading to indicate the class implements the Serializable interface. ObjectOutputStream oos = new ObjectOutputStream(out). "". "RD". "Kelowna". "X". You‘re ready to create a unit test to confirm that an address is serializable. Here is the unit test method to check that we can serialize these two Address objects.writeObject(a). public class Address implements Cloneable.io. and are all serializable). simply add a statement at the beginning of the class. try { FileOutputStream out = new FileOutputStream("address. "Calgary".writeObject(a1). "Canada". Begin by creating two Address objects within the Address unit test. in the setUp method. In some cases (the instance variables are single-valued. i++. it says something about the class which implements it. "V1Y4X8"). "Fifth". "CA". look at the Serializable interface itself for its details. a = new Address("1234". Address a1. "KLO".dat"). While you are looking in the Java documentation. 218 . you need do nothing else to make an Address object serializable. not collections. but it doesn‘t bring along methods and instance variables. "Avenue". "BC".are Strings. will check that the correct data was written. It will attempt to write out the two objects and then check that two objects were really written. Serializable is what is called a marker interface. The deserialization test. a1 = new Address("1000". "SE".

} catch (FileNotFoundException e) { System.IOException. } Note that in order to use serialization we must also use exceptions.ObjectOutputStream.println("problem with ObjectOutput " + e. } // check that we were able to write two objects assertEquals(i. Here‘s a suggestion. when you need to import many classes from one package. an Address knows how to serialize itself. Since an Address is made of serializable objects and Address implements Serializable. We have no more output so ensure // the buffer is written to a disk somewhere oos. The asterisk is a wildcard.io package. we need to include the statements import java. 2). // output may be held in memory until a buffer // is full.i++. but not any packages within java.io. so that the messages displayed in the catch clauses have a place to 219 . For this unit test to compile.println("problem with address. import java. which we saw in the previous chapter. // we don‟t need the stream any more oos.io. import java. But it is easier.err.toString()). The writeObject method is a method in the ObjectOutputStream class.*. A wildcard means ―any value that matches this pattern.io.io.‖ Checkstyle will complain if you use a wildcard to import classes.err.* means ―every class in the java. The unit test uses the writeObject method to actually write an Address object.flush(). make sure that you open the BlueJ Terminal window. Before you run any methods which use exceptions.toString()).io.‖ In this case. to just use import java. } catch(IOException e) { System.close().FileOutputStream. java. where any value can replace the asterisk.io.dat " + e.

or press + T. If you look closely at the code. } catch (IOException e) { System. should there be an error of some kind. by casting to an Address.getCity(). Usually this will not happen.err. a1 = (Address)ois. after all the existing objects become null.println("Can not find address.toString()). public void testDeserialization() { try { FileInputStream in = new FileInputStream("address. Note that any method which casts an Object to some other datatype must handle a possible ClassNotFoundException. We have talked about saving and then restoring an object. an error. then we would have many objects in the stream. but the casting process requires us to handle that possibility. choose View.close(). assertEquals(a. // we use the same file name as in writeObject ObjectInputStream ois = new ObjectInputStream(in). "Kelowna").dat " + e. a = (Address)ois. If we were to serialize a collection.display.) We can do this because both are Address objects. their order would be restored.dat").readObject(). But note there is something unusual going on here.getCity(). Both of these tests succeed. } catch (ClassNotFoundException e) { // will not happen but must be caught } assertEquals(a1. "Calgary"). when the stream cannot be opened).toString()). But serialization is not designed to work quite like this. } The readObject method is a method in ObjectInputStream.readObject().err. } catch (FileNotFoundException e) { System.println( "file problem with ObjectInput " + e. ois. To do this. 220 . but restored them in the reverse order (a1 and then a. when we recreated the collection. The deserialization takes place at a later time. with one method serializing and another immediately deserializing. and we must then indicate the type of object. Show Terminal. Here is a unit test to check that we can deserialize Address objects. It reads an object from the stream (throwing an exception. or have ceased to exist. you‘ll see that we serialized the two Address objects in one order (a and then a1).

But that fact is not particularly useful to us right now. This is because they each contain collections. but we know how to do that. they are like Address and MyDate. and when there are no collections (a fact already mentioned). Object serialization – Meeting and Mark You may have implemented these two classes. Student. It is very easy to make them serializable. in the College class. static class variables are accessible to all objects of the class. We have seen some static constants. Since a MyDate object only contains single-valued instance variables. We have seen very few of them yet.Object serialization – MyDate Recall that we began by discussing how to serialize a Person object. Create the unit tests to show the serialization and deserialization of MyDate objects works. and a MyDate (not yet serializable. they work when there are no static or transient variables (a fact not already mentioned). Are they serializable? No. Make it so. That will be implemented as a static class variable. all the instance variables of a Person are now serializable. we cannot create instances of a Person object. by design). an Address (now serializable). all this involves is asking the class to implement the Serializable interface. Object serialization – Person. 221 .) Make the MyDate class serializable. only one in fact. A Person object contains Strings (all serializable. In particular. static instance variables persist from one method call to another. since the rate changes from time to time but is common for all bank accounts. The Person class is abstract. as they contain only single-valued instance variables with no collections. Consider the interest rate paid on all bank accounts. Object serialization – some subtleties The readObject and writeObject methods we have used so far work well for simple situations. Professor Assuming the code you created to serialize MyDate (and perhaps Mark) works. Person is the parent class of Student and Professor and we can create instances of Student and Professor. If so. We will explore how to deal with the collections in a few moments.

so the skeleton for the writeObject method we need to create looks like this. When we have static variables. using the appropriate write methods of the ObjectOutputStream class and the read methods of the ObjectInputStream class. We‘ll override those methods with our own. we will need to create our own methods to read and write objects. ―Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures: private void readObject(java. In particular.ObjectOutputStream stream) throws IOException ‖ Assuming we have the appropriate import statements. a topic which we will not discuss further here. too.ObjectOutputStream. we can just use ObjectInputStream instead of java.io.io. ClassNotFoundException. We can encrypt variables using the java. or because they require special handling (like encryption).security package.But writeObject does not serialize static instance variables and thus readObject cannot deserialize them. Object serialization – creating writeObject and readObject methods Some classes contain collections. private void writeObject(ObjectOutputStream oos) throws IOException{ // write instance variables } // end writeObject 222 . How do we create our own readObject and writeObject methods? The signatures of these methods are specified in the ObjectOutputStream documentation as follows. we will need to provide replacements for writeObject and readObject. usually because they can be calculated (like iterators or retirement dates). to use that technique we will need to write some extra methods. We can handle collections on our own. private void writeObject(java. We can serialize static variables ourselves. We will need to deal with such variables on our own.ObjectInputStream stream) throws IOException.io.ObjectInputStream and ObjectOutputStream instead of java. transient is a reserved word. The standard readObject and writeObject methods won‘t work with those classes.io. used to identify variables whose state should not be saved. Like encryption.

we could use. This assumes student identifiers are serializable. This assumes Student objects are serializable. If we are serializing that class. oos. This is a generic method and needs to be modified for each class in which we use it. } where oos has been opened earlier. The only place that we should have a collection of Student objects is the College class.writeObject(theStudents.readObject()). } } // end readObject To use this method.size()). } where oos has been opened earlier. we create our own readObject method. Then I write the collections. in the College class.size()). for (String s:theStudents) { oos.add((Student) oos. we could use the following statement.println("Unable to deserialize " + e. we could use the following statement.writeObject(theStudents. int n = (Integer) oos. first.readObject(). should there be any. i < n. the ones which are not collections.toString()). first writing the number of elements in the collection and then the elements of that collection. for (Student s:theStudents) { oos. My style is to write out the singlevalued instance variables. Similarly. Set<Student> theStudents = new HashSet<Student>().The comment indicates where we write the instance variables. oos.writeObject(s). The Course class contains a collection of student identifiers. If we are serializing that class. they will be soon. they are since they are Strings. corresponding to the students in the class. for (int i = 0.writeObject(s).err. private void readObject(ObjectInputStream ois) throws IOException { try { // read instance variables here } catch (ClassNotFoundException e) { System. for example. i++) { theStudents. 223 .

println("Problem with sections.} Any special handling required by transient or encrypted variables will need to be included in the method as well.obj " + e. which look after opening and closing the streams. both the readObject and the writeObject methods will be called by other methods. i++.out. System. illustrated below for the Section class. which is serializable. Section is a class which contains two collections. Object serialization – Section and Student Due to the similarities between these two classes we‘ll discuss them together. perhaps as members of a collection. to the ones which contain collections.toString()). This class is derived from Person. Student is also a class which contains two collections. in particular.close().err. as well as extracting the objects and saving them with unique identities. the other (theMeetings) is a collection of Meeting objects (which we just made serializable). the other (theMarks) is a collection of Mark objects (which we just made serializable). ObjectOutputStream oos = new ObjectOutputStream(out). oos. Why?). Why?).writeObject(s1).println("s1 = " + s1. we have the following method in SectionTest.println("s2 = " + s2.toString()). oos. One (theSections) is a collection of section identifiers (serializable. One (theStudents) is a collection of student identifiers (serializable. we use the same logic. public void testObjectSerialization() { int i = 0.obj"). i++. Following the idea of creating the unit test first. System. oos. For both of these classes. As we have seen in the examples above. } catch(IOException e) { 224 . Let‘s see how this applies to the classes we have developed.flush(). oos.out.writeObject(s2). } catch (FileNotFoundException e) { System. try { FileOutputStream out = new FileOutputStream("sections.toString()).

One appears in testObjectSerialization as oos.writeObject(s2).writeObject(endMonth). oos. // write the collections oos.writeObject(endYear). Now you can serialize a section.writeObject(m). in the Section class.writeObject(startYear).writeObject(courseNumber).writeObject(startMonth). }.writeObject(sectionNumber). oos.writeObject(getStudentCount()).writeObject(departmentAbbreviation). oos.writeObject(s).println("Problem with ObjectOutput " + e. but how do you deserialize it? 225 . oos.writeObject(howManyMeetings()). The other appears as a private method in the Section class. private void writeObject(ObjectOutputStream oos) throws IOException { // write the single-valued instance variables oos. oos. oos.System. oos.toString()). oos. as private void writeObject(ObjectOutputStream oos) throws IOException The first is automatically translated into a call to the second. Much of it is taken up with processing the collections which are part of the object. if (getStudentCount() > 0) for (String s:theStudents) oos. Run the unit test and confirm that you can serialize a Section. if (howManyMeetings() > 0) for (Meeting m:theMeetings) oos.writeObject(identifier). Note that we have two writeObject methods. } assertEquals(i. 2).err. } Now we can create the writeObject method itself.

obj " + e. assertEquals(s1.readObject().courseNumber = (Integer) ios. s1 = (Section)ois. this. } catch (ClassNotFoundException e) { // will not happen but must be caught } assertEquals(s2. for (int i = 0. we create the readObject method itself.obj"). } Finally.toString()). private void readObject(ObjectInputStream ios) throws IOException.readObject().readObject().readObject().readObject().close(). "PHYS"). this.startMonth = (Integer) ios. ObjectInputStream ois = new ObjectInputStream(in).identifier = (Integer)ios.readObject().readObject().readObject(). Much of it is again taken up with processing the collections which are part of the object.toString()). this. ois. this. "COSC").println( "file problem with ObjectInput " + e. this. } catch (IOException e) { System.students = new HashSet<Student>(). this.departmentAbbreviation = (String)ios. this.err.endYear = (Integer) ios. ClassNotFoundException { // single-valued instance variables this.err.readObject(). s2 = (Section)ois.readObject().readObject().endMonth = (Integer) ios.println("Can not find sections.getDepartmentAbbreviation(). int n = (Integer) ios. i++) { 226 .startYear = (Integer) ios.sectionNumber = (String) ios. public void testObjectDeserialization() { try { FileInputStream in = new FileInputStream("sections.getDepartmentAbbreviation(). // collection instance variables this. i < n. } catch (FileNotFoundException e) { System.Object deserialization – Section and Student First we create the unit test for the readObject method.

meetings = new TreeSet<Meeting>(Meeting. This appears a little unusual. Note also that we have used statements like this. We could convert an int variable i to an Integer object iObject with the statement Integer iObject = new Integer(i).readObject(). autoboxing and autounboxing. the first is translated into the second. for (int i = 0. } this.0 (also known as Java 5). Autoboxing carries out the first statement for us and thus makes it easier to convert primitive datatypes to the corresponding object.5.add((Meeting) o). this.readObject().identifier = (Integer)ios. } } Note that we again have two readObject methods. not primitive datatypes. since the left side of the assignment statement is a primitive datatype and the right side is an object. Autounboxing carries out the second statement for us and thus makes it easier to extract primitive datatypes from objects. In many places we need to convert primitive datatypes like int to their corresponding object.readObject(). in this case Integer. theMeetings. The one in the Section class is readObject(ObjectInputStream ios) Again.TIME_ORDER). Two new concepts were added to Java beginning with Java 1.readObject(). n = (Integer) ios. collections contain objects. theStudents.add((String) o). The one in the testObjectDeserialization method appears in s1 = (Section)ois.Object o = ios.readObject(). 227 . i++) { Object o = ios. and then insert iObject into the collection. We could extract the int from the object with the statement i = iObject.intValue(). When would we need to do this? Well. i < n.

This gives rise to very complicated programs. 228 . The collection of courses taught in the past is a collection of Strings. But the students don‘t start registering until next week. As I review this section. using individualized writeObject and readObject methods because of the collections. We simply serialize a zero if the collection is empty.) Make Professor serializable. a course may not have any sections. and it is not advisable. Strings. Instead. Object serialization – College Now that all the classes we have built are serializable. We will do so. but because they are collections. we may be serializing a section before it has its meeting times determined and/or before students have registered. Professor objects are serializable. and any additional instance variables (birthDate and retirementDate) are serializable. Our way of writing a collection (record the number of items in the collection. if any) accommodates this nicely. in particular. Make it so. It contains various collections so we had to wait until all their elements are serializable. We will follow those standards. Object serialization – Section and Student. it is better to have an idea ahead of time of the structure of the file. For example. it is important to know that the file contains objects of only one class. revisited We may be serializing a class while its collections are empty. not because they contain Strings. Object serialization – Professor Since Professor is derived from Person (which is serializable). you may extract objects one at a time from the file and then use instanceof to determine the datatype of the object before you cast it appropriately. (We mentioned adding some collections to a Professor object. The collections require separate processing. and they finally are. and then the items themselves. many programming standards forbid this use of instanceof. Similarly. the sections are all in place and their meeting times have been set. In fact. The collection of current sections taught is a collection of section identifiers. particularly before the scheduling of those sections occurs. we can make the College class serializable.Programming style Should you have one large data file which contains many objects of different types and you don‘t know the order of the types.

Why would we want to do this? Perhaps so that we could create a webpage from the data we read. In many cases it might be better if the file could be read by a program written in a language other than Java.Summary In this chapter we have seen one way to save the state of our objects. 229 . We‘ll explore a technique which allows this in the next chapter. The problem with the particular technique is that it produces files which are only readable by another Java program. Perhaps so that we could create printed material from the data we read.

Make the Mark class serializable. make it serializable. If you have implemented a Department class. Make the BankAccount class serializable. In a previous chapter we discussed modelling the sightings a birder makes. Is the Transaction class serializable? If not. 8. make it so. Make the AngloAmericanPlayingCard class serializable. 2.Exercises 1. 230 . In a previous chapter we discussed modelling playing cards. 6. 3. Make the Meeting class serializable. 4.security package to see how you can encrypt data when you serialize it. Make the class Sighting serializable. 5. Explore the java. 7. Make the MyDate class serializable. In a previous chapter we discussed modelling bank accounts.

These contain the instructions to paint a picture. capable of describing many different kinds of data.wikipedia. It could be a logo.org/wiki/XML) defines XML as follows: ―The Extensible Markup Language (XML) is a W3C-recommended general-purpose markup language for creating special-purpose markup languages. A Digression . part 2 Learning objectives By the end of this chapter you will be able to:   Define XML and describe its characteristics Implement persistence using XML Persistence via XML Wouldn‘t it be great to have a way to write a file so that it contained both data and a description of that data? What if a file could be read by many different programs. the Extensible Markup Language. ―XML is a way of describing data and an XML file can contain the data too‖. written in different languages? And wouldn‘t it be great if a file were also human-readable? There is a way to do all that. or it could be an animated movie.Scalable Vector Graphics Scalable Vector Graphics (SVG) files are an interesting application of XML files. and it involves the use of XML. there is no problem. The serialization in the previous chapter allows us to store the structure of objects and to remember the data they contain. You can display XML files on the web.‖ We are particularly interested in the ―in other words‖ portion of that definition. Thus you can examine them in a text editor. Wikipedia (http://en.Chapter 13 – Persistence. so you may have skipped that chapter. In other words: XML is a way of describing data and an XML file can contain the data too. But it is a less-common technique. You can write programs to process the files containing XML in languages other than Java. since that is what we wish to do. If so. as in a database. Why would we wish to use XML? The files containing XML are plain text files. What sort of picture? It could be as simple as a bar graph. 231 . Is this chapter we will see that XML serialization is an alternative way to do this and much more.

beans. are different because they are in different classes. import java. For more details on SVG files. To reconstitute the objects using the data and instructions in a file we will use an object of the XMLDecoder class.XMLDecoder. there must be some other code elsewhere. Both XMLEncoder and XMLDecoder are in the java. public void testXMLSerialization() { Thread.You could create a picture using something as simple as Notepad or as complicated as Adobe Illustrator.beans package so we need to import them into any class which will be using XMLEncoder and XMLDecoder. search the web for terms like SVG and create. There are even pictures you can create using a Java program. These methods.XMLEncoder. Here‘s a method within the Address class which translates an Address object into XML. The class Address contains a writeObject method.setContextClassLoader( 232 . and uses an XMLEncoder which has miraculously appeared from nowhere. To carry out its task. Using an XMLEncoder . The advantage of them is that they are very small. we will use an object of the XMLEncoder class. import java. } // end writeXML This method is named writeObject and it calls a method also named writeObject. classes which have a no-parameter constructor and setters for all instance variables. public void writeObject(XMLEncoder e){ e. It translates an object into the instructions necessary to restore it and provides the value of the object‘s instance variables to be used when restoring it.beans.writeObject(this). Since the method we created is very short.currentThread(). which is associated with a file. Most modern browsers will display SVG graphics. it delegates responsibility to the writeObject method from the XMLEncoder class. while sharing the same name. Similar methods work with all of our classes which do not contain collections. It processes the instructions the decoder created.no collections To translate an object into the appropriate XML statements. Using an XMLDecoder is similar to deserialization with its readObject method. Note that these classes are designed for use with JavaBeans. Using an XMLEncoder is similar to serialization with its writeObject method. Our classes are not JavaBeans. but we‘ll convert them to JavaBeans in a moment. It‘s in the unit test.

"X". there are no setters for the collections.err.org/mhonarc/lists/gef-dev/msg00469. or perhaps using separate processors. "T0L0M0").currentThread(). For now. we simply use that statement whenever we wish to use an XMLEncoder or an XMLDecoder. This hint was provided through an answer to a question at http://dev. "Calgary". the XMLEncoder is unaware of the class Address.setContextClassLoader(getClass().getClassLoader()). To avoid this error. The file created when we pass a1 to the XMLEncoder is shown below. perhaps sharing a processor.getClassLoader()).xml"))). The heading lines may change as different versions of XML and Java appear. // the variable a is an Address and has been // defined in the setUp method a.html. Without that line. Threads are a mechanism by which a program can be doing several things at once. it‘s just values I made up. "Fifth". "AB".XMLDecoder"> <object class="Address"> <void property="city"> <string>Calgary</string> 233 . } } Note the line that reads Thread. This is not a real address.close(). e.getClass().eclipse.0_01" class="java.beans. Once the XMLEncoder is aware of the class it is processing. "Canada". "Avenue".5. so the collections are not output.writeObject(e). <?xml version="1.println(fe. it can prepare output for all instance variables which have setter methods. Note that when our objects contain collections. Suppose we create an address object with the statement Address a1 = new Address("1234". try { XMLEncoder e = new XMLEncoder( new BufferedOutputStream( new FileOutputStream("address. Your method will generate a ClassNotFoundException error. } catch (FileNotFoundException fe) { System. We need to do that ourselves and we will see how in a few moments. We will explore threads in a later chapter.toString()). "SE".0" encoding="UTF-8"?> <java version="1. include this statement in any method which creates either an XMLEncoder or XMLDecoder object.

</void> <void property="country"> <string>Canada</string> </void> <void property="direction"> <string>SE</string> </void> <void property="name"> <string>Fifth</string> </void> <void property="number"> <string>1234</string> </void> <void property="postalCode"> <string>T0L0M0</string> </void> <void property="province"> <string>AB</string> </void> <void property="suffix"> <string>X</string> </void> <void property="type"> <string>Avenue</string> </void> </object> </java>

You can see how the file encodes the class name and instance variables. The <object> tag indicates the class of the object. The property tags indicate, in alphabetical order, the instance variables and <string> indicates the datatype of the instance variables. Other datatypes will appear when necessary. Each tag has its corresponding closing tag, beginning with </. You can display an XML file in a text editor (like Notepad), in a browser (like Internet Explorer or Mozilla Firefox), or in an XML editor (like XMLSpy) or, as noted earlier, you can write a program in some other language to read and display the contents of the file. Using an XMLDecoder - no collections Once we have created a file containing XML statements, we can create a method to retrieve information from it. An XMLDecoder works by assuming that you have a no-parameter constructor plus setters for all the instance variables. We don‘t have a no-parameter constructor yet, so we need to create one.
/** * no-parameter constructor for an Address, * used with XMLEncoder. */ public Address() {

234

}

This no-parameter constructor creates the object, but none of the instance variables have values. It might be better if we at least gave the instance variables the value of blank, or zero, or null, depending on their datatype. If the class contains any collections (this one does not), your no-parameter constructor must create them (as empty collections) too, as we will see in a few moments. Check that you have setters for all your instance variables. Check also that the name of the setter is the word ―set‖ followed by the name of the instance variable. If you need to rename any of your setters, change (and rerun, just to be sure) the appropriate unit test as well. Here is a method which retrieves a single Address object from the file address.xml, assuming the no-parameter constructor and all setters exist.
/** * restore an Address from XML. */ public void readObject(){ Thread.currentThread().setContextClassLoader( getClass().getClassLoader()); try { XMLDecoder d = new XMLDecoder( new BufferedInputStream( new FileInputStream("address.xml"))); Address a = (Address) d.readObject(); d.close(); // a has been created as a temporary variable. // now copy its contents to the variable we // really want. this.number = new String(a.number); this.suffix = new String(a.suffix); this.name = new String(a.name); this.type = new String(a.type); this.direction = new String(a.direction); this.city = new String(a.city); this.province = new String(a.province); this.country = new String(a.country); this.postalCode = new String(a.postalCode); } catch (IOException e) { System.out.println("Error reading address " + e.toString()); }// end catch return; } // end readAddressXML

If we used a statement like this.number = a.number; we would have two variables both referencing the same area of memory. By writing this.number = new String(a.number); we have

235

two variables, referencing different areas of memory, with the different areas containing the same data. We could use a clone method to copy the variables if we prefer. We can test this decoding with simple unit tests. Create two Address objects in the setUp method, containing different values. Then write one out, and retrieve its value into the other.
public void testXMLSerialization() { Thread.currentThread().setContextClassLoader( getClass().getClassLoader()); try { XMLEncoder e = new XMLEncoder( new BufferedOutputStream( new FileOutputStream("address.xml"))); a.writeObject(e); e.close(); } catch (FileNotFoundException fe) { System.err.println(fe.toString()); } } public void testXMLDeserialization() { Thread.currentThread().setContextClassLoader( getClass().getClassLoader()); try { XMLDecoder e = new XMLDecoder( new BufferedInputStream( new FileInputStream("address.xml"))); a1.readObject(e); e.close(); } catch (FileNotFoundException fe) { System.err.println("unable to create file"); } System.out.println(a1.toString()); assertEquals("addresses match", a.toString(), a1.toString()); }

Does this method work?
/** * Possible alternative to restoring an Address from XML. */ public void readObject(){ Thread.currentThread().setContextClassLoader( getClass().getClassLoader()); try { XMLDecoder d = new XMLDecoder( new BufferedInputStream( new FileInputStream("address.xml")));

236

Address a = (Address) d.readObject(); d.close(); // this part of the method is different! this = a; } catch (IOException e) { System.out.println("Error reading address " + e.toString()); }// end catch return; } // end readAddressXML

Why or why not? Using an XMLEncoder - with a collection Most of our classes include collections. The collections are instance variables which have neither setters nor getters. Instead, they have methods for adding elements to the collection. This lack of getters and setters causes problems with XML serialization, since the XMLEncoder and XMLDecoder use the setters and getters. However, Java provides an alternative mechanism we can use in this case, the DefaultPersistenceDelegate class. A DefaultPersistenceDelegate determines the statements the XMLEncoder produces for us. Unknowingly, we have been using a DefaultPersistenceDelegate, a simple one which assumes the class is a JavaBean, when we saved Address objects using XML. It knew what to do with the noparameter constructor, the getters, and the setters. But we must provide an alternative DefaultPersistenceDelegate whenever we are dealing with a class which contains one or more collections. Let‘s see how this works with the Section class. Remember that the Section class contains two collections, one (theStudents) of student identifiers and the other (theMeetings) of Meeting objects. First, we must make modifications to the Section class. Create a no-parameter constructor. This constructor creates the empty collections.
public Section() { this.theStudents = new HashSet<Student>(); this.theMeetings = new TreeSet<Meeting>(Meeting.TIME_ORDER); };

Then we extend the DefaultPersistenceDelegate class within the file containing the Section class. That is, Section.java will now contain two classes.
class SectionPersistenceDelegate extends DefaultPersistenceDelegate{

237

// create XML statements to define instance // variables and their values // each statement includes the method to be called and // its arguments, as an array protected void initialize(Class type, Object oldInstance, Object newInstance, Encoder out) { // single-valued instance variables Section s = (Section) oldInstance; out.writeStatement(new Statement(oldInstance, "setIdentifier", new Object[]{s.getIdentifier()})); out.writeStatement(new Statement(oldInstance, "setDepartmentAbbreviation", new Object[]{s.getDepartmentAbbreviation()})); out.writeStatement(new Statement(oldInstance, "setCourseNumber", new Object[]{s.getCourseNumber()})); out.writeStatement(new Statement(oldInstance, "setSectionNumber", new Object[]{s.getSectionNumber()})); out.writeStatement(new Statement(oldInstance, "setStartYear", new Object[]{s.getStartYear()})); out.writeStatement(new Statement(oldInstance, "setStartMonth", new Object[]{s.getStartMonth()})); out.writeStatement(new Statement(oldInstance, "setEndYear", new Object[]{s.getEndYear()})); out.writeStatement(new Statement(oldInstance, "setEndMonth", new Object[]{s.getEndMonth()})); // collections for (Student st:s.getStudents()) { out.writeStatement(new Statement(oldInstance, "addStudent", new Object[]{st})); } for (Meeting mt:s.getMeetings()){ out.writeStatement(new Statement(oldInstance, "addMeeting", new Object[]{mt})); } } }

238

Recall that the theStudents and theMeetings collections both have private visibility. To access their elements, we need two more methods in the Section class, getStudents and getMeetings.
public Set<String> getStudents() { return theStudents; } public Set<Meeting> getMeetings() { return theMeetings; }

As noted in an earlier chapter, it would be better style if we created iterators allowing us to access individual elements of the collections. Make it so. Finally we create a DefaultPersistenceDelegate object and attach it to the XMLEncoder we are using.
/** * save a Section as XML. * @param e The XMLEncoder which will create the file * @return nothing */ public void writeObject(XMLEncoder e){ // need a DefaultPersistenceDelegate because of // students and meetings e.setPersistenceDelegate(Section.class, new SectionPersistenceDelegate()); e.writeObject(this); } // end writeObject XML

That‘s it. Except of course there are some import statements we need.
import java.beans.DefaultPersistenceDelegate; import java.beans.Statement; import java.beans.Encoder;

Yes, there is a unit test which defines the file to which the XMLEncoder is connected.
public void testXMLSerialization() { Thread.currentThread().setContextClassLoader( getClass().getClassLoader()); try { XMLEncoder e = new XMLEncoder( new BufferedOutputStream( new FileOutputStream("section.xml"))); // create a Section object

239

// specific instance variables are not shown here // to save space // and save the object s.writeObject(e); e.flush(); e.close(); } catch (FileNotFoundException fe) { System.err.println(fe.toString()); } }

Now we are able to write a Section object to an XML file, sometimes called an archive. If you wish to see the XML file produced by the writeObject method, simply navigate to the folder or directory in which it was placed (the default is the one in which your project is located) and use any of the programs noted above. The file we have just created contains many lines, but is not that complicated. Here is sample output, describing a section containing four students, meeting twice a week.
<?xml version="1.0" encoding="UTF-8" ?> - <java version="1.5.0_01" class="java.beans.XMLDecoder"> - <object class="Section"> - <void property="identifier"> <int>123</int> </void> - <void property="departmentAbbreviation"> <string>COSC</string> </void> - <void property="courseNumber"> <int>111</int> </void> - <void property="sectionNumber"> <string>001</string> </void> - <void property="startYear"> <int>2005</int> </void> - <void property="startMonth"> <int>8</int> </void> - <void property="endYear"> <int>2005</int> </void> - <void property="endMonth"> <int>11</int> </void> - <void method="addStudent">

240

<string>3</string> </void> - <void method="addStudent"> <string>2</string> </void> - <void method="addStudent"> <string>1</string> </void> - <void method="addStudent"> <string>4</string> </void> - <void method="addMeeting"> - <object class="Meeting"> - <void property="dayOfWeek"> <int>1</int> </void> - <void property="endTime"> <int>1250</int> </void> - <void property="roomNumber"> <string>L322</string> </void> - <void property="startTime"> <int>1200</int> </void> </object> </void> - <void method="addMeeting"> - <object class="Meeting"> - <void property="dayOfWeek"> <int>3</int> </void> - <void property="endTime"> <int>1250</int> </void> - <void property="roomNumber"> <string>L322</string> </void> - <void property="startTime"> <int>1100</int> </void> </object> </void> </object> </java>

You can simplify the display somewhat (when you are using internet Explorer) by clicking the minus sign beside each line that begins <object class =

241

departmentAbbreviation).endMonth. } The statement Section s = (Section) d.0_01‖ class=‖java.readObject().add(st. <?xml version=‖1. this.0‖ encoding=‖UTF-8‖ ?> .clone()).readObject().theStudents.identifier = s. this.identifier. 242 . * @param d The XMLDecoder being used */ public void readObject(XMLDecoder d){ Section s = (Section) d.add(mt.endYear. click the plus sign. this.startMonth.courseNumber = s.startYear.departmentAbbreviation = new String(s.This gives the following file.5. } for (Meeting mt:s. The following method does the reconstituting.clone()). They tell us that the file contains an object of type Section and nothing else. for (String st:s.with a collection The archive contains all the instructions necessary to reconstitute a Section object.endMonth = s.startMonth = s.startYear = s.sectionNumber). /** * restore a Section from XML.theMeetings.beans. Using an XMLDecoder . this. To suppress the details.getMeetings()) { this.sectionNumber = new String(s. implements the instructions we placed in the archive to create a temporary object of the appropriate type and we copy that temporary object into our object. this.XMLEncoder‖> + <object class=‖Section‖> </java> The plus and minus signs are from the editor.<java version=‖1. this. click the minus sign which replaces the plus sign.getStudents()) { this. this.endYear = s. this.courseNumber. unlike when we were using object serialization. To see more details about the instance variables of an object.

Similarly. Using XML – summary This is only a brief introduction to using XML as a tool to provide persistence for objects.org.asp  A list of links and resources.altova. now would be a good time to do so. http://www.coverpages. Thus we need to use new String for Strings. Programming Style I have adopted the practice of having readObject (having an XMLDecoder object as a parameter) and writeObject (having an XLEncoder object as a parameter) methods in all my classes. There is much more to learn in this area. we actually have the ability.org/  XMLSpy. The corresponding unit tests are called testXMLSerialization and testXMLDeserialization.html Besides providing persistence. we ensure the object contains its own elements. primitive datatypes. if I had covered the previous chapter.com/  A collection of XML resources and tutorials.org/XML  XML.w3. The code above shows how to deal with collections which are lists or sets.xml. What about maps. not just references to the elements of the temporary copy. Online sources you may wish to explore include the following.org/  An O‘Reilly (a publisher of well-received computer science books) website on XML. The Map. I find it useful to use the similar names for similar methods.zvon.com/xmlspy. The corresponding unit tests are called testObjectSerialization and testObjectDeserialization. and the clone method for the Meeting objects. http://www. Java does not get confused. We simply use an assignment statement for them.org/  ―The Guide to the XML Galaxy‖.While copying elements from the temporary copy into our object. XSL is a stylesheet 243 . As these methods have different signatures. The other instance variables are numbers. found at http://www. to present our saved information in many different ways. I have readObject (having an ObjectInputStream object as a parameter) and writeObject (having an ObjectOutputStream object as a parameter) methods in all my classes.w3schools. and then reconstruct the map. http://www. http://www. through the use of a technology called XSLT.xml. http://xml. if we had any? One possible solution is to save each key-value pair.  The World Wide Web Consortium. http://www. If you have not implemented the clone method for Meeting.com/xml/default.Entry interface provides an easy way to retrieve the key-value pairs.

start by exploring the Java IO tutorial at http://java.sun. Many will include this topic in an introductory course but I have chosen to omit it. Now that we know how to create classes. If you are interested in this subject.language for XML. this is a third-year or fourth-year course. If you are interested in this subject. Summary This chapter covered what is perhaps the most-advanced topic in this book. 244 . start exploring Java Database Connectivity at http://java. This is definitely a topic better left to another course.com/javase/technologies/database/index.com/docs/books/tutorial/essential/io/index. Persistence via databases There is another option to providing persistence. a language for translating one XML document into another. and how to persist them.html. At Okanagan College. XSLT is XSL Transformations. by writing data into a series of traditional files. In particular. Persistence via traditional files There is yet another option to providing persistence. we need to see how to build data entry screens. This topic is much too complicated to consider in an introductory course. But it is a topic which will become more and more important as the role of XML increases.sun. by writing data into a database. it is time to look at how we allow the users to provide the data to create classes.

Implement the XML serialization of a Sighting. Of course. In previous chapters.com/javase/technologies/database/ 2. 3. we discussed modelling a bank account. Explore the topic of Scalable Vector Graphics. if this were a real model. Check your knowledge of XML serialization by using it with some of the other classes we have in our college model.Exercises 1.sun. Implement the clone method in the Student and Meeting classes. you would need to implement XML serialization for all of the classes. A good place to begin is http://www. Implement the XML serialization of a YardList.org/Style/XSL/ Explore the topic of using databases to persist Java objects. 4.org/Graphics/SVG/ Explore the topic of XSL and XSLT.w3. You will need it for the Student class when you use XML to persist the College class. In previous chapters. Implement the XML serialization of a Transaction. 5. A good place to begin is http://www. we discussed modelling the sightings a birder makes. A good place to begin is http://java. Implement the XML serialization of a BankAccount. 6. Remember that we have about 10 different classes from which you can choose. 245 . 7.w3.

246 .

You may omit these three chapters should you wish.Creating a GUI – Data entry screens. no buttons. I disagree. and no labels. However. While BlueJ uses windows and buttons. Introduction You may have noticed that the way we have been running our program is not the way you normally run a program. Use Swing components to create data entry screens Describe some of the considerations involved in data entry screen design Describe the role of a layout manager in creating data entry screens Use a layout manager to create data entry screens Use ActionEvents and ActionListeners Use InputVerifiers Warning to the reader This chapter and the two following it contain information which some people feel should not be in an introductory course. the code we have been creating has no windows.Chapter 14 . We need to develop a way in which the program can present a prettier face to the world. since we have been discussing saving and retrieving objects. After all. We need to explore the world of the graphical user interface. part 1 Learning objectives By the end of this chapter you will be able to:        Describe the parts of a Graphical User Interface.‖ 247 . I feel we should also look at how the objects receive their values in the first place. they won‘t always have their values defined in unit tests. An alternative name which is becoming common is ―user experience.

JTextField. to the maximum degree possible. or AWT) contained widgets which used code that was dependent on the processor you were using. JButton.  Buttons. The major parts of a GUI are:  A frame which contains all the pieces of the interface. 248 .  Panels. ―A placeholder name for any unspecified device or good‖ and ―a component of a graphical user interface that the user interacts with.‖ The two names are actually related. which allow you to make zero or more choices from a collection.  Labels. and checkboxes‖. and JRadioButton. JMenuItem. which identify data you should provide. To quote from the documentation. In case you missed it. ―Widget‖ is a generic term.  Textboxes. Even within Windows. radio buttons. rather than refer to ―labels. which provide a space where you provide data. The toolkit we will use is called Swing. it provides a specific style of widget. The toolkit you use to build a GUI provides the widgets.swing package. which allow you to make a single choice from a collection. which models that real world. JCheckBox. which provide a way to enter commands using a mouse or other pointing device. and JPanel. this package ―Provides a set of "lightweight" (all-Java language) components that.GUI A graphical user interface (usually abbreviated GUI and pronounced ―gooey‖) is one way by which we can enter data that exists in the real world into the program we have created. which divide the interface into logical sections. but it also provides a ―look and feel. I found two appropriate meanings. the widgets mentioned above are called JFrame.  Checkboxes. and different versions of Windows have a different look and feel. you might simply call them widgets. JPanel. In addition to these widgets we will (in later chapters) use JApplet. These parts are standard (although the terminology may change somewhat) regardless of the language you are using to create the GUI. work the same on all platforms. and is available in the javax. Windows programs have a different look and feel from those designed to run on a Macintosh. JMenuBar.‖ An earlier toolkit (Abstract Window Toolkit. JLabel. GUIs are built using a toolkit of predefined widgets. the widgets in Swing all have names beginning with the letter J.‖ That is. which helps you position all the parts of the interface. JMenu.  Radio buttons. and  A layout manager. Within the Swing toolkit. When I looked up the word in Wikipedia (on 2006-05-23). some progress bars have square ends while others have rounded ends. with several meanings.

Layout managers are not widgets. neatness counts. The left and right sides of a screen should be balanced with approximately the same number of visible widgets and the same amount of whitespace (the background) on each. When you are colour-blind.     Layout managers Some of the rules above affect the positioning of widgets within your frame. but garish is not nice. which we will explore in the next chapter.  Colours are nice. It also means that a product designed for international use should be customizable. The Wikipedia article on color blindness goes into a great deal of detail on this subject. A layout manager helps us to follow these rules. should use standard terms. Balance is good. so pay attention to the colours you use. Java is designed to run on many different operating systems. Help is the last. What is a layout manager? To once again quote the Java tutorial. Columns are good. Some HCI considerations HCI is an abbreviation of Human-Computer Interaction. the field involves decisions you should consider when building an interface which will be used by a person to interact with a computer.org/. it confuses people. SIGCHI. and top to bottom. Some prefer to call it CHI. A cluttered screen is not good. Your mother was right. It also means that those rules don‘t apply when your market is a culture that is not Western. Menus. random (or non-columnar) arrangements are bad. and they should be in standard places. particularly men. a layout manager ―[d]efines the interface for classes that know how to lay out Containers. It‘s okay when the top of the screen contains more than the bottom. so the GUI for your program should respect that.sigchi.  Most Western cultures read from left to right. and any buttons should be at the bottom. are colour-blind.) Whatever the abbreviation. (One such group is the ACM‘s Special Interest Group on Computer-Human Interaction. File is the first item on a menu. you may not see colours the same way others see them. Commonly.‖ A container is something (like a JPanel or a JFrame) into 249 . Many people. A common problem is an inability to distinguish between red and green. Here is a brief list of some of the HCI issues you should consider. That means that the important information a user must enter should be at the top. Don‘t present an interface suitable for a Macintosh unless the computer actually is a Macintosh. http://www.

South. While this layout manager is often used for widgets in a single line. the rectangles will be the same size. it will also serve for multiline layouts. and allows you to place widgets in each. West. or a chess game. if you have a JFrame called jf and you use GridLayout jf. place the buttons on your screen in the South region. East. and a layout manager controls the placement of those widgets. If there are too many widgets on one line. widgets may move from one line to another. Java provides a couple of choices. GridBagLayout is useful when you are creating a more complicated screen. including other containers. Because the rectangles are the same size. GridLayout might be useful should you be creating a Minesweeper -clone. Again. BorderLayout breaks its container into five regions. Of course. but it is very complicated to use. a calculator. For example. FlowLayout is one of the simpler layout managers. or at fixed percentages from the left and top of the surrounding container. You will find the screen divided into 20 small rectangles. all of the same size. 250 . a ® telephone. It can be useful if you are placing checkboxes beside each other. This can be very useful when you are placing a series of buttons side-by-side. and Center regions. Of course. It divides the frame into equal-sized rectangles. and that doesn‘t lend itself to the type of GUI we will be building.which you can place widgets. for example. Consider the buttons on the left side of the main BlueJ window.setLayout(new GridLayout(5. Ideally. FlowLayout also works for columns of widgets. It places its widgets in left-to-right (or right- to-left. the next widget will simply continue onto the next one. should you choose) order. I prefer a layout manager which lets you place widgets in relation to one another. we won‘t be using GridLayout here. This can be useful. We will use this layout in a later chapter. There are many different layout managers. some very simple and some very complicated. We will use FlowLayout only in special situations. I‘ll bet they are laid out using a FlowLayout layout manager. which we can conveniently place in the North. (Search the web for Java GUI builder to get an idea of what is available. five rows each containing four rectangles.) GridBagLayout is considered the most complicated layout manager. 4)). You might consider using GridLayout to divide the frame into a single column of rectangles. where we design a screen that has three sections. and Center. North. South. if you resize the container. you will find a tool which lets you draw the screen and then creates the appropriate Java code for you. This could be confusing for many of the people using your GUI.

google. One layout manager. if you want. The experience of laying out a GUI yourself is something everyone should do at least once. A more-detailed explanation about how this layout manager works is at http://www.html While this layout manager has many features. 251 .google.‖ This and the subsequent two chapters will use the layout manager from Google. Preferences.4. In fact. Java also provides the SpringLayout class. ―Due to the painstaking nature of writing layout code by hand. GroupLayout. A jar file contains compiled Java classes. if only to understand the underlying principles. Navigate to the jar files. ―RelativeLayout is a free layout manager for Java SE 1. simply by providing a new library which implements that feature. layout manager is available from http://code. it is also a little challenging to use. and virtually any interface you can imagine can be easily created this way.com/p/relativelayout/.onjava. like SpringLayout. Click one and then choose Open. and GridBagLayout. That‘s why there are so many layout managers. The webpage describes the layout manager using these words.GroupLayout is described in the Java tutorial as ―… a layout manager that was developed for use by GUI builder tools.2). everyone has his or her own idea of the way it should be done. To let BlueJ know that the jar files are available. you can open it with a standard compression program. which matches the way I think but is not supplied by Sun. note where you save them. Rather than relying on grids or nested boxes.com/p/relativelayout/. Libraries. However.0 and higher (with limited support for Java 1.‖ One of the strengths of Java is that you can add new features to it. This turns out to be a much more intuitive way of going about it. but it can also be used manually.‖ Yes. it is strongly recommended that you use the SpringLayout layout manager combined with a builder tool to lay out your GUI.com/pub/a/onjava/2002/11/27/layout2. choose Tools. Choose Ok. but easier-to-use. The name appears in the list of libraries. described several years ago at http://www. A similar. Installing the RelativeLayout layout manager To use this layout manager. Repeat for the other. you need to download two jar files from http://code.com/pub/a/onjava/2002/09/18/relativelayout.onjava.5. there are builder tools which will assist us in laying out a GUI. Choose Add. RelativeLayout lets you lay out components relative to each other and the window that contains them. You can think of it as a zipped file of classes.html?page=1. we won‘t use them here. However. using this layout manager requires attention to detail. is RelativeLayout. but the documentation for this class clearly advises against writing code using SpringLayout.

so I can refer to its documentation. what it means is ―You can‘t use RelativeLayout until you restart BlueJ. Preferences. You will want to review the website cited above to have some idea how to use RelativeLayout and its bindings (or constraints. choose Tools. and JTextFields in a second column providing space to enter the data. just as I do with all other Java documentation. it is being used simply as a teaching device. Download the jar file. Creating a data entry screen For our first data entry screen we should begin with a simple example.A message box appears. what we will be doing is identifying widgets and then positioning each in terms of the container and/or the other widgets in the container. which has the fewest instance variables? I think MyDate provides a good example of the process of creating a simple GUI. Perhaps it would look something like this. Actually. RelativeLayout is shown as being available.‖ So exit from BlueJ and restart it. We don‘t need the source code (unless we are curious) but we need the documentation which comes with the source code. JLabels in one column identifying the data to enter. Yes. Libraries again. Which is our simplest class? That is. 252 . the one that contains the source code for the layout manager.) To summarise. Should you be a cautious person. How the data entry screen should appear How should our data entry screen look? Let‘s make something simple. you should download a third jar file. Note that this GUI would not be part of a real program. I unzipped mine and saved it somewhere I could find it again.

swing. Can you spot the other errors? There at least two.*.matrix. import edu. The second provides the AWT events to which we can respond. import java. here are the additional import statements we need.*. import edu.cmu. import javax. These are ―better‖ widgets than those in the Abstract Window Toolkit.relativelayout.event.*.*.relativelayout. More details on events will be given later. Import statements To use the RelativeLayout layout manager. To use Swing components.There are several things wrong with this illustration. This provides the layout manager and its associated components. here are the import statements. 253 .awt. or AWT. The first of these additional statements provides the widgets we will be using. The first is that there is probably too much space between a label and its textfield.cmu.

As we are using a relative layout. // add the constraints to the collection labelYearConstraints. the constraints are relative to the JFrame or to other widgets. and exit buttons). // create the first label JLabel labelYear = new JLabel("Year – four digits"). // create a BindingFactory to create various // Binding objects (constraints) to control the // position of the widgets BindingFactory bf = new BindingFactory(). and the JTextFields. Binding leftEdge = bf. the default is the left edge // of the frame. first create the JFrame and attach a layout manager to it. // Bindings (constraints) // leftEdge is relative to the last leftMargin // established. and minimize.addBinding(leftEdge). 254 . Finally. maximize.the JFrame (including a title bar. the JLabels. jf. the labels (implemented as JLabels). For each widget you wish to add to the JFrame. // ditto for top edge. create the widget and the constraints which specify its location. To summarise the process. attach the widgets to the JFrame and the constraints to the layout manager. // a collection of constraints RelativeConstraints labelYearConstraints = new RelativeConstraints().setLayout(new RelativeLayout()).topEdge().Creating the JFrame We begin by creating what we see . Binding topEdge = bf. The method is explained line-by-line on subsequent pages.setDefaultCloseOperation( JFrame. // create a RelativeConstraints object.leftEdge(). Below is a method to create the JFrame.HIDE_ON_CLOSE). and the textfields (implemented as JTextFields). */ public static JFrame buildFrame() { // create a frame JFrame jf = new JFrame("Enter MyDate"). /** * create a JFrame to allow data entry. // and set its layout manager jf.

labelDayConstraints). labelYearConstraints).addBinding(topEdge). labelDayConstraints. labelMonthConstraints. // textfields will begin 200 pixels from the // left edge of the frame bf. RelativeConstraints labelMonthConstraints = new RelativeConstraints().addBinding(leftEdge). labelDayConstraints. leftEdge = bf. jf.topAlign(labelYear). 255 .below(label2). // add the label and its constraints to the // frame jf.setLeftMargin(200).below(label1).add(textYear.addBinding(leftEdge).labelYearConstraints. labelMonthConstraints). // this Binding makes the two labels share // a common left edge leftEdge = bf. jf.addBinding(topEdge).add(labelDay.addBinding(topEdge).leftAlignedWith(label2).leftEdge(). // top edge is aligned with its label topEdge = bf. textYearConstraints. // firstTextfield (year) JTextField textYear = new JTextField(4). topEdge = bf.leftAlignedWith(label1). textYearConstraints. // and place it below the first // using just the first statement below has the // effect of making the left edge at the edge of // the Frame. // third label JLabel labelDay = new JLabel("Day – two digits"). jf.addBinding(topEdge). labelMonthConstraints.addBinding(leftEdge).add(labelYear.add(labelMonth. // second label JLabel labelMonth = new JLabel("Month – two digits"). RelativeConstraints labelDayConstraints = new RelativeConstraints(). topEdge = bf. leftEdge = bf. textYearConstraints). RelativeConstraints textYearConstraints = new RelativeConstraints().

add(textMonth.// ditto for a second textfield (month) JTextField textMonth = new JTextField(2).setVisible(true).isVisible()). leftEdge = bf. } Making the JFrame visible Finally. 300)).topAlign(labelMonth).setLocation(100. 100). textMonthConstraints). here‘s a method to create and make the JFrame visible. textMonthConstraints. jf. /** * show the Frame. leftEdge = bf. System. box. // done return jf.leftAlignedWith(textYear). while (box.addBinding(leftEdge).add(textDay.leftAlignedWith(textYear). */ public static void showFrame() { JFrame box = buildFrame(). RelativeConstraints textDayConstraints = new RelativeConstraints(). textDayConstraints.setPreferredSize(new Dimension(500.addBinding(topEdge). topEdge = bf. } 256 . box. textDayConstraints. box.addBinding(topEdge).exit(0). textMonthConstraints.addBinding(leftEdge). // ditto for a third textfield (day) JTextField textDay = new JTextField(2). jf.topAlign(labelDay).pack(). textDayConstraints). RelativeConstraints textMonthConstraints = new RelativeConstraints(). box. topEdge = bf.

It also tracks the relationship between widgets. The Java tutorial says ―A frame.‖ jf. Thus it will be available quickly should we need it again. We‘ll give a few lines of code and then explain them. Notice that building a frame and displaying it are done in two separate methods.setLayout(new RelativeLayout()).‖ I see a BindingFactory as a class which creates bindings to our specifications.setDefaultCloseOperation(JFrame.‖ The JFrame we create has the title ―Enter MyDate. is a window that typically has decorations such as a border. The RelativeLayout layout manager will interpret those rules for us. Applications with a GUI typically use at least one frame. BindingFactory I see a Binding as an instruction which the layout manager uses to control the positioning of widgets. and buttons for closing and iconifying the window. The package documentation says ―A Binding represents a dependency of some component's position on the position either of another component or of the surrounding container. The layout manager jf.HIDE_ON_CLOSE). implemented as an instance of the JFrame class. The JFrame Let‘s begin with the creation of the JFrame. Associated with the JFrame are the rules that govern the placement of widgets in the JFrame. You have seen frames whenever you have used a computer with a windowing system. as implemented by a layout manager. the JFrame will hide itself. a title. When you click the X button in the top right. final JFrame jf = new JFrame("Enter MyDate").Explaining the code Let‘s examine these methods in some detail.‖ // create a BindingFactory to create various // Binding objects (constraints) to control the 257 . The package documentation says ―A factory for quickly creating Bindings to lay out simple interfaces.

) If you had many widgets. In the code above.topEdge(). The most common bindings are those which specify the top edge of the widget and left edge of the widget. We create two bindings to describe the position of the JLabel. Dewey. The labels Continuing through the method. Create the bindings related to the position of the widget. we usually position widgets relative to other widgets. The way in which we create and place widgets is the same for all widgets. and Louie. o o o Create a widget. the default is the left edge // of the frame. and so on.leftEdge(). When you look in the documentation for BindingFactory. Since this is a relative layout manager. there should be a label. and Add the widget and those bindings to the container‘s layout manager. beta. // ditto for top edge. after Donald Duck‘s nephews. The label Bindings // Bindings (constraints) // leftEdge is relative to the last leftMargin // established. BindingFactory has two constructors you can use. you‘ll find there is a default BindingFactory object and you can access it. Binding leftEdge = bf. Thus. BindingFactory bf = BindingFactory. we begin to create and place widgets. For each piece of data we wish to enter. This is different from the Singleton pattern. delta.getBindingFactory(). gamma. But one or more widgets 258 .// position of the widgets BindingFactory bf = new BindingFactory(). Binding topEdge = bf.) But neither naming strategy is a good one. Singleton allows you no access to the constructor. If you had only three widgets I suppose you could name them Huey. I suppose you could name them after the letters in the Greek alphabet (alpha. the last statement above could be replaced with this one. we create a JLabel containing the words ―Year – four digits‖. (Perhaps it‘s time for a joke about getting your ducks in a row. starting with a label. // create the first label JLabel labelYear = new JLabel("Year – four digits").

Similarly any negative number represents measurement to the left or up.must be anchored to the frame itself. Unfortunately. we add the label and its collection of bindings to the frame. // add the constraints to the collection labelYearConstraints.addBinding(topEdge). This could be modified. you could modify it if you wanted more or less space between the widget and the edge of the form. 10% of the way down the JFrame. 259 . // add the label and its bindings to the // frame jf. and their width expands to display the contents.add(labelYear. JLabels have a default height. The second binding positions the top edge of the JLabel a certain number of pixels down from the top edge of the frame. Also. Now that we have our first widget anchored relative to the frame. If we specify numeric pixel values (as we will soon). This margin is the default value. a positive value represents measurement to the right or down. note that we are positioning the widget in an absolute position. the layout manager will process all the bindings and position the widget properly. Once we have created the bindings for the label. we place those labels in a collection. The first binding (constraint) positions the left edge of the JLabel a certain number of pixels from the left edge of the JFrame. We use this first JLabel as the anchor and then position other widgets relative to it. labelYearConstraints.addBinding(leftEdge). // create a RelativeConstraints object. we can place the other widgets relative to the anchor. it may be better to position it. 0) in this measurement system. See the setLeftMargin method within the BindingFactory class. When the JFrame is made visible. labelYearConstraints). We could create bindings describing the height and width of the JLabel but there is no need to do so. // a collection of constraints RelativeConstraints labelYearConstraints = new RelativeConstraints(). Finally. say. The upper left corner of the JFrame is the origin (or 0. depending on the direction of motion. it does not appear that this layout manager supports that method of placement.

Finally we add the label and its collection of bindings to the frame. after all. JTextField yearText = new JTextField(4). so is omitted here. We need to create a binding describing its top edge.addBinding(topEdge). in this case. Textfields Once we have the JLabels in position.The other labels JLabel labelMonth = new JLabel("Month – two digits"). jf. and don‘t change all the names we need to change. in which you will enter data. The code to create the third JLabel is almost identical to the code for the second. topEdge = bf. saying.addBinding(leftEdge). this one representing the month. This problem usually comes when we are sloppy in our cutting and pasting. the BindingFactory determines the precise value. How would you do that? Finally. whenever we provide too little information or inconsistent information about the positioning of a widget.add(labelMonth. via InconsistentConstraintExceptions and AmbiguousLayoutExceptions. thus leaving one of the bindings attached to the wrong widget. Now we create another JLabel. This width of four characters is based on the average width of the characters in the font you are using. labelMonthConstraints). labelMonthConstraints). labelMonthConstraints. We create the JTextField. How much below is a based on the height of the label.below(labelYear). We create a second binding. jf. we create the collection of bindings. we deal with the JTextFields. Note that some people prefer to have the right edges of the labels line up. ensuring its left edge lines up with the left edge of the previous label. labelMonthConstraints. 260 .add(labelMonth.leftAlignedWith(labelYear). leftEdge = bf. The layout manager will tell us. giving it enough space to accommodate four characters. RelativeConstraints labelMonthConstraints = new RelativeConstraints(). that it is below the year JLabel.

The first step is to create a JFrame and associate a layout manager with it. we return it to the calling method. we place the other two JTextFields on the content pane. textMonthConstraints. Note that RelativeConstraints contains two methods for adding Bindings. Summarizing building a data entry screen This is a simplified version of the process. Finally. Their top edges are aligned with the correct labels.leftEdge(). textMonthConstraints. we add the textfield and its collection of bindings to the frame. We have used the first. // textfields will begin 200 pixels from the // left edge of the frame bf. leftEdge). The second step is actually a series of steps.a ―W‖ is wider than an ―I‖. we could have used textMonthConstraints. textMonthConstraints). In the same way. repeated for all widgets. and add them to the textfield‘s collection of bindings.topAlign(labelYear).add(textMonth. But there is also addBindings which allows us to add more than one Binding. leftEdge = bf. a font is the combination of typeface and point size. The order in which we add the bindings does not matter. the width of a label is determined by the typeface and point size. We create the appropriate bindings. // top edge is aligned with its label topEdge = bf.  Create a widget which we wish to place on the frame.setLeftMargin(200). 261 . and their left edges are aligned with previous textfields. Thus. Other textfields Similarly. Done! Once we have created the JFrame.addBindings(topEdge.addBinding(topEdge). jf. A more complete version appears in the next chapter. which adds one Binding to the collection.addBinding(leftEdge). Thus the actual width (in pixels) may vary depending on the typeface and point size you are using. RelativeConstraints textMonthConstraints = new RelativeConstraints().

If you are using a resolution lower than this. as something else becomes visible. We have not specified its location of the screen. 300)). If you are using a resolution larger than this. The showDataEntryFrame method does that. your JFrame will occupy less of the screen. Position and size the frame box. so the JFrame will be approximately 1/3 the width of the screen. your JFrame will occupy more of the screen. We specify its size (500 pixels wide by 300 pixels high.setPreferredSize(new Dimension(500. Add the widget and its collection of bindings to the frame. Simply change the parameter to false. 262 . I‘m running my screen at 1680 by 1050 resolution. And then we make it visible. We specify the location of the top left-hand corner of the frame (100 pixels in from the left edge of the screen.setLocation(100. 100). box. You might say we have created the blueprint for the JFrame and now we need another method to size and position it. Displaying the frame Note that we have not yet specified the size of the JFrame. Make it visible box. and 1/3 its height.Dimension.   Create the bindings for the widget. There may be times when you wish to make it invisible. 100 pixels down from the top of the screen). As I write this. Create a collection for the bindings and add the bindings to the collection. First we create the JFrame using the method we just finished examining. We have not even made it visible. and to make it visible.awt. giving it the name box. Let‘s examine its statements.setVisible(true).) You‘ll need another import statement here. import java. Create the frame JFrame box = buildDataEntryFrame().

The following statement gives a specific location on the screen. box. should the person using your program not like the size or position of your frame.setLocationRelativeTo(null). of course. having the left edge at 700 pixels may mean that part of the frame is invisible since it is off your screen. Exit System.setLocation(700. the program exits gracefully.isVisible()) {} The while loop simply ensures the JFrame remains visible until we click the X in the top right corner to dismiss the frame.Keep it visible while (box. This is something we have given up in favour of a simpler-to-use layout manager. 400). and run the showDataEntryFrame method. How do we change the position of the JFrame when it appears? First. placing the JFrame near the top left corner of the screen. and the top of the JFrame is 400 from the top of the screen. the mouse (or other pointing device) is available to resize and reposition it.exit(0). Of course. how do you place a widget 10% of the way down the JFrame? My reading of the documentation for this layout manager tells me that we cannot do this. And once the frame disappears. Answering some questions How do you place a widget without using pixel numbers? For example. Normally. Depending on your screen resolution and the size of the frame. Displaying the frame Compile MyDate. box. 263 . the following method call places the frame in the centre of the screen. Once that is done. I would use setLocation with small values (like 100) for the arguments. we must set the preferred size of the JFrame. The left edge of the JFrame is 700 pixels from the left edge of the screen. right-click the class in the class diagram.

labelYear. you may wish to remove the hint from the label and add this statement to your method.setExtendedState(Frame. We first specify the mnemonic. When you press mnemonic.Frame class if you have not already done so. the cursor will move to the JTextField.setLabelFor(textYear).VK_Y).Is it appropriate to have the labels contain prompts about the corresponding JTextFields? No. textYear.four digits"). I feel it is not a good idea to start a frame full-size. Should you wish to ignore this advice (and many programs do). Then specify the JTextField with which the JLabel is associated. and what about editing the data provided? 264 . the letter in the JLabel caption which is to be underlined (if your interface underlines mnemonics) and which will function as a hot-key. box.MAXIMIZED_BOTH). You just want to press a combination of keys which will take you to the correct widget. and then use the statement box. intruding on. The documentation of the KeyEvent class lists all the mnemonics you may use.setToolTipText ("Please enter the year . indeed obscuring. It‘s much better to use JToolTips. Hot-keys allow you to do this.Frame class and then use this statement. small balloons of text that appear when the mouse hovers over the JTextField. not by tabbing through the others. import the java. There are two biggies – what about buttons (did you notice they were missing from the frame we built?). But these are minor questions. How do we use hot-keys to move to a specific JTextField? Sometimes. labelYear.setExtendedState(Frame.setDisplayedMnemonic(KeyEvent. whatever a person is doing. It‘s rude. not by taking your hands off the keyboard to click the one you want. you have many widgets on the screen and you wish to move to a specific one.awt. Here we assign Y as the mnemonic representing year. For example.ICONIFIED).awt. If you wish the frame to start minimized. import the java. it isn‘t. and the How do I start the frame full-screen? Minimized? In general.

BOTTOM. Cancel button Let‘s create the Cancel button first. Direction. Edge.RIGHT.Buttons The JFrame we created is quite unusual. or it may be retrieved from a resource bundle. 25. but it has no JButtons. 10. The button is placed near the bottom of the frame.ABOVE. We would expect at least an OK button and a Cancel button. Direction. It has JLabels and JTextFields.LEFT. And place the bindings in the collection.BOTTOM. 265 . When we create a button.addBinding(buttonCancelRight).RIGHT. Binding buttonCancelBottom = new Binding(Edge. In particular. off to the right. The bottom edge of the button is 10 pixels above the bottom edge of the frame. o Create a widget. Create the button JButton buttonCancel = new JButton("Cancel"). RelativeConstraints buttonCancelConstraints = new RelativeConstraints().addBinding(buttonCancelBottom). jf). we provide its caption. the right edge of the button is 25 pixels to the left of the right edge of the frame. Create the button’s bindings Binding buttonCancelRight = new Binding(Edge. and o Add the widget and those bindings to the container‘s layout manager. o Create the bindings related to the position of the widget. Notice how the parameters in the method calls match the wording in the English statements. Note the idiom we have seen throughout this chapter. This caption may be specified here. buttonCancelConstraints. jf). Edge. buttonCancelConstraints. Create the collection to hold the bindings.

Edge.addBinding(buttonOkayTop). jf.setDefaultButton(buttonCancel).addBinding(buttonOkayRight).LEFT. buttonCancelConstraints). // tops of the two buttons are aligned Binding buttonOkayTop = bf. buttonOkayConstraints. the button which will be deemed to have been clicked when you press .VK_C). Create a mnemonic Buttons have mnemonics too.add(buttonCancel. Place it to the left of the ―Cancel‖ button. 10. At this point. 266 . Button action What should happen when we click the Cancel button (or press )? The same actions as when we click the X button to exit the JFrame. But when we have many (two or more) buttons the default button is usually the one which causes the least damage when it is pressed accidentally.getRootPane().topAlign(buttonCancel). This is exactly the same process we used with all our other widgets. we have only one button so of course it is the default button.Add the button and its bindings to the frame jf. The default button And one of the buttons should be the default. in this case the letter C.setMnemonic(KeyEvent. buttonCancel). buttonOkayConstraints. RelativeConstraints buttonOkayConstraints = new RelativeConstraints().LEFT. // right edge of the button is 10 pixels to // the left of the right edge of buttonCancel Binding buttonOkayRight = new Binding(Edge. How we make this happen is shown below. The OK Button We use similar statements to create an ―OK‖ button.RIGHT. Direction. buttonCancel.

an ActionEvent occurs. What should happen when we click the cancel button? For now.Alternative layout managers We have used RelativeLayout to place these buttons. using FlowLayout. ActionListener buttonCancelActionListener = new ActionListener () { public void actionPerformed(ActionEvent e) { // do something } }. When a button is clicked. The ActionListener will be notified each time the JButton is clicked. ActionEvents. let‘s have it just tell us that it has been clicked. When a JTextField gains or loses focus. When an ActionEvent occurs. A JTextField which has focus allows input. for each of our buttons. Creating an ActionListener We need to create an ActionListener. What does an ActionListener do? When an action occurs. buttonCancel. the ActionListener notices.addActionListener(buttonCancelActionListener). an ActionEvent occurs. and has the responsibility of doing something in response to the ActionEvent. Linking an ActionListener to a JButton We need to connect the ActionListener to each JButton. an object which processes ActionEvents. Let‘s begin with an ActionListener for the cancel button. the component containing the widget is notified. and ActionListeners How do we tell that a button has been clicked? This leads us to the world of ActionEvents and ActionListeners. We may need them for our textfields. A later example will show how to place them within a JPanel. Replace // do something 267 .

What does an ActionListener do.INFORMATION_MESSAGE). Find the line where you declared jf and add the word final to it.‖ Without going into the details of inner classes. The parameters to all setters and constructors should be final. JOptionPane. But we are not declaring a constant here nor are we working with a parameter. Now it reads final JFrame jf = new JFrame("Enter MyDate"). What happens? Nothing happens when you click the okay button (unless you thought ahead and gave it an ActionListener. right-click the class in the class diagram. as a promise that we will not change a variable within an inner class. continued? Compile MyDate. 268 . We have seen the word final before. we‘ll just follow its advice. "Clicked cancel". needs to be declared final. An informational message appears.showMessageDialog(jf. But it doesn‘t compile! The error message is ―local variable jf is accessed from inner class. We are using final in a different sense. "Cancel". The intent is that this should simply display a message for us. Go back through your code and ensure the parameters for your setters and constructors are final. in connection with the declaration of constants and as a promise that the method will not change the value of a parameter. This use of final as a promise is something Checkstyle checks and it may get upset with our setters and constructors.with JOptionPane.) But go ahead and give the okay button an ActionListener. Now click the button. I‘ll wait. and then click either JButton. run the showDataEntryFrame method. as a promise that the setters and constructors will not be changing the values provided to them.

setVisible(false). You probably should not be doing anything else while installing new programs. then the message is centred on the screen. A good example is when you are installing software. This may not be a good idea since it may not show a clear association between the parent and the message. How does the dialog appear and how is it related to the statement you copied? o The first argument to showMessageDialog is the name of the parent component. The message which appears will be centred on that component. Should the name be null. 269 . to close it. You should use modal dialogs when it makes no sense to allow you to continue without responding. This icon will change depending on the value of the fourth argument. o o o Behind the Cancel Button But we wanted the cancel button to cancel the frame. The second argument is the message which appears beside the icon. The fourth argument indicates that the message is one of information only. The dialog is modal. The third argument is the title which will appear in the message dialog frame. you must click the OK button within it before you can continue and do anything else with this application. Replace the showMessageDialog call in the ActionListener with jf. and will result in an information icon appearing in the message dialog frame.Note the different colours or shading in the titles of the two frames. not display a message.

we must cast to the // appropriate type to extract the contents String text = ((JTextField) input). month and day) have been provided.and the JFrame will no longer be visible when you click the cancel button. The main feature of an InputVerifier is a verify method. JOptionPane. We cannot check that the day JTextField is appropriate to the month (30 days hath September …) until all three JTextFields (year. Modern authors suggest that you not intercept keystrokes as they are typed.ERROR_MESSAGE). which accepts a JComponent as a parameter. 270 . The verify method will return true if it finds no errors with the data provided in the JComponent. We can check that the JTextFields contain only numbers. "Missing data". false if there is a problem with the data provided. Editing data There are two times as you are entering data when it may be appropriate to test it is reasonable. Thus showDataEntryFrame exits. // because an InputVerifer can be attached to many // types of Components. While this technique creates a snappier application.length() == 0) { // no data provided JOptionPane. It would continue running with some other frame visible and the invisible one (or ones) waiting their chance to reappear. We cannot check that the month JTextField contains only the numbers from 1 through 12 until the JTextField is complete. InputVerifier verifierYear = new InputVerifier() { public boolean verify(JComponent input) { int screenYear. A JComponent is the parent of the parent of JTextField. and you must remember to close the data entry frame eventually. "Need to supply a year". but you verify the contents of a JTextField as you attempt to leave it. This is done with an InputVerifier. and we do not know the order in which the data will be provided. Verifying year and month Here is the InputVerifier for the year. if (text. One is as it is being entered.getText().showMessageDialog(jf. In a normal application. the program would not terminate. the other is when an Okay button is clicked. it does use up memory. Why do we need both times? Consider the MyDateEntry frame.

Note the use of (new Integer(text). We attempt to make the conversion. } // end verify }. } // end catch return true. return false. // end verifierYear What could go wrong while entering a year? o You could neglect to enter anything. ″Year should be four digits in length.". // the data contains an integer.intValue()). Of course there is a method (intValue) to extract the underlying int.ERROR_MESSAGE). JOptionPane. 271 .intValue()) to convert a String into an int. The Integer class is a wrapper class for int. "Year contains non-numeric characters. // length = 0 try { // data was provided. }. o You could enter non-numeric data.return false. "Bad year". textYear. We have already used the Integer class in our discussion of autoboxing.ERROR_MESSAGE). catching an exception should it be unsuccessful.showMessageDialog(jf. return false. in the order listed. we must attach it to the appropriate widget. Is it an integer? screenYear = (new Integer(text). } } catch (Exception e) { JOptionPane. o You could enter a numeric value which is too small or too large. Once we have created the InputVerifier. The InputVerifier checks each. "Bad year". // is it reasonable? // reasonable is defined as between 1000 and // 9999 inclusive if ((screenYear < 1000) || (screenYear > 9999)) { JOptionPane.setInputVerifier(verifierYear). JOptionPane. it takes the primitive datatype and converts it to a class.showMessageDialog(jf.".

buttonCancel. // length = 0 try { screenDay = (new Integer(text). if (screenDay < 1) { // regardless of the month. "Bad day". "Day number is too small. and day have been // specified check maximum value for day int screenYear = 0. Test your data entry screen. how can you correct it? Hint. JOptionPane. Note that you cannot use the cancel button to exit unless a valid year has been provided. InputVerifier verifierDay = new InputVerifier() { public boolean verify(JComponent input) { int screenDay. An obvious exception to this generalisation would occur on a data entry screen which requires the entry of several dates. }. try { // do we have a year? 272 .ERROR_MESSAGE). if (text. But if you choose the cancel button.InputVerifiers are almost always associated with only one widget. JOptionPane. String text = ((JTextField) input). month. 0 or a negative // number is a bad day JOptionPane. an error message appears.showMessageDialog(jf. return false. return false. "Need to supply a day". Why does this happen? More importantly.ERROR_MESSAGE).intValue()). If you choose the X in the top-right corner. consider this statement. you are able to leave the data entry screen with no problem.setVerifyInputWhenFocusTarget(false). How is that for the name of a method? What does that method do? The InputVerifier for the month is similar and is left as an exercise. Verifying the day of the month The InputVerifier for the day of the month is a little more complicated since the upper limit for the day depends on the month and the year.showMessageDialog(jf. All the year fields could share the same InputVerifier. "Missing data".".length() == 0) { // no day has been provided JOptionPane. int screenMonth = 0. } // if the year.getText().

"Bad day".ERROR_MESSAGE).". if (screenMonth == 2) if (isLeapYear(screenYear)) // isLeapYear follows this method maxDays = 29. intValue().getText())). return false. // do no more day editing // screenYear or screenMonth is zero. JOptionPane. "Day number contains non-numeric characters.screenYear = (new Integer(textYear.showMessageDialog(jf. } // end too many } // end year and month provided } // end try catch (Exception e) { JOptionPane. return false.getText())).". "Bad day".ERROR_MESSAGE). intValue(). // end verifierDay 273 . // now we know the maximum number of // days in the month if (screenDay > maxDays) { // too many days JOptionPane. if ((screenMonth == 9) || (screenMonth == 4) || (screenMonth == 6) || (screenMonth == 11)) maxDays = 30. } // end verify }. } // end non-numeric return true. else maxDays = 28. // do we have a month? screenMonth = (new Integer(textMonth. JOptionPane. } catch (Exception e) { // some part of the date is missing. so // the following if statement will not be // executed } if ((screenYear > 0) && (screenMonth > 0)) { int maxDays = 31. "Too many days in the month.showMessageDialog( jf.

Note the isLeapYear method. First. embodying the logic necessary to decide when a year is a leap year (see. } Rather than writing yet another leap year routine. Don‘t forget the import statement.org/wiki/Leap_year). we attach this InputIdentifier to its widget.GregorianCalendar. is it appropriate?). and have seen how to create one simple data entry screen. In the next chapter. so we‘ll examine its data entry screen next. If so. and textDay variables as final. Course. this method checks that a year and month have been provided. 274 . http://en. /** * calculate if a year is a leap year. is it numeric? If so.setInputVerifier(verifierDay). Professor. College. textMonth. Data entry for other classes Using the ideas above. Summary In this chapter. * @param year The year which we are checking * @return true if so. Meeting.util. it determines the correct number of days in the month and compares the value provided to that number. and Address.The logic verifying the day is similar to that verifying the year and month (Is there anything provided? If so. we have focussed on the basics of creating data entry screens. textDay. we will see how to create more-complicated data entry screens. Student. for example.wikipedia. Most of these will be left as exercises for the reader. (as you see when you compile this code) you will need to declare textYear. Of course. import java. The logic for checking the upper limit is a little more complicated since it depends on the year and the month. I have chosen to use the GregorianCalendar class and its isLeapYear method. And yes. false if not */ public static boolean isLeapYear(int year) { return (new GregorianCalendar()).isLeapYear(year). Section has some interesting aspects. you can create simple data entry screens for the other classes which require them. Mark.

6. 8. students. but not associating it with a student and course just yet. Create a data entry screen for the Student class. Create a data entry screen for entering a species of bird. 10. Create a data entry screen for the College class. Explore the subject of ―look and feel‖. Create a data entry screen for entering a transaction. or courses. 275 . 5. Create a data entry screen for the Meeting class. including both the common and scientific name. Create a data entry screen for the Professor class. omitting the choice of the account to which the transaction applies.Exercises 1. collecting personal information but nothing on the sections and courses the professor teaches. Create a data entry screen for entering the personal information for the holder of the account. In the next chapter we will add the account. (Hard and maybe pointless) Use the GridBagLayout manager to recreate the data entry screen we have created in this chapter. In previous chapters we discussed modelling the sightings a birder makes. In previous chapters we discussed modelling a bank account. 14. Create a data entry screen for the Course class. but nothing about employees. collecting personal information. 13. In previous chapters we discussed modelling a bank account. Create a data entry screen for the Address class. 9. 3. What options do you have with the Swing toolkit? What are the differences between the options? What are some of the other layout managers you can use? When would you use each? Could you use any of them to create the data entry screen we have seen in this chapter? 11. 2. Which layout manager do you prefer? 12. but not collecting any information about the sections of the courses which are offered. 7. Complete the InputVerifier for the month textfield. Create a data entry screen for the Mark class. 4. but not registration information. but not associating it with a section just yet. It will allow you to enter its address and website.

055 (as of 2010-05-13) bird species seen in North America. It may be possible to use this list to make the data entry screen in this question redundant.bcfo.org).bsc-eoc. 16. In the next chapter we will add the species.org/. These include. you should know about the American Ornithologists‘ Union and their website at http://www. In previous chapters we discussed modelling the sightings a birder makes. This site makes available a list of the 2. the British Columbia Field Ornithologists (http://www. Create a data entry screen for entering a sighting. Find a GUI builder and use it to create a data entry screen.ca/) and Bird Studies Canada (http://www. 276 . omitting the choice of the species which was sighted. 15. you could perhaps link to the AOU site and choose from a list.aou.If you are serious about birding. for example. You should also know about your local birding groups.

It contains some labels.Creating a GUI – Data entry screens. JScrollPane. 277 . and a collection of buttons. The data entry screen we will create is shown below. They include lists of items. JList. But more complicated data entry screens are very common. some textfields. and some buttons. Building the Section data entry screen The data entry screen for a Section naturally divides itself into several portions: the course with which the section is associated. JPanel. additional Swing components are necessary. Let‘s see how we create these data entry screens. To build this screen. and JCheckBox components. the meeting times for the section. part 2 Learning objectives By the end of this chapter you will be able to:      Use Swing components to create complicated data entry screens Describe the role of a layout manager in creating data entry screens Use a layout manager to create complicated data entry screens Use ActionEvents and ActionListeners Use InputVerifiers Introduction The data entry screen we created in the previous chapter is relatively simple. including the JRadioButton.Chapter 15 . They include panels to separate portions of the frame. They include checkboxes and radio buttons.

Let‘s examine parts of the method necessary to build this screen. 278 . labels. and checkboxes associated with meeting times. textfields. I have omitted the border on the third panel because it seems to be superfluous. The bottom border of the second panel serves as a top border and the left. The first JPanel is the portion of the screen containing the course list and section number. and bottom borders of the frame itself serve as the left. The second JPanel contains the radio buttons. It is clearly separated from the rest of the screen by a border. a few statements at a time. The third JPanel contains the buttons. It also has a border.You can see the three JPanels in the image above. right. and bottom borders. right.

Create the frame
public static JFrame buildDataEntryFrame() { // create the JFrame. final JFrame sectionInput = new JFrame("Enter Section Information"); sectionInput.setDefaultCloseOperation (JFrame.HIDE_ON_CLOSE);

We have created the frame (In the previous chapter, I used the nondescript variable name jf. Here I use the more informative sectionInput.) and specified that it will hide itself when we click the X icon in the top-left corner of the frame. These statements are common to most data entry screens you create. Create a column of panels
// use the BorderLayout to create a column of JPanels. // Actually BorderLayout gives five sections of the // frame but we will not use the EAST and WEST. sectionInput.setLayout(new BorderLayout());

Recall that the BorderLayout divides the form into five regions, a central region and four surrounding regions. The comment notes this. Create the three panels
// create three panels for the frame // at the top - choose a course and enter a section // number // in the middle - meeting times // at the bottom - buttons JPanel topPanel = new JPanel(); JPanel middlePanel = new JPanel(); JPanel bottomPanel = new JPanel(); // and add the panels to the Box in the // correct order, from top to bottom sectionInput.add(topPanel, BorderLayout.NORTH); sectionInput.add(middlePanel, BorderLayout.CENTER); sectionInput.add(bottomPanel, BorderLayout.SOUTH);

The BorderLayout layout manager (imported from java.awt.BorderLayout. Don‘t forget the import statement!) divides the frame into five sections. We are using three sections and our panels will expand to fill those section. The EAST and WEST sections will still exist, but will be empty (and disappear). While I like the RelativeLayout layout manager, there are times where it is the best tool and times where other layout managers are the best tools. I am trying to show you other layout managers

279

whenever their use is appropriate. As we build this frame, we will also use the BoxLayout and the FlowLayout layout managers. Notice that we have created the three JPanels and placed them within the frame, but we have not yet specified what the JPanels contain. We‘ll do that in a moment, starting with the top JPanel. Populate the top panel
// the top panel contains two Boxes, one containing a // JLabel and a JList to choose the course, // the other containing a JLabel and a // JTextField to enter a section number Box courseSelector = Box.createVerticalBox(); Box sectionSelector = Box.createVerticalBox();

Looking back at the sample screen, you‘ll see that the top JPanel contains two columns of Objects. A Box is a container into which you can place Objects either vertically or horizontally. More correctly, a Box is a container which uses the BoxLayout layout manager, a manager which stacks widgets on top of each other, or beside each other, depending on the orientation of the Box. When you have columns of widgets, it may be easier to use a VerticalBox to contain and position them than to use some other layout manager. Like all other advice I give here, take this with a grain of salt. You‘ll soon see that I don‘t always follow my own advice.

// courseSelector Box JLabel courseLabel = new JLabel("Course"); courseSelector.add(courseLabel); // the course JList, a list of items from which // the user can choose. First prepare // some default values, stored in an array. // These values should come from a database, but we // don‟t know how to use databases yet so we will // juts provide some value here String[] data = {"COSC 109", "COSC 111", "MATH 139", "NTEN 112", "BUAD 123", "PSYC 123", "GEOG 111", "POLI 100", "BUAD 123", "BUAD 128", "BUAD 111"}; // create the list box and place the contents // of the array in the JList JList coursesList = new JList(data); // allow user to make only one selection coursesList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION);

280

// embed the JList in a JScrollPane to allow // for scrolling JScrollPane courses = new JScrollPane(coursesList); // add the JScrollPane to the panel courseSelector.add(courses); // done with courseSelector Box

So the courseSelector Box contains a JList (which scrolls, and allows only one choice to be made). We don‘t have a database of courses, which we would normally use to populate the JList. Instead, we simply create an array containing some courses, and use that array to initialize the JList, using enough courses that we will see the scroll bars appear. We have seen arrays before, and will see them again.
// sectionSelector Box JLabel sectionLabel = new JLabel("Section"); sectionSelector.add(sectionLabel); // the section JTextField final JTextField sectionText = new JTextField(4); sectionSelector.add(sectionText);

Similarly, we create and place the widgets in the second VerticalBox.

Place boxes in the panel
// and add both Boxes to the top JPanel top.add(courseSelector); top.add(sectionSelector);

And we place both Boxes in the JPanel. Note that the BoxLayout manager does not require the bindings that RelativeLayout does. It simply places widgets one after the other. Decorate the panel We would like to separate the first two panels from the rest of the frame by surrounding each with a border. So we need to create the borders.
// create borders for the JPanels Border raisedBevel = BorderFactory.createRaisedBevelBorder(); Border loweredBevel = BorderFactory.createLoweredBevelBorder(); Border compound = BorderFactory.createCompoundBorder( raisedBevel, loweredBevel);

281

Border is a Swing interface used to describe a border around a JPanel. A BorderFactory is a class which creates objects implementing the Border interface. To use these objects, you must include two import statements at the beginning of the class. import javax.swing.border.*; import javax.swing.BorderFactory;

Explore BorderFactory to see the kinds of borders it can create. If you find a more appealing border, use it in place of what I have created. Continuing with our method,
// finish with a border top.setBorder(compound);

Now that we have a Border available, we place it around the JPanel and the appearance of the top JPanel is complete. Create the middle panel This panel is more complex than anything we have seen. Because of its complexity, we will use RelativeLayout to design it. I suppose we could have built it using 11 vertical boxes, or six horizontal ones.
middle.setLayout(new RelativeLayout());

Labels
Note that there is a row of labels. For each label, we follow our usual practice; create a widget and its bindings, add the bindings to a collection, and then add the widget and its collection of bindings to the frame or, in this case, panel. In this case, the top edge of all the labels is the same, so we create a constraint for that, and then use it for each label.
middlePanel.setLayout(new RelativeLayout()); BindingFactory bf = new BindingFactory(); JLabel dayLabel = new JLabel("Day of the week"); Binding dayLabelLeft = new Binding(Edge.LEFT, 10, Direction.RIGHT, Edge.LEFT, middlePanel); Binding dayLabelTop = new Binding(Edge.TOP, 10, Direction.BELOW, Edge.TOP, middlePanel); RelativeConstraints theBindings = new RelativeConstraints(); theBindings.addBindings(dayLabelTop, dayLabelLeft); middlePanel.add(dayLabel, theBindings);

282

JLabel startLabel = new JLabel("Start time"); Binding startLabelTop = bf.topAlign(dayLabel); Binding startLabelLeft = new Binding(Edge.LEFT, 275, Direction.RIGHT, Edge.LEFT, dayLabel); theBindings = new RelativeConstraints(); theBindings.addBindings(startLabelTop, startLabelLeft); middlePanel.add(startLabel, theBindings); JLabel endLabel = new JLabel("End time"); Binding endLabelTop = bf.topAlign(dayLabel); Binding endLabelLeft = new Binding(Edge.LEFT, 75, Direction.RIGHT, Edge.LEFT, startLabel); theBindings = new RelativeConstraints(); theBindings.addBindings(endLabelTop, endLabelLeft); middlePanel.add(endLabel, theBindings); JLabel roomLabel = new JLabel("Room"); Binding roomLabelTop = bf.topAlign(dayLabel); Binding roomLabelLeft = new Binding(Edge.LEFT, 75, Direction.RIGHT, Edge.LEFT, endLabel); theBindings = new RelativeConstraints(); theBindings.addBindings(roomLabelTop, roomLabelLeft); middlePanel.add(roomLabel, theBindings);

Notice something new in these statements. Rather than having separate collections for the bindings of each widget, we use only one collection, named theBindings. There is no way to remove bindings from a collection, so we simply allocate new memory for it each time we wish to erase the previous bindings.

The meetings
The labels are followed by several similar rows for the different meetings of the section. The actual number of rows which appear is available from the College class. For each meeting of the section (for each of the rows), we need seven JRadioButtons (corresponding to the days of the week), and three JTextFields (the start and end times of the meeting, and the room in which it will take place.) We‘ll see how to do the checkboxes in a moment. So we have several rows of widgets, each row of which appears identical. Intuition (another name for learning from past mistakes) tells me that a good way to do this is to use a data structure of some kind, perhaps an array or a Vector or a List, with each element of the collection corresponding to one row on the data entry screen. Continuing with intuition, we realise there are seven radio buttons. They could make a collection too. Since the data structure or collection is quite simple and there is no real processing of the elements in the collection, we can use an array. To do that, we should examine arrays more fully before we continue.

283

Arrays We have used collections (and arrays) before. A Student object contains a collection of Mark objects. A Course object contains a number of Section objects. A Section object contains a number of student identifiers. Generally we needed to go through all the elements in the collection, starting at the first and ending at the last. But what if we need to access the elements of the collection randomly? That is, we want the fourth element, then the eighth, then the first. It would be very inefficient (slow) to have to process all preceding elements in the collection to retrieves a specific one. Fortunately, there is a very traditional data structure which supports random access. This is the array. An array has two parts. The first is the collection of data items. The second is the subscript or index, a number used to indicate which element of the collection we wish. Suppose we have a collection of Student objects, which we wish to store as an array because we need to access the Student objects randomly. Consider the statement
Student[] theStudents = new Student[50];

This array, whose name is theStudents, contains space for 50 Student objects. The objects are numbered zero through 49. The index always starts at zero. In memory, these 50 objects are stored next to each other. When we wish to retrieve the last Student object we retrieve theStudents[49]. If we wish to retrieve the first Student object, we retrieve theStudents[0]. When we wish to retrieve all the Student objects, we use a for statement.
for (int i = 0; i < 50; i++) { // do something with theStudents[i] }

But why stop at an array of Student objects? We can have an array of anything, primitive datatypes like int or char (Did you realise that you can think of a String as an array of char? You probably did since we inspected a String and saw its array of char.), or an array of arrays. An array of arrays? Yes, each element of one array is itself a second array. You have probably seen this structure often. The board on which you play chess or checkers is a two-dimensional array. The rows are elements of an array; but each row contains an array, each element of which is a column. Each sheet of a workbook (a spreadsheet) is a two-dimensional array, whose elements are much more complicated than those of a chessboard.

284

That is, these are arrays in which you can think of each array element consisting of an array.

Were we to create a variable to represent a chessboard, we might use something like this.
int [][] chessboard = new int [8][8];

The model of a chessboard and its pieces could represent an empty cell with a zero, a cell containing a white piece with a negative number (different numbers correspond to different pieces), and a cell containing a black piece with a positive number. If you stretch your mind you can imagine ragged arrays, in which each row may not have the same number of cells. Imagine this histogram turned on its side.

So, now that we know a little more about arrays, let‘s continue building the data entry screen.

Create the middle panel, continued
Radio buttons When I look at the screen we are building, experience helps me see that the radio buttons form a two-dimensional array (several rows, seven columns), while the start time, end time, and room each form one-dimensional arrays (several rows each). Most importantly, the arrays are associated. That is, an element in one row of one of the arrays is associated with the corresponding element in the other arrays. When you look at the data in, for example, the third elements of these arrays, you will find the day of the week on which the third meeting takes place, the time it starts, the time it ends, and the room in which it occurs.

285

ButtonGroup
Note that radio buttons occur in groups. When you select one button in a group, all the others are deselected. That‘s the traditional way you choose which radio station to listen to on your vehicle radio. Push one button, you hear one station; push another button and you hear another station. When you have more than one group of radio buttons on a screen, selecting and deselecting in one group does not influence your choices in the other groups. We accomplish this by placing the buttons for each of the possible meetings in different ButtonGroups.
ButtonGroup aGroup = null;

We will see how to add JButtons to ButtonGroups in a moment. When first created, all the buttons in a button group will be deselected. Note that there are some applications in which choosing a button in one group may affect the contents of another group. For example, a washing machine I recently purchased lets you choose the type of material you are washing. Depending on your choice, you may not be able to use hot water. The ―hot water‖ choice in the temperature group is disabled.

An array of radio buttons
Since we have arrays, we need to have values which tell us the bounds of the loops which we will use to process the elements of the arrays.
College c = College.getInstance(); final int MAX_MEETINGS = c.getMaxMeetingsPerWeek(); final int DAYS_IN_WEEK = 7;

And then we create the arrays.
final JRadioButton[][] aRadioButton = new JRadioButton[MAX_MEETINGS][DAYS_IN_WEEK];

Note that we have created the possibility of the array; the individual array elements do not yet exist.

An array of textfields
Similarly, we create arrays of textfields for the start and end times, and the room numbers.
final JTextField[] startText = new JTextField[MAX_MEETINGS]; final JTextField[] endText = new JTextField[MAX_MEETINGS]; final JTextField[] roomText = new JTextField[MAX_MEETINGS];

286

final JCheckBox[] hasMeeting = new JCheckBox[MAX_MEETINGS]. I realised it could be difficult to tell which of the five meeting possibilities are actually being used and it would be inconvenient to change many values when a meeting is removed. Note that we have created the possibility of the array. So I decided to place a column of checkboxes down the right side of the screen.charAt(j). j++) { String text = "" + ("SMTWRFA"). for (int j = 0. Binding top = bf. You may have noticed that all these arrays are declared to be final. i++) { // the radio buttons aGroup = new ButtonGroup(). aGroup.add(aRadioButton[i][j].) When the data entry person clicks the OK button. the individual array elements do not yet exist. Placing the arrays in the frame At last we are able to begin creating the individual elements of the arrays and placing them on the screen. i < MAX_MEETINGS. aRadioButton[i][j] = new JRadioButton(text). 287 . top). Whenever the data entry person chooses a day. Checkboxes In thinking about this screen. middlePanel. j < DAYS_IN_WEEK . the appropriate time and room will be erased from the screen. left = bf. or a time. or a room. left = bf. This is so that the ActionListeners we will need are able to access them properly. theBindings = new RelativeConstraints(). the individual array elements do not yet exist.addBindings(left.rightOf(aRadioButton[i] [j]).Note that we have created the possibility of the arrays.below(dayLabel). // for all the meetings for (int i = 0. theBindings.add(aRadioButton[i][j]). theBindings). (When the data entry person unchecks a checkbox. the appropriate checkbox will be checked by the method.leftEdge(). This requires another array. we will process only those rows which have the checkbox checked. Binding left = null. We saw this in the previous chapter.

theBindings = new RelativeConstraints(). middlePanel.addBindings(left. the outer one deals with the rows to be displayed. The inner loop deals with the radio buttons for the seven days of the week. } The first loop. middlePanel.below(aRadioButton[i] [0]). theBindings. and the checkboxes. 288 . top).add(endText[i]. theBindings.leftAlignedWith(roomLabel).leftAlignedWith(startLabel). theBindings).. j < DAYS_IN_WEEK ..leftAlignedWith(endLabel).add(roomText[i].addBindings(left. endText[i] = new JTextField(4). middlePanel. roomText[i] = new JTextField(4). top). top). for (int i = 0.addBindings(left. specifically related to the textboxes for the start and end times. } The core of this code is a pair of nested for loops. left = bf.addBindings(left. i < MAX_MEETINGS.) indicates there are some statements that must be done to make the radio buttons appear. theBindings = new RelativeConstraints().} // and the text fields startText[i] = new JTextField(4). The second ellipsis indicates there are some statements that must be done after the radio buttons are created. theBindings = new RelativeConstraints()... left = bf. i++) { for (int j = 0..rightOf(roomText[i]).add(hasMeeting[i]. top = bf. theBindings. The first ellipsis (the . middlePanel. theBindings = new RelativeConstraints(). theBindings. j++) { .add(startText[i]. left = bf. top). left = bf. theBindings). theBindings). } . and the room. theBindings).. // and the checkbox hasMeeting[i] = new JCheckBox().

// InputVerifier for the times InputVerifier verifierTime = new InputVerifier() { public boolean verify(JComponent input) { int screenTime. This keeps the columns of radio buttons aligned on their left edge as all radio buttons are the same width. left = bf. top = bf. The textfields line up with their respective labels. how do we deal with the bindings? We can use a binding to describe the top of all widgets in a row.We definitely need to create the individual array elements. For example. Subsequent radio buttons are to the right of the previous radio button.getText(). Subsequent rows are below the previous row. What do we do for the individual widgets in a row? The radio buttons begin at the left edge of the panel. left = bf.leftEdge(). all of which are aligned along their top edges. 289 .leftAlignedWith(startLabel). The checkboxes are placed to the right of the last textfield. String text = ((JTextField) input). The label on the radio button is determined for the English-speaking world. The variable names left and top are used over and over again. for all the arrays and we need to place them in the correct locations. Notice that every widget has a left and top binding. Binding top = bf.below(dayLabel).rightOf(roomText[i]). left = bf.below(aRadioButton[i] [0]). The first meeting row is below the row labels. left = bf. How do we do that? In particular.rightOf(aRadioButton[i] [j]). taking into account the default margin. InputVerifiers But wait a moment! We realize that we will need InputVerifiers for the textfields. methods which check that the data we enter is reasonable.

"Time contains non-numeric characters.23\n" + "Second two 00 . This InputVerifier is simply a stub. JOptionPane. the room is acceptable.59". return false.getText(). whenever we supply a room.length() == 0) { // no time specified JOptionPane. is incomplete.showMessageDialog( sectionInput. "Time should be four digits. "Missing data".showMessageDialog (sectionInput. 290 . JOptionPane.intValue()).showMessageDialog( sectionInput.ERROR_MESSAGE). }. int screenMinutes = screenTime % 100. return false. The InputVerifier simply returns true.if (text. "Bad time".ERROR_MESSAGE). "Bad time".\n" + "First two 00 . // length = 0 try { // is there a numeric time screenTime = (new Integer(text).".ERROR_MESSAGE). as we do not have any way of storing and retrieving a list of allowable rooms. if ((screenTime < 0000) || (screenTime > 2359) || (screenMinutes > 59)) { JOptionPane. // end verifierTime The InputVerifier below. } // end catch return true. } // end verify }. // InputVerifier for the room InputVerifier verifierRoom = new InputVerifier() { public boolean verify(JComponent input) { int screenRoom. } } catch (Exception e) { JOptionPane. JOptionPane. String text = ((JTextField) input). // and is it reasonable? int screenHour = screenTime/100. return false. for the rooms. "Need to supply some time". a small piece of code which will be completed at a later time.

} ActionListeners for radio buttons Recall that the check boxes work in conjunction with the radio buttons and textfields. with some unique String within the parentheses. But we need an additional feature of ActionListeners. so we can use aRadioButton[i][j]. roomText[i]. } // end verify }. // end verifierRoom Of course each InputVerifier must be attached to the appropriate widget. i < MAX_MEETINGS. } return false. we would like to have the radio buttons become unchecked and the start time. If we click a radio button or enter a start or end time.setActionCommand(Integer.setActionCommand( ). and room number to vanish.setInputVerifier(verifierTime).setInputVerifier(verifierRoom). we would like the check box for that row to become checked.toString(i)). The String needs to identify the row in which the radio button is located.if (text. When an ActionListener is executed. Similarly.length() != 0) { // should check if the room is in // a database. for (int i = 0. the ability to identify a specific String with each widget. but we don't have one yet return true. if a check box is unchecked. Instead of just creating a radio button aRadioButton[i][j] = new JRadioButton(text). How can we link these components together? We have seen ActionListeners in the previous chapter and we need them here as well. endText[i]. or a room. end time. we need an additional statement aRadioButton[i][j]. 291 . i++) { startText[i].setInputVerifier(verifierTime). we can check this specific String with the getActionCommand method.

Don‘t forget to add it to each radio button.isSelected(). hasMeeting[i]. // ActionListener for the radio buttons ActionListener actionListenerRadioButton = new ActionListener () { public void actionPerformed(ActionEvent e) { try { int row = new Integer(e.setText(""). roomText[row]. // ActionListener for the checkboxes ActionListener actionListenerCheck = new ActionListener() { public void actionPerformed(ActionEvent e) { // which button AbstractButton abstractButton = (AbstractButton)e.Here is the appropriate ActionListener. we will erase all the information associated with that meeting. intValue(). hasMeeting[row]. Then we can associate this ActionListener with all the check boxes. endText[row]. one which applies to all the radio buttons.setText("").toString(i)). we need the ActionCommand to be set so we can tell which checkbox is checked.setSelected(true). For this to work. When a checkbox is deselected.setText(""). startText[row]. } catch (Exception x) { } } 292 .getActionCommand()). // was it checked or unchecked? boolean selected = abstractButton.getModel().setActionCommand(Integer. ActionListeners for checkboxes We need ActionListeners for the checkboxes.getActionCommand()).getSource(). // if unchecked if (!selected) { try { int row = new Integer(e. } catch (Exception x) { } } }. intValue().

middle. the one containing the buttons. setDefaultButton(cancelButton).add(cancelButton). // the standard order (left to right) is // OK and then cancel bottomPanel. components are placed side by side. which we don‘t have yet. in the order in which they are added to the JPanel. and room number.} }. we will use FlowLayout. it contains JButtons // use FlowLayout placing components at the right.VK_C). bottom. We need an array of ButtonGroups. With this layout manager. Instead.getRootPane(). The bottom panel Let‘s continue and build the bottom JPanel. But we have a small problem.VK_K). RelativeLayout would be overkill for such a simple situation.setBorder(compound). We can clear all the buttons in a group using the clearSelection method but to do that we need to know the ButtonGroup with which we are dealing. JButton okayButton = new JButton("OK"). Which layout manager should we choose? The panel contains only two JButtons. That is. sectionInput. Decorate the middle panel Place a border around the middle JPanel and we are done with it.RIGHT)). bottom. so will be moved to the left when we add the cancel button. at the specified end of the panel.add(okayButton).setMnemonic(KeyEvent. okayButton.setLayout( new FlowLayout(FlowLayout. // build the bottom JPanel. Make it so. cancelButton. end time. This ActionListener erases the values we provided for the start time. but leaves the radio buttons checked. 293 . JButton cancelButton = new JButton("Cancel"). the okay button is added first.setMnemonic(KeyEvent.

cancelButton. okayButton. 500).setVisible(false).". "Clicked okay.setLocation(100.addActionListener(actionListenerOkay). this is exactly the same technique we used to display the MyDate data entry screen. Done! And then the screen is complete. ActionListener actionListenerOkay = new ActionListener () { public void actionPerformed(ActionEvent e) { JOptionPane. /** * show the Frame. } Create a method to display it. } }. box.setVisible(true). } }.exit(0).addActionListener( actionListenerCancel). ActionListener actionListenerCancel = new ActionListener () { public void actionPerformed(ActionEvent e) { sectionInput. box. box. } 294 . 100). JOptionPane. box.INFORMATION_MESSAGE). while (box.showMessageDialog(sectionInput.pack().Button ActionListeners Of course.isVisible()) {} System. buttons need ActionListeners too.setPreferredSize(600. */ public static void showDataEntryFrame() { JFrame box = buildDataEntryFrame(). // done return sectionInput. Yes. "Okay".

you may wish to avoid the use of JOptionPanes. Canadian Social Insurance Numbers. postal codes. The second step is to create any widgets (including panels. Repeat this step as many times as necessary. ―Their container‖ may be the frame or it may be another panel. Modify it as you think appropriate. you may customise the data entry screen to suit your preference. When you are entering a large amount of data. which will need their own layout managers) which we wish to place in the frame. or American Social Security Numbers. The sixth step is to test that everything works properly. For each. The fourth step is to examine all the panels. 295 . If that is so. particularly if there are nested panels. You will find the JFormattedTextField makes your life easier. we create the bindings (constraints) associated with each widget. Create the positioning information associated with each panel. Some companies have design standards to which you must adhere. Create their positioning information and add them to the panel. Add the panels and their positioning information to their containers. Other layout managers use different terms to control the position of the widgets.Test it. The fifth step is to add InputVerifiers to all the textfields and ActionListeners to all the buttons. create the (non-panel) widgets the panel contains. It is described in the online Java documentation. but for now. Then we add the widgets and their positioning information to the frame. be they radio buttons or JButtons. Summarizing building a data entry screen This is a longer summary than the one you saw in the previous chapter. You may need different layout managers to create the different parts of the screen. something you have been doing throughout all the steps. The third step is to create any panels which we wish to place within other panels. haven‘t you? Some general comments on data entry You may need to accept data in a special format. be it phone numbers. If we use the RelativeLayout layout manager. you may find the JOptionPanes that appear from the InputVerifiers when you make errors interrupt the flow of typing. The first step in building a data entry screen is to create a JFrame and associate a layout manager with it.

But if you choose the cancel button. add a normally-invisible label to the data entry screen. perhaps by clicking the okay button. suppose your Section data entry screen checks that the end time is after the start time. cancelButton. For example. or you will not be able to exit from the field.setVerifyInputWhenFocusTarget(false). an error message appears. The only way to leave the day JTextField is to provide a valid day within February 2009. how can you correct it? Hint. 296 . and return to the day field to enter the number 30. Then you may change the month to March. and screens containing a menu. If you choose the X in the top-right corner. The InputVerifier method will need to return true always. but you entered the start time incorrectly. Summary But a complete system does not involve only data entry screens! A complete system probably involves a splash screen (something to watch as the rest of the program loads). when you meant to enter 1030 and 1120. You meant to enter 2009/03/30. You acknowledge it. If you adopt this method. As you leave the day JTextField you will receive an error message. Creating a screen containing a menu is the subject of the next chapter.Instead. and click in the month JTextField. you are able to leave the data entry screen with no problem. Why does this happen? How can you avoid it? Similarly. Why does this happen? More importantly. one of which we have already seen. consider this statement. How can you fix it? You may be forced to change to a time which is correct and then change it back. Here are a couple of interesting problems. Attempt to leave the data entry screen without entering any data. A person might do this when there were many data entry screens and the person accidentally chose the wrong one. How is that for the name of a method? What does that method do? Here‘s another problem: assume you have entered 2009/02/30 as the date on the Meeting data entry screen you created in the previous chapter. But the day error message reappears. you will need to verify all the fields when you attempt to accept the data on the screen. allowing you access to other parts of the system. place an error message in it and make it visible whenever the input is in error. a start time of 1130 with an end time of 1120.

Complete that screen adding the choice of the species which was sighted. whose number you must provide. Which layout manager do you prefer? When you enter data into the start time. In the previous chapter you created a data entry screen for entering a sighting. Use the GridBagLayout manager to recreate one of the data entry screens we have created in this chapter. 8. Assume this has grown into a system containing many sightings. Complete that screen. Modify your program so that the appropriate checkbox is checked. 2.Exercises 1. The section ―Some general comments on data entry‖ speaks about JFormattedTextField. the appropriate checkbox is not checked. 3. 7. or room number textfield. Develop a screen which allows you to display the sightings of a particular species. The section ―Some general comments on data entry‖ speaks about using invisible fields which become visible to display error information. Develop a screen which allows you to display details on a specific account. In previous chapters we discussed modelling the sightings a birder makes. 4. In previous chapters we discussed modelling a bank account. In previous chapters we discussed modelling the sightings a birder makes. 6. end time. 297 . 5. In the previous chapter you created a data entry screen for entering a transaction. In previous chapters we discussed modelling a bank account. Explore the capabilities of that class and create a small data entry screen that illustrates those capabilities. adding the choice of the account to which the transaction applies. whose name you must provide. Modify a data entry screen to use that approach. Assume that this has grown into a system which has many accounts.

298 .

BlueJ has menus. JSeparators are the visual dividers. 299 . In particular.Chapter 16 . a JMenuBar object is the horizontal menu. In this chapter. but how do you access them? In modern computer applications. and BlueJ is a Java application. you see separating JMenuItems into logical groups. you often have a menu system that allows you to access the various parts of your system. we will focus on creating a menu system. In addition to JMenuItems. a JMenu can also contain JSeparators.a popup window containing JMenuItems that is displayed when the user selects an item on the JMenuBar. usually horizontal lines.‖ That is. How did the developers make those menus? Creating the menus Definitions A menu appears across the top of a frame and is implemented through the JMenuBar class. containing a collection of JMenu objects. The Java documentation says that the JMenuBar class is ―An implementation of a menu .Creating a GUI – Menus Learning objectives By the end of this chapter you will be able to:     Use Swing widgets to create menus Describe some of the considerations involved in designing a menu Describe the role of a layout manager in creating menus Use ActionEvents and ActionListeners with menus Introduction Having data entry screens is fine. A JMenu object is the vertical list of JMenuItems and JSeparators which appears when you click an item in the JMenuBar.

to save any unsaved work.  Save. as a minimum. containing all choices relating to data entry  Help. to create a new college or a new semester. I would suggest. we would need new professor. import java. we don‘t want a menu created except under the control of the createAndShowGUI method.event. 300 . open student.*. But note that we will not be implementing all the functionality behind the menus. I would suggest these items. As in the previous chapters. transcripts. shown below. list of professors. createAndShowGUI. containing a help system On the File JMenu.  File.*.  New. The Java tutorial provides us guidance. A third method. we would need open professor.  Open. Note that the constructor is private. we need the Swing library for the widgets and the AWT library for the events associated with them.  Exit.com/docs/books/tutorial/uiswing/components/menu Create a class named CollegeMenu. to allow us to display timetables. new student. displays the JMenuBar within a JFrame. It contains only a few methods. to work with an existing college or semester. I would suggest these items. http://java.sun. to shut down our program On the Edit JMenu. to provide a brief blurb about the developers of the program Implementing the menu So. these items. containing all choices relating to the files in which we are storing data  Edit. On the JMenuBar. and open section. The constructor uses a helper method to create the JMenuBar.Designing the menu system So what do we want our menu system to contain? We need to answer that question before we begin to implement the menu system. import javax. if there is any.  Print. I would suggest:  editing an existing professor  editing an existing student  editing an existing course  editing an existing section On the Help JMenu. If we were to implement this in its entirety. to provide access to documents describing how to use our program  About. let‘s begin.  Help.swing. and new section.awt. If we were to implement this in its entirety. etc.

bar. public JMenuBar getBar() } return bar. Now the menu bar contains one choice. private CollegeMenu() { bar = createMenuBar(). 301 . fileMenu. } We‘ll create the menu in a moment.public class CollegeMenu { The only instance variable in this class is the JMenuBar. The menu will contain the word which appears in the menu bar. The accessibility methods are described below. private JMenuBar bar.setMnemonic(KeyEvent. but it is empty. We define a variable to contain the File menu.getAccessibleContext(). fileMenu. etc"). Recall that we used mnemonics when we established shortcuts in our data entry screens. which will appear across the top of the frame.add(fileMenu). setAccessibleDescription ("Deal with files . save. but let‘s first create a getter to retrieve it. } Now we can create the menu and submenus. bar = new JMenuBar(). It does not contain any of the vertical menus yet.open. along with all the choices in the vertical menu. private JMenuBar createMenuBar() { Create the horizontal menu. JMenu fileMenu = new JMenu("File").VK_F). Once fileMenu has been created add it to the menu bar. The constructor calls the createMenuBar method and stores the menu which is created in the variable named bar. The createMenuBar method does all the work. but the vertical menu is empty.

getAccessibleContext(). } } The code as shown will work. frame.setMinimumSize(450. //Display the frame frame. though. frame.VK_N).add(menuItem). 260). setAccessibleDescription ("Create a new file").setLocation(100. */ public static void createAndShowGUI() { // provide a frame in which to display the menu JFrame frame = new JFrame("COSC 111/121 Example″). the method above creates the menu bar but does not display it. /** * Create the GUI and show it. First. menuItem. // repeat for other JMenuItems (see below) // repeat for other JMenus (see below) // done return bar.setVisible(true).setDefaultCloseOperation (JFrame. We need another method which will create the frame into which we can place the menu. } As we did with the data entry screens. test the menu system by compiling the CollegeMenu class and then executing its createAndShowGUI method. // create the menu system // and add it to the appropriate JFrame frame. KeyEvent. 100). We‘ll see what is missing below. JMenuItem menuItem. fileMenu.getBar()). but it is incomplete.EXIT_ON_CLOSE). 302 . frame.We define a variable which will be used to successively create the choices on the File menu.setJMenuBar(new CollegeMenu(). // create JMenuItems for fileMenu menuItem = new JMenuItem("New". And then we create the choices.

We have seen that a mnemonic is a single letter abbreviation you can use to choose a selection from a menu. Or you could use S for both. menus are divided into logical sections (New. pressing and the mnemonic repeatedly will switch from one of the duplicate entries to the next. who may use a screen reader to identify the mouse location and the text on which it is located. in a circular fashion. we are providing access for those with serious vision problems. S for Save and P for Print are common mnemonics. and Save all deal with files) and you usually wish to separate one logical group from another.Accessibility We have used some new methods here. As you do this. we saw them in an earlier chapter. fileMenu. Tooltips appear when you rest your mouse over a choice but do not click a button on the mouse. Open. An example is menuItem. I added a separator after Save. what mnemonics did you use for Student and Section? As a general rule. Completing the menu Now complete the other parts of the menu system. I used T for student and S for section. You could use S for student and E for section if you prefer. On the Edit menu.add(new JSeparator()). When you have duplicates and you cannot find suitable different mnemonics. An alternative to getAccessibleContext().setToolTipText("Create a new file"). To avoid this. 303 . The other problem you run across is that the vertical. adding one to the menu wherever appropriate. Do this with JSeparators. the duplication of mnemonics.setAccessibleDescription would be to use tooltips for those who don‘t use a screen reader. relating to accessibility. drop-down. To accommodate all users. you may run across an interesting challenge. In this case. Accessibility refers to making computers easier to use by those with different types of sensory challenges. you should use both AccessibleDescriptions and ToolTips. you shouldn‘t have the same mnemonic for two selections on the same menu. and one before Exit.

the menu itself. This is a simple version. Here the CollegeMenu class itself will implement the ActionListener interface. This is done to expand your knowledge of tools available to you. For example. by returning the word which it displays.setActionCommand("exit").equals("about")) { // display message box JOptionPane.getSource()). Others. "CollegeMenu . }. How do we invoke methods to do these actions? We use ActionListeners again. we must be able to distinguish between the ―many other objects‖. The getText method allows us to identify which menu item has been chosen. menuItem. however. We use the setActionCommand method to identify each menu choice. The listener uses the ActionPerformed method to identify which menu selection is made. which is an ActionListener. or query screens (but we don‘t have any of those yet). If you wish. The word this refers to the current object.showMessageDialog(null. } if (source. JOptionPane.INFORMATION_MESSAGE).exit(0).demo program for COSC 111/121". } // do something for each other possibility return. listening only for the Exit and About JMenuItems.equals("Exit")) { System. lead to data entry screens. public void actionPerformed(ActionEvent e) { JMenuItem source = (JMenuItem)(e. if (source. so that the menu 304 . "About".Performing actions Some of the choices on a menu simply lead to other choices.addActionListener(this). you could have an ActionListener to each menu item. since it implements the ActionListener interface. Should you be planning to internationalise this system.getText(). menuItem.getText(). Don‘t forget the import statement! We have seen where each widget implements an ActionListener. public class CollegeMenu implements ActionListener Each menuItem variable must register itself with the listener. When one object acts as a listener for many other objects.

These will be removed from your program (replaced by generic terms) and stored in a properties file. It will have to recognise the other languages.selections will appear in other languages. This is described as ―an open source software. First.‖ Note that there has not been a lot of development work on this package for several years. since there are 18 characters between the first and last letters of internationalization. Would it be better after all to have separate listeners for each menu item? What changes would you need to make to your menu to make this possible? Help Implementing a help system is a complicated task. extensible help system that enables you to incorporate online help in applets.sun. see http://java. 305 . This is a common geeky abbreviation for internationalization. Second. platform-independent. For more details on JavaHelp. since it should be able to answer any questions that the user has about your program. you need someone to do the translation.com/javase/technologies/desktop/javahelp/ Other similar packages may be available. Internationalization Definition Seeing data entry screens and a menu system in English raises the question ―what does it take to use a different language?‖ How would I translate this system into French? Into Russian? Into Japanese? Let me introduce a common abbreviation – i18n. I haven‘t used them. a full-featured. Steps to follow So how do you translate a system into another language? A good place to get general information is http://java.com/docs/books/tutorial/i18n/index. This trail goes into more details than I will here. I‘ll refer you to the website for JavaHelp. operating systems. a portion of the Java tutorials dealing with i18n.html. components.sun. you need to identify the words which need to be translated. be prepared to change this method. and devices. Rather than going into great detail about implementing a help system. applications.

) Thus. In a properties file for a French translation. according to one of my students. The second and third parts of the name are the international abbreviation for the language and the international abbreviation for the country. Ouvrir has been provided by your translator. with the vocabulary differing between countries.htm. Note that the mnemonic may change as well as the term. the French spoken in Quebec (a province of Canada) has differences from the French spoken in France. here is the line for New. MessagesBundle is the name chosen to reflect the fact that this file contains a collection (colloquially called a bundle) of messages. insert the translations into the properties file. First you need to create a file (whose name doesn‘t matter) containing the statements you would expect to see in the properties file. your File menu contains the option New.properties For languages which do not use the Latin alphabet (alphabetic characters whose ASCII values are between 0 and 127) you need an additional couple of steps before you create the properties file.gov/standards/iso639-2/php/code_list. you need save your properties file. This may have implications for the spacing between widgets on your data entry screens.For example.iso. Its name must be MessagesBundle_xx_yy.org/iso/country_codes/iso_3166_code_lists/english_country_names_and_code_el ements.properties. Perhaps you will choose the generic term createAFile. you will place a line that says createAFile = Nouveau.properties MessagesBundle_fr_CH. Thus you may need createAFileMnemonic = N and openAFileMnemonic = O. but with the translations in the native alphabet. and from that in Burkina Faso (a landlocked country in West Africa which gained its independence from France in 1960.properties MessagesBundle_fr_FR. For example. Third. Nouveau has been provided by your translator. you will place a line that says openAFile = Ouvrir.php and the country abbreviations (in English) are available at http://www. Fourth. file. Note also that the translated term may be longer than the term it is replacing. in Russian. MessagesBundle_fr_CA. For example. we would need four properties files. In a properties file for a French translation. if we were making a program that could be used in those four countries. For the word Open. from that spoken in Switzerland. Note that one language may be used in different countries.loc.createAFile = Новый 306 . The language abbreviations are available at http://www.properties MessagesBundle_fr_BF. create a generic term openAFile.

MessagesBundle_ru_RU.‖ Details on the UTF-8 format are at http://en.currentLocale). Both are Strings. will save in UTF-8 as long as you click UTF-8 in the dropdown list labelled ―Encoding. provided with Windows. The Java statements to make the magic happen In the method which shows the menu (createAndShowGUI). use the native2ascii program (available as part of the Java download) to convert its contents to a file which contains only ASCII characters and Unicode characters.wikipedia. Notepad. replace the method header public static void createAndShowGUI() { with public static void createAndShowGUI(final String language. That is.properties MessagesBundle_ru_RU. ResourceBundle messages = ResourceBundle. declare two variables. You do not need a fancy program to do this.util. Once the file is created. one for the language and one for the country.ResourceBundle. Thank you. ensuring that it is saved using the UTF-8 standard.createAFile = \u041d\u043e\u0432\u044b\u0439 All the Cyrillic characters have been replaced with Unicode characters.properties since Sergey was the student who did the translation.Locale and java. These variables need to be given values. Remember to import java. In my case. To use native2ascii. 307 .getBundle( "MessagesBundle".Create this file. I used the command native2ascii sergey. final String country) { Use these two variables to create a Locale object and a ResourceBundle object.util. for example) with the appropriate word. country). Locale currentLocale = new Locale(language. as it is the first method which should be run. Sergey.org/wiki/UTF-8. The easiest way is through parameters to the method. run it at the command line.properties now contains a line which says file. The fifth and final step in internationalization (the simple form we are considering) involves Java code to replace the generic terms you chose (createAFile.

getBar()).com/. for example) is the key and the translation is the value. Conclusion This is only an introduction to the subject of i18n. some cultures use one format for numbers. others use a different format.getString("createAFile")). all the text now comes from the translation. Many other cultural differences need to be considered. There is much more to using ResourceBundles. That is. how do you deal with different formats for numbers. The generic term we used (createAFile. frame. language would be entered as ―en‖ and the country as ―CA‖. the standard name? The variable messages becomes a parameter to any method that has been internationalized. Alternatively.setJMenuBar(new CollegeMenu(messages). Note that a ResourceBundle is actually an instance of a map. the first of which is the constructor.com/ or http://babelfish.paralink.The getBundle method looks for the properties file that corresponds to the correct language and country. For example. The constructor becomes public CollegeMenu(ResourceBundle messages) { bar = createMenuBar(messages). you could use an online source like http://webtranslation. to extract the appropriate text from the ResourceBundle.yahoo. Can you use a name other than MessagesBundle. How do you deal with error messages that are put together from smaller messages? The order in which the words occur may differ from culture to culture. } The createMenuBar method (note that it now has messages as a parameter) then uses statements like JMenuItem openMenuItem = new JMenuItem(messages. 308 . When you display your menu and data entry screens. Who did the translation? You didn‘t have someone to do the translation for you? You could simply create a file for English as it is spoken in Canada.

Thus. we‘ll set the college. You have seen a large amount of Java. However. storing data. You have seen the basics (and more) of how to design a program. and its professors aside as we consider other ideas and examples. there are additional aspects of programming. its students. and of Java. and manipulating data. which do not fit well into this example of a college. entering data. 309 . working system.Summary There is still a lot of work to do to make this system a complete. but there are other ideas we should pursue.

In previous chapters we discussed modelling the sightings a birder makes. Remember there are English sentences like ―She saw that saw. how well do the translation websites I mentioned work? Find someone who speaks a language different from you and explore the accuracy and appropriateness of the translations.Exercises 1 2. You will notice that I have placed my menu in one frame. As the world‘s economies become more and more interrelated. 310 .‖ in which the same word may appear as both a noun and a verb. Complete the CollegeMenu class started in this chapter. 4. Explore the subject of internationalization. How does the length of your translation compare to the English words? Does that affect your screen design? 3. and the data entry screen in other frames. internationalization will become more and more important. How would you place the menu and data entry on the same frame? In previous chapters we discussed modelling a bank account. Other languages may have such challenges. In particular. Create a menu system for a banking system involving many accounts. Create a menu system for a birding system involving many sightings. 5.

not an ordinary class.Chapter 17 . but make sure it is an applet.com/applets. for example at http://java. This site includes many sample applets. Creating an applet Open BlueJ and create a new project. used as part of a web page. so we will use that name for the first applet you write.Applets Learning objectives By the end of this chapter you will be able to:    Define applet Use the predefined methods which applets provide Create applets to carry out a variety of tasks Introduction Up to now. These are small programs. 311 . Traditionally. the first program students write is named HelloWorld. But Java can also be used to create applets. The GUI is part of the application and so are all the classes. Let‘s see how we can create an applet. and online.sun. we have been building parts of an application as a stand-alone program which runs on its own. They are described in most books on Java. Then create a new class in that project.

Running an applet I know we have added no code to the applet. The window below appears. To see this. it looks like a class on its class diagram. 312 .Well. but BlueJ has created a complete. workable. although minimally-functional. but it is clearly marked as an applet. right-click the applet and choose Compile the Applet. applet for us. and then right-click the applet again and choose Run Applet.

the menu allowing you to control the applet comes from AppletViewer. The output of the applet is two lines of text. using an application called AppletViewer. Much of what you see comes from AppletViewer.The appropriate radio button has been chosen. and the height and width are fine. Click Ok. Terminate AppletViewer. in particular. 313 . and the applet opens.

// May not be necessary with your browser.awt. but this time in your default web browser.*.replace the example // below with your own private int x. I set the width to 600 and the complete title appeared. but don‘t be concerned. but this time choose ―Run applet in web browser. The applet runs. Most of the length is documentation. rootPane. Run the applet again. the name in the title bar was truncated.write a description of the class here * * @author (your name) * @version (a version number) */ public class HelloWorld extends JApplet { // instance variables . it started on a new tab in Firefox. An applet (as created by BlueJ) under the microscope Here is the code as it appears in the editor (formatted as usual to fit on the printed page. Boolean.putClientProperty( "defeatSystemEventQueueCheck". The three dots at the end of the name (an ellipsis. How does the applet do its work? Let‘s open it in the editor and see. /** * Class HelloWorld . import java. It is always called before the first * time that the start method is called.) This is much longer than most applets you‘ll see in textbooks. import javax. If the browser was not running. Run the applet a third time.getRootPane(). In my case.In my case. it would have started. we‘ll examine the parts of the applet in detail.*.TRUE). there was not enough room to display the full name. which we have seen before) indicate this truncation.‖ Then click Ok. but make its width larger. */ public void init() { // this is a workaround for a security conflict // with some browsers including some versions of // Netscape & Internet Explorer which do not // allow access to the AWT system event queue // which JApplets do on startup to check access. After this code. as Firefox was already running. Due to the font chosen and the width of the frame. JRootPane rootPane = this.swing. 314 . /** * Called by the browser or applet viewer to * inform this JApplet that it has been loaded into * the system.

g. * * @param g the Graphics object for this applet */ public void paint(Graphics g) { // simple text displayed on applet g.drawString("created by BlueJ".setColor(Color.black).setColor(Color.fillRect(0. g. } /** * Called by the browser or applet viewer to * inform this JApplet that it is being reclaimed * and that it should destroy any resources that it * has allocated. and also just before the * JApplet is to be destroyed. */ public void stop() { // provide any code that needs to be run // when page is replaced by another page or // before JApplet is destroyed } /** * Paint method for applet. g.drawString("Sample Applet".blue). 20.white). 40).setColor(Color. */ public void start() { // provide any code required to run each time // web page is visited } /** * Called by the browser or applet viewer * to inform this JApplet that it should stop * its execution. The stop method will always 315 . It is called after the init method and * each time the JApplet is revisited in a Web page. It is called when the Web page that * contains this JApplet has been replaced by * another page. g. 20). g. 0. 200. 100). 20.// provide any initialisation necessary // for your JApplet } /** * Called by the browser or applet viewer to * inform this JApplet that it should start its * execution.

"description of third parameter"}}. * * @return a String representation of * information about this JApplet */ public String getAppletInfo() { // provide information about the applet return "Title: \nAuthor: \n″ + ″A simple applet example description. "url". {"images". * An applet should override this method to * return a String containing information about * the author. "description of first parameter"}. "1-10". the type. * * @return a String[] representation of * parameter information about this JApplet */ public String[][] getParameterInfo() { // provide parameter information about the applet String paramInfo[][] = { {"firstParameter". "description of second parameter"}. * and a description. An applet should * override this method to return an array of Strings * describing these parameters. ". "boolean". version. * Each element of the array should be a set of * three Strings containing the name. } } Whew! 316 . and copyright of the JApplet. } /** * Returns information about this applet. {"status". return paramInfo. */ public void destroy() { // provide code to be run when JApplet // is about to be destroyed. * Returns information about the parameters than * are understood by this JApplet. } /** * Returns parameter information about this JApplet.* be called before destroy.

*/ Many times the init method will do nothing. * It is called after the init method and each time * the JApplet is revisited in a Web page. As we have seen in the previous chapters. then the init method would be where you check. /** * Called by the browser or applet viewer to inform * this JApplet that it should start its execution. We look at each in turn below. paint. */ 317 . stop.The applet begins with two import statements. When you have any GUI components in your applet. In particular. These are init. Java has two graphics libraries. Just remember that an applet cannot save data to a file on your computer without asking your permission. start. applets can contain buttons and textfields and … In fact. awt (Abstract Window Toolkit) and Swing. That is. this is the place to define them and add their listeners. the workaround that is shown appears to be unnecessary on my computer. and the applet we are creating extends JApplet. init The documentation BlueJ creates states it all. start The documentation BlueJ creates gives the purpose of the start method. JApplet is a Swing class that extends Applet. much of what we saw in the previous three chapters can be applied to an applet. /** * Called by the browser or applet viewer to inform * this JApplet that it has been loaded into the system. * It is always called before the first time that the * start method is called. We look at each in turn below. and destroy. Yes. getAppletInfo and getParameterInfo should be implemented as a favour to people who wish to use the applet. Should you have an applet that requires a specific version of a browser (or a specific browser or operating system). an awt class. Applets use both.) A JApplet must implement several methods. HelloWorld is a JApplet (as well as being an Applet.

Perhaps it is running an animation and it should stop. since it appears on a white background. and to write text (beginning at a specified position). This method may do nothing. /** * Called by the browser or applet viewer to inform * this JApplet that it should stop its execution. to draw filled rectangles (and other shapes as well).yellow. 200. It is hard to see the rectangle. The documentation BlueJ creates does not let you know this. This creates a white rectangle. called a graphics context (an object of type Graphics) is provided as a parameter and then you can issue whatever commands you need to produce the graphics output you wish. but they can contact other websites to download images. files. this is the method in which you will write most (perhaps all) of your Java statements. 318 . and then draw it. and also * just before the JApplet is to be destroyed. When drawing something in an applet. * It is called when the Web page that contains this * JApplet has been replaced by another page. As you see from the sample BlueJ provides. paint This is the method which does all the heavy lifting in an applet. the process is to set its colours and other characteristics. the code to do it is placed in this method. this method may do nothing. Of course. g. This area. That is.setColor(Color. To see the rectangle.fillRect(0. stop The documentation BlueJ creates gives the purpose of the stop method. perhaps Color. */ Perhaps the applet is playing some music and it should stop. change it to a different colour. g. it needs an area on which to draw. these commands allow you to specify colours. Should your applet do that. 100). Its upper corner is in the upper left corner of the window (and has co-ordinates 0. The rectangle has a width of 200 pixels and a height of 100 pixels. As such. An applet is a graphics program. 0. or other data. 0).white).Applets cannot open files on the machine on which they are running without asking your permission.

* version.blue). You will have the opportunity to use some of the other methods in the exercises for this chapter. * * @return a String representation of information * about this JApplet */ 319 . */ Perhaps the applet has allocated some memory and it should be released. and copyright of the JApplet. 20).g. * An applet should override this method to return a * String containing information about the author. g. Perhaps it has established a connection to another website somewhere and that connection should be severed.drawString("Sample Applet".setColor(Color. /** * Called by the browser or applet viewer to inform * this JApplet that it is being reclaimed and that * it should destroy any resources that it has * allocated. a little further down in the graphics context. /** * Returns information about this applet. 40). this method may do nothing. To see the other methods you can use to draw. g. Of course.setColor(Color. getAppletInfo The BlueJ documentation gives the purpose of the getAppletInfo method.black). and displays some text (in black). 20. You can see that it is similar to the toString methods we have written in all of the classes we have developed earlier. destroy The documentation BlueJ creates gives the purpose of the destroy method. This changes the colour to black. look at the online documentation of the Graphics class. g.drawString("created by BlueJ". This changes the colour to blue and displays some more text. The lower left corner of the leftmost character is 20 pixels from the left edge and 20 down from the top. 20. The stop method will always be called * before destroy.

getParameterInfo When you run an applet. getParameterInfo provides a way to find out which parameters an applet will process. You can see this in the window which appears when we choose to run the applet. the type. and click Add. The BlueJ documentation describes this in more detail.It is only politeness that you should provide meaningful information from this method. * * @return a String[] representation of parameter * information about this JApplet */ 320 . and a * description. * Returns information about the parameters than are * understood by this JApplet. specify its value in the box provided. specify its name in the box provided. and then click Ok. The default value of null is not informative. /** * Returns parameter information about this JApplet. Repeat for as many parameters as you need. you can provide it with input. * Each element of the array should be a set of three * Strings containing the name. An applet should override * this method to return an array of Strings describing * these parameters. If you wish to specify a parameter. This information is provided through parameters.

and String paramInfo[][] = { {"firstParameter". you can also specify those parameters. "1-10". "description of second parameter"}. But you can‘t specify the parameters unless you know what they are called. you will need to explore the getParameter method of the Applet class. To follow in the steps of those who have gone before. in which the first sample program was to display the words ―Hello World‖. containing three elements. Hello world Since Kernighan and Ritchie published their book on C. Notice the way you can declare an array and give its elements at the same time.This method returns a two-dimensional array (the documentation does not make this completely clear). When you use AppletViewer to view the applet. all Strings. Trying to access paramInfo[3][3] will cause an exception ( an ArrayIndexOutOfBoundsException) to be thrown. Thus paramInfo[1][2] is ―description of second parameter‖. in green text on a purple background. You are definitely not a beginning programmer if you have covered the previous chapters. {"status". and a description of the parameter (element 2). Thus {"firstParameter". each of which is itself an array of three elements. Interpret this two-dimensional array as a one-dimensional array. in 32 point text. To complete those exercises. modify the skeleton applet to display the message Hello World. "description of third parameter"}}. When you run the applet from a web browser. the type of the parameter (element 1). each of whose elements is an array whose three elements are the name of the parameter (element 0). but writing a Hello World program is something all programmers do. beginning programmers have learned how to do this as well. Remember that both row and column subscripts start at 0. "description of first parameter"}. but you will have the opportunity to do so in the exercises. "boolean". 321 . "1-10". You can refer to individual elements of paramInfo by giving the individual row and column subscripts. "description of first parameter"} represents an array. The getParameterInfo method will tell you about the parameters. {"images". you can specify those parameters. The applets we create in this chapter do not use parameters. the elements of which are Strings. declares an array of three elements. "url". paramInfo[2][1] is ―url‖.

322 . 32. and 255-255-255 is white. When I minimize AppletViewer and then restore it. we create a rectangle in which we can display the text. 160-32-240 is interpreted by our brain as purple.32)). g.setColor(purple). the contents remain. The colours (the first number refers to the amount of red in the colour. not the Java code to create green text on a purple background.setFont(g. 50). purple is not one of the constants in the Color class! All colours can be constructed from a mixture of red.getFont(). and the third to the amount of blue) are measured on a scale from 0 (none) to 255 (all). A problem When I resize the applet in AppletViewer. 200. green on purple is ugly.fillRect(0.green). Color purple = new Color(160. 20.drawString("Hello World". g. Make it so. Ugly. Once we have the colour we want. And we display the text. 240).PLAIN. 0. Google the words RGB purple and you will find many sites which tell you that purple is something like 160-32-240. Thus 0-0-0 is black. green. Why does it happen in AppletViewer and how can you fix it? Squares You can create an abstract painting by placing a series of filled rectangles on the graphics context. isn‘t it? That is. g. this time using a predefined value. we need to create the correct font. the contents disappear. g.setColor(Color. Then we set the color of the text. Before we display the text.Oh. This behaviour does not happen when I run the applet in my web browser.deriveFont(Font. based on the default font. and blue. the second to the amount of green. 100). g.

Or you could right-click the applet in the class diagram.pch. skating. A ―Save As‖ window appears. applets are more often viewed via a web browser. Thus you need to create a webpage which contains the applet.gc. titled ―Select HTML page 323 . hockey. flags. the bars and background are easy to draw. choose Run Applet. since the applet is called CanadianFlag. along with the maps. All you need to do is identify the points on the maple leaf where the line surrounding it changes direction and then provide that information to the drawPolygon method. and Nanaimo bars. and click Ok. tell BlueJ to ―create webpage only‖. If I draw the flag as a rectangle.gif provides an appropriate image. and a loon! Word 2007 appears to have lost some of the images. for example. you could just rename the automaticallycreated page. I found images of maple syrup. I didn‘t notice the maple syrup and blueberry pie. Generate web page only.ca/progs/cpsc-ccsp/etiquette/images/fig3. what does the world think of Canada? While looking for this image in Microsoft® Office Word 2003‘s library. I‘ll create a Canadian flag. BlueJ allows us to do this very easily. the webpage is called CanadianFlag. This is a newto-us method which allows us to draw a polygon. As an aside. tuques. I used a drawing program to identify the approximately 30 points I needed to define the vertices of the polygon adequately. I‘ve chosen the Canadian Flag applet.java. Being Canadian.html and is located in the same folder as the applet. don‘t tell BlueJ to run it in AppletViewer or the web browser. When you run the applet. blueberry pie. Creating HTML to run an applet While we have used AppletViewer to run our applet. given the x and y co-ordinates of its corners. Compile the applet. In my case. and flowers of the provinces. The maple leaf is the challenge.Canadian flag Or you can create your national flag. Make it so. http://www. If you wished to create the webpage with another name.

jar.file:/F:/DATA/COSC111/java/ Fall2006/RelativeLayout/RelativeLayout. <html> <!-.when the applet is next run inside BlueJ.file:/F:/DATA/COSC111/java/Fall2006/Applet/" alt="Your browser understands the &lt.file:/C:/BlueJ/lib/junit." > Your browser is ignoring the &lt.destination. The simpler version of the HTML file is: <html> <head> <title>CanadianFlag Applet</title> </head> <body> <h1>CanadianFlag Applet</h1> <hr> <applet code="CanadianFlag. for some reason. Save into a --> <!-. Here are the contents of the html file. Any manual changes made to file will be lost --> <!-.preserve this file. and then provide a name for the HTML page.‖ Double-click the Applet folder name.APPLET&gt.jar.Environment. tag! </applet> <hr> </body> </html> But much of this is unnecessary. I chose CanadianFlagTest and the extension .class" width=500 324 .html was appended automatically.This file automatically generated by BlueJ Java Development --> <!-.jar.directory outside of the package directory if you want to --> <!-.class" width=500 height=500 codebase="F:\DATA\COSC111\java\Fall2006\Applet" archive="file:/C:/BlueJ/lib/bluejcore.applet is run. tag but isn't running the applet. --> <head> <title>CanadianFlag Applet</title> </head> <body> <h1>CanadianFlag Applet</h1> <hr> <applet code="CanadianFlag. It is regenerated automatically each time the --> <!-.APPLET&gt.

and may extend over any lines if you wish. surrounded by <title> and </title> tags. These comments will not appear when you display the webpage. Its national holiday is July 1.</p> Should you wish to add comments within your webpage (see the second line of the automatically-generated webpage). celebrating the day Canada became a nation in 1867. these control the appearance of lines which you use to separate parts of your webpage. <h6> and </h6> (unused in this example) mark the smallest. These are called tags. and the body is surrounded by <body> and </body> tags. HTML (Hypertext Markup Language) is a language used to describe the way webpages will appear when viewed with a web browser. the default is too small to show the entire flag. you can specify a title. capitalization doesn‘t matter. The heading is surrounded by <head> and </head> tags. Within the body of the webpage. <applet> and </applet> mark the instructions which identify the applet to run (code=). the heading and the body. surround each paragraph you wish to add with <p> and </p> tags. 325 . The <h1> and </h1> tags mark the largest type of heading. there are two sections. here‘s the quick introduction. which appears as the title of the window in which the webpage is displayed.height=500 > </applet> </body> </html> A quick introduction to HTML Should you not be familiar with HTML. The description of each webpage begins with <html> and ends with </html>. you may have headings. <hr> (without a matching </hr>) inserts a horizontal line across the screen. You may have seen a similar idea in the chapters using XML. You have seen different tags when we used XML to serialize objects. comments begin with <!-.and end with -->. Within a webpage. Should you wish to add some text to the webpage (not shown here). Should you omit the size. For example <p>This is the national flag of the great country of Canada. in my case. the applet will run in a window of default size but. and the size of the window in which it is to appear. Within the heading.

Enjoy them! In the next chapter. we will step back from Java for a moment. and look at some of the underpinnings of good analysis and design. the exercises actually contain quite a bit of new material of applets. and because they can be fun. 326 . Should you develop websites. solutions which have worked for others and which you can adopt to make your own programs better. We will look at patterns. I have included them here as many students enjoy creating visual artefacts.Summary Applets are graphics programs designed to run in a browser. In this chapter. If not. you find you use them extensively. you may not use them at all.

If you don‘t specify the size. Modify the applet so it accepts parameters to specify the size of the frame. your applet should choose some reasonable value. Let‘s start with height and width. private int height. Create a simple applet which displays your name. First. 327 . To accomplish all this. specify those parameters and their values.Exercises 1. When you use BlueJ to run the applet. The declarations are private int width. if (parameter != null) width = new Integer(parameter). and the loadParameters method is private void loadParameters() { String parameter = getParameter("width"). Create a loadParameters method and call it from the init method. begin by declaring instance variables for your applet. I would suggest length and width should be the names. else width = 300. parameter = getParameter("height"). decide on the names of your parameters.

ensure you enclose it in quotation marks. create a new applet on the workbench. 2. Thus when you use the statements int width = r. You will need to explore the Graphics class to use these methods. To determine the centre.width)/2. recall that you are specifying the corners of the box surrounding it. Create a simple applet to draw some geometric shapes. int y = (r. Rectangle r = g. Assume for a moment that you use the height and width that BlueJ suggests.x + r. and execute its getParameterInfo method. Modify the getParameterInfo method to explain the parameters the applet accepts. height). When you draw a circle.height)/2. with your name being the default value. width. Create an applet which generates a circle in the centre of its graphics context. It should display the name provided as a parameter. You should probably make sure the applet accepts both the name color (the American spelling) and colour (the Canadian and English spelling). 328 . Modify the applet so it uses the colour provided as a parameter. 0.width / 4. else height = 400.) You may draw squares and rectangles with the drawRect and fillRect methods. to determine the size of the box and then use the statement g. You may draw circles and ovals using the drawOval and fillOval methods. as 0. (An oval is a circle drawn within a non-square rectangle. int x = (r.height / 4. int height = r. Other polygons are drawn using the drawPolygon and fillPolygon methods. To test this method. represented by x and y. 3. The Rectangle that ClipBounds returns has its top left corner. } Modify the applet so it doesn‘t display always your name.if (parameter != null) height = new Integer(parameter).drawOval(x y.y + r.getClipBounds(). Accomplish this by declaring an instance variable and then establish its value in loadParameters. The Rectangle‘s width and height are the values you (or BlueJ) specify when you run the applet. use something like the following statements. Ensure there is an appropriate default colour. If the name you wish to enter contains one or more spaces.

// distance to move radially int hypotenuse = diameter / 20.to draw the circle. Consider the statements below.radius.sin(doubleAngle) * hypotenuse)). height). diameter. You could go directly to your destination. g. 329 .toRadians(angle). g. any direction. you need to use this statement. I chose this distance since it is large enough to see. You will draw a circle in an invisible box. applied to the angle we specified. Thinking again of the right-angled triangle. But the statement above will draw an oval.drawOval(x . They just take different amounts of time. width).min(height. whose top left corner is at the centre of the graphics context. we can‘t determine the lengths of the sides unless we also know the length of the hypotenuse. int deltaY = new Long(Math. int radius = diameter / 2. width. the calculation of the centre of the frame is the same. int diameter = Math. out from its current centre. Both routes get you to the same destination. The first two lines decide the maximum distance the circle will move in a radial direction.drawOval(x . y . through a parameter. double doubleAngle = Math. This involves a little trigonometry. int deltaX = new Long(Math. We have used a loadParameters method to provide a value for angle. To actually draw a circle whose centre is in the centre of the graphics context. If you specify that the applet runs in a non-square frame. not a circle.cos(doubleAngle) * hypotenuse)).radius.intValue(). What value should you use as the diameter of the circle if we really want to draw a circle? I would suggest the minimum of the height and width you have calculated. Make the circle move from the centre along a path whose angle you specify. but small enough that it will take a number of steps to move the circle a long distance. y – height / 2. You could follow a route along the hypotenuse (the long side). We can calculate the distances in the x and y directions by using the cosine and sine functions.intValue(). Think of a rightangled triangle. in degrees. or you could do it in two steps.round( Math.round( Math. diameter).width / 2. When you move in a direction. there are at least two ways to do so. or you could follow a route along the other two sides. move a certain distance in one direction and move a certain distance in another direction. you will not draw a circle in the centre of the graphics context.

The conversions in the last few statements arise because drawOval expects ints while the sine and cosine produce doubles. centreY = centreY + deltaY. repeating as many times as necessary. i++) { // draw the oval in the background colour g. and draw the first circle. When you run the applet. Finally we are at a point where we can make the circle move. but we have specified the angle in degrees.The trigonometric functions in the Math library expect the angle to be in radians. centreY. The distance the circle moves in the x direction is given by the hypotenuse times the cosine of the angle.getColor(). How do you slow this action down? One solution is to use the Timer class defined in javax. which the trigonometric functions expect. // and redraw it somewhere else //in the original colour centreX = centreX + deltaX. diameter. diameter).setColor(fg). Color fg = g. } These statements determine the colours to use. unless you have a very slow computer. But that happens automatically! 4.swing. The toRadians method converts degrees to radians. g. This exercise will use many of the ideas from the previous exercise. giving a double. The circle should appear to vanish as it reaches the edge of the frame. Make the circle move along a path whose angle you specify through a parameter. g.drawOval(centreX. calculate the new location of the circle and draw it there. Its centre is specified via parameters. diameter).drawOval(centreX. The circle should bounce off the edge of the frame and continue on its path.white. diameter). you may not see the circle move.setColor(bg). // default background g. i < 25. centreY.drawOval(centreX. Create an applet which generates a small circle in the graphics context. Color bg = Color. plus you will need to 330 . You may see it only at its last position. Explore that class. diameter. Thus we convert the double to a Long and then extract the int equivalent. diameter. for (int i = 0. g. centreY.Timer. The distance the circle moves in the y direction is given by the hypotenuse times the sine of the angle. Then they redraw it using the background colour (this makes it disappear).

But the Olympic Movement flag would be easy to create. Burkina Faso. This will use much of what you have seen in the previous two questions. Some international organizations. at www.) Assume that you move the ball by deltaX and deltaY.detect collisions between the circle (think of it as a ball) and the edge of the frame (think of it as a wall. If you look at the World Flag Database. Ukraine. and United Arab Emirates.flags. Other easy-to-create flags are Aruba.) When I ask my students to draw flags. Some flags are harder than others due to curved shapes. Afghanistan and Albania are probably impossible to create using Java. are also difficult to create. Bangladesh.net. See Australia and New Zealand. we usually draw the flag of the United Kingdom and then use it as part of the flag of other nations in the Commonwealth. for example the African Union. Hitting a horizontal wall means changing the sign of deltaY while leaving deltaX unchanged. you‘ll quickly find some of these difficult-to-draw flags. 331 . Then. 5. as in the previous exercise. Create a method that allows you to draw a star.) If the edge of the frame is smooth (and it is) the angle at which the circle approaches the edge of the frame is the supplement of the angle at which it bounces off. hitting a vertical wall means changing the sign of deltaX while leaving deltaY unchanged. 6. Then you can consider drawing the flags of the United States (easier) and Micronesia (harder. For example. Libya (probably the easiest of all). Rotate the triangle. because the stars do not all point straight up. Create an applet which generates a triangle in the centre of the frame. for example. Create an applet which creates the flag of your country. They need a star method too. (Two angles are supplements if they total 180 degrees or π radians.

332 .

An architectural example is the pattern called Capturing Light. The name may be pattern. and consequences in a word or two. you can see nine additional architectural patterns at http://www. or standardized ways of achieving certain aims.) They define a pattern as having four essential elements.architectureweek. since the sun rises in the east. Steven John Metsker states that ―A pattern is a way of doing something. or a way of pursuing an intent. or blueprint. or template. This jargon often refers to patterns. The community of people who practice a craft usually invent jargon that helps them talk about their craft. and woodworking. … The problem describes when to apply the pattern. knitting. and Parts in Proportion. The authors are Erich Gamma.com/2003/0423/patterns. Ralph Johnson and the late John Vlissides. Writers document these patterns. This idea applies to cooking. or recipe. helping to standardize the jargon. Often they prefer to sit in the sunlight.Chapter 18 – Design Patterns Learning objectives By the end of this chapter you will be able to:    Define design pattern Use design patterns to help you design classes Use design patterns to help you understand the design of existing classes Introduction In his book on Design Patterns. You can see this in the house described at http://www. or jig. its solutions. collectively they are known as the ―Gang of Four‖ or simply ―GoF‖. so the quiet place should be on the east side of the building.architectureweek. popularised by Christopher Alexander. effective methods for achieving aims and solving problems in various contexts. The word pattern became known in computing with the publication of Design Patterns: Elements of Reusable Object-Oriented Software in 1995.com/topics/patterns.‖ Among the crafts in which patterns are used are sewing.html and. In any craft that is mature or that is starting to mature. developing software. Richard Helm. Sheltering Roof. you can find common. ―The pattern name is a handle we can use to describe a design problem. Many people like to have a quiet place to have their morning coffee.html. and to any other craft. … The solution describes the 333 . They have names like Inhabiting the Site. Writers also ensure that the accumulated wisdom of a craft is available to future generations of practitioners. The idea of patterns in computer science comes from the world of architecture. making fireworks.

Object-oriented design patterns typically show relationships and interactions between classes or objects.org/wiki/Design_pattern. Metsker‘s paragraph which I quoted appears near the beginning of his book. Regardless of the field. and collaborations. and lists many of the patterns that have been published. Wikipedia provides details on the history of patterns within computer science. This is clearly shown in a pattern map from the GoF book. without specifying the final application classes or objects that are involved. but we will also see patterns from other sources. 334 . In this book he shows how to apply the design patterns first publicised in the GoF book. The article begins with the words ―In software engineering. at http://en. It is a description or template for how to solve a problem that can be used in many different situations. a design pattern is a general repeatable solution to a commonly occurring problem in software design. In architecture.wikipedia. … The consequences are the results and trade-offs of applying the pattern. In software engineering a pattern is not a piece of Java code. illustrating the connections between the GoF patterns. responsibilities. in software engineering we have Singleton and Creator. their relationships. It‘s now time to do so.‖ We will see some of the GoF patterns below. we have Capturing Light. A design pattern is not a finished design that can be transformed directly into code.‖ A few of these patterns are independent of the others. Throughout this book we have been using patterns without naming them. Design Patterns Java Workbook. a pattern is a named solution to a problem in design.elements that make up the design. Metsker‘s book shows how to implement the patterns in Java. that would be an implementation artefact. The GoF book describes many patterns. one which has been used by many people to solve a problem. but many work with other patterns.

The basic idea behind this pattern is to describe some capabilities a class may have. For the Serializable interface. 335 . we saw that the capabilities it specifies are the ability to write objects of a class into a format that may be read back easily. for some reason. This pattern is not directly named in the GoF book since the authors were not using Java examples. requires a Serializable object to be used as argument. The Student class implements Serializable. and then leave the classes to provide the details of how those capabilities are implemented. they used Smalltalk and C++ and those languages don‘t support interfaces as Java does. The details of how that is accomplished depend on the specific class. including Serializable and Comparable. a Student object is also a Serializable object. Set and Map. If we have a method which. capabilities which many classes may be expected to have. We have used many Java interfaces in our coding.Interface pattern Here is a pattern that underlies much of the philosophy behind Java. Thus.

wikipedia. It helps you answer the question ―Which class should create new objects?‖ As such it is a pattern that you use while designing your system. With this pattern. If a class implements several interfaces. The problem it is solving is how to write high quality code.org/wiki/Marker_interface Creator pattern This pattern is a simple one. GRASP. College should create new Student objects. For example. Courses are taught by professors.wikipedia. in our college model. The Creator pattern was publicised by Larman as part of his General Responsibility Assignment Software Patterns. More details on this pattern are at http://en.a Student object may be used. Which class should create a new Student object? Which should create a new Course object? Since students are registered at the college. sometimes it will not. but the course continues to be available after the professor has left the college. Serializable (where we may not implement code) and Cloneable (where we will implement code) are both marker interfaces we have used which involve this pattern. a course is taught by a professor. and gives a name to a practice used for a long time. A few more details on this pattern are available at http://en. Thus. High Cohesion This is another of Larman‘s patterns. It is not a pattern you use in solving problems that arise while implementing the system. Many would note that this is a design principle and not a pattern. College should create Course objects. then an object of that class has several types. 336 . code which can be understood by a single programmer. But so too may be a Mark object. A design principle is ―less important‖ than a pattern. since a Mark object is also a Serializable object. Marker interface pattern A specialisation of the Interface pattern is the marker interface pattern. an object which implements a marker interface indicates that it will support the capabilities of the interface. Does that mean Professor objects should create Course objects? No. Sometimes this capability will require us to write code.org/wiki/Interface. we have students and courses.

particularly in the ActionListeners we used while building our data entry screens. it must identify itself to some other object which also listens. This pattern (or design principle) states that a class should do a limited number of things and it should do them well. One object publishes. or sends. while others (the listeners) subscribe to receive those messages. and that those connections be as simple as possible. Observer or Event listener The GoF defines the problem this pattern solves as ―Define a one-to-many dependency between objects so that when one object changes state. and gives a name to a practice used for a long time. An object listens for events and acts on them.org/wiki/Event_listener Delegation This is another pattern which is clearly reflected in the philosophy of Java. To do this. The problem it is solving is how to minimise the connections between classes. but lets other objects know of the events. This pattern is related to the GoF Mediator pattern. We saw this most clearly while using the XMLEncoder. Note that the Checkstyle extension interprets this to mean that a method should have no more than seven parameters. Low Coupling This too is another of Larman‘s patterns. Many would note that this is a design principle and not a pattern. code which attempts to do too much. so that a change in one class has minimal effects on another. This has also been called a ―publish and subscribe‖ pattern. 337 .wikipedia. we replaced the DefaultPersistenceDelegate with one which knew about the collections our object contained. objects appear to possess behaviours but delegate those behaviours to other objects. This pattern (or design principle) states there should be no more connection between classes than is necessary.‖ This is another pattern which is clearly reflected in the philosophy of Java. all its dependents are notified and updated automatically. messages about events. More details on this pattern are at http://en.Something which gets in the way of understanding is complicated code.

wikipedia. Dynamic programming. which we will use with some of the mathematical functions in the next chapter. and provide a global point of access to it. Not all classes have the constructors you would expect. is another use of the lazy initialization pattern. Simply display a splash screen and an hourglass icon until all the screens are ready to use. One school of thought says you should create all the screens before the program displays its main menu. Or suppose you have a program that takes some time to create an index for a document (or some other large. Both of these could be improved by paying attention to the lazy initialization pattern.) Some programs would create the index while you are typing the document.valueOf method. This pattern says don‘t create something until it‘s needed. Factory Like delegation. That could involve a lengthy wait as the program loads. the marks for a student in a course are 338 . We have seen this with the BigInteger.wikipedia. slowing down the program. this is a pattern which is clearly reflected in the philosophy of Java.org/wiki/Lazy_initialization_pattern Singleton pattern The GoF book defines the problem this pattern solves as ―Ensure a class only has one instance. For our college. the various BorderFactory. perhaps you could use the factory pattern to decide how it is created. Note that this is also one of the principles behind extreme programming.create methods. and with BindingFactory. More correctly.‖ We used this pattern when we created the College class. the methods are factories.More details on this pattern are at http://en. More details on this pattern are at http://en. which build objects. complicated data structure.org/wiki/Factory.wikipedia. Suppose you have a program which involves many data entry screens. Other programs would create the index only when requested. More details on this pattern are at http://en. Lazy initialization pattern Perhaps this is a design principle rather than a pattern but it deserves mention. In some cases they have methods which act as constructors. When it is needed.org/wiki/Delegation_%28programming%29. a class which ensures there is only one set of rules which applies to all students.

This allowed for all sorts of problems when values were accidentally changed. dating back to the days when Smalltalk. More details on this pattern are at http://en. We have also mentioned the use of databases. without recompiling the system. was new. the interface is isolated from the details of the model implementation. Note that we have looked at several candidates for the model. independent of the student.wikipedia. If we write the controllers correctly. or the department. MVC is the pattern we have tried to use in creating the GUI for the College. But sometimes. but it can limit the changing of those values. By using controllers. Thus the constructor would need to see it there already was such a method created. There would be only one rule to determine the interest paid on a bank account. Controllers respond to user events and modify the model. the course. Of course. But we wish only one such method. 339 . it is a more powerful technique than using global variables. variables which were known and changeable in all parts of a system. As such. you want to display them as a letter grade. The Singleton pattern allows the retrieval of global values. were we to examine bank accounts as an example of objects. the term ―pattern‖ was not used then. For example. by reading something in from a resource bundle. This is also an example of the application of the Low Coupling pattern. we would find that the Singleton pattern helps us keep the interest rates paid in only one place. many older programming languages used global variables. they too are ignorant of the model implementation. Similarly. It also allows changing values on the fly. That method would know whether XML or a database is being used. the model could have a writeData method which the controller could invoke.stored as a percentage. one of the first objectoriented languages. We would need a class which creates a method to translate these percentages into letter grades. including serialization and XML. The view represents the interface we have created to manipulate and present the data. The controllers are the glue that connects the model and the view. The model represents the data and how it is stored. The college needs to have one set of rules for translating percentages to letter grades.org/wiki/Singleton Model-view-controller (MVC) This is quite an old pattern. As an aside.

org/wiki/Model Summary Patterns are a very important part of design. In the third.wikipedia. while it touches on design. good places to start online are http://en.wikipedia. I wish I could find it! More details on this pattern are at http://en. and the exercises on the next page.A famous example of MVC divides the screen into four quadrants. 340 . In the fourth it is displayed as a table of data. If you wish to look into patterns in more detail (and you may do so in further courses). This chapter has provided a very brief introduction to patterns.com/cgi/wiki?DesignPatternsBook. it is displayed as a pie chart.org/wiki/Design_Patterns and http://c2. that data is displayed as a histogram. In the first you enter data into the model. is mainly dealing with implementation. We are not able to go into them further as this book. In the second.

and Protected Variations. the CD is perhaps better. Note that the GoF book is available on CD as well as in printed format. Composite.Exercises 1. You will become a better designer and programmer when you gain familiarity with these patterns. Bridge. For learning the patterns. Factory Method. Adapter. Their catalogue contains 23 patterns with which you should become familiar. 341 .hillside. These include Information Expert. Façade. These include Abstract Factory. Iterator. Look in Larman‘s book and explore the patterns he discusses. Template Method. Proxy.net/. Chain of Responsibility. One provides the theoretical underpinnings for the pattern. Controller. Flyweight. Prototype.hillside. and Visitor. Decorator. Command. Polymorphism. 4. Pure Fabrication. Low Coupling. Don‘t attempt to become familiar with all the patterns at once. Look in Metsker‘s book and see how the GoF pattern may be implemented in Java. 3.net/patterns/. Interpreter. I suggest you use Metsker‘s book in combination with the GoF book. 2. Creator. particularly the patterns section of the website. Look in the GoF book and explore the patterns they discuss. http://www. Observer. Builder. Memento. State. Singleton. Mediator. Visit http://www. Indirection. Strategy. and the other provides a Java implementation. Explore the links they provide. High Cohesion.

342 .

Suppose you need numbers larger than that. 343 .Mathematical examples Learning objectives By the end of this chapter you will be able to:    Define rational number Define complex number Use Java to create classes which were omitted from the Java libraries Introduction The classes we have created in earlier chapters were all related to computer representations of things in real life. The national debt for a large country may exceed even the limit for a long. Public key encryption using the RSA algorithm involves factoring large numbers. (If there were. and a long contains 64 bits (representing integers from -263 to 263 – 1). Certainly the gross national product for many companies will exceed even the limit for a long. one an 80-digit number. I‘d like to look at some mathematical examples now. an int contains 32 bits (representing integers from -2147483648 to 2147483647). what would that integer plus one be?) Unfortunately computers don‘t work well with large numbers. For numbers. Sometimes a class can represent mathematical concepts instead.Chapter 19 . one of which is available as part of a Java package. a short contain 16 bits (representing integers from -32768 to 32767). We have already seen the limits Java imposes on the size of integers. In early 2007. researchers reporting factoring a 307-digit number into its two prime-factors. a byte contains 8 bits (representing integers from -128 to 127). BigInteger What is the largest integer? Since the time of the Greeks it has been known there is no largest integer. the other a 227-digit number. and two of which we can create ourselves. It took several supercomputers about 11 months to accomplish this feat.

in many cases. bit manipulation.PI). All of these functions are available for floats and doubles. we should look at java. primality testing.Math package The online Java documentation says ―The class Math contains methods for performing basic numeric operations such as the elementary exponential. We haven‘t needed many of these mathematical functions in our calculations so far. you may convert degrees (a circle represents 360 degrees) to radians (a circle may also be measured as 2π radians). please consult any statistics textbook. ints and longs. continued The GCD calculation referred to above is the greatest common divisor calculation. ones which meet tests of randomness but are actually created non-randomly. shorts and bytes are generally not welcome. square root.E) and π (Math. The online Java documentation says ―BigInteger provides analogues to all of Java's primitive integer operators. Maximum and minimum functions are available.lang. BigInteger.Math. But Java is used in the world of science and engineering. and all relevant methods from java. GCD calculation. and vice versa.‖ Method is the term we use in Java. BigInteger provides operations for modular arithmetic. The applet exercises used trigonometric functions.So how do we represent even larger numbers? The BigInteger class comes to the rescue. the Math class provides a way to generate pseudo-random numbers. Finally. The absolute value method (abs) strips the signs from numbers. converting negative numbers to positive ones.Math first. logarithm. 344 . The Math class also provides values for the mathematical constants e (Math. So are trigonometric and inverse trigonometric functions. so many people do need these mathematical functions.lang.‖ To understand that statement.lang. and. while function is the term we use in mathematics. a nice recursive method which we examine in more detail in the next chapter. and trigonometric functions. prime generation. For details of how this is done. Additionally. Logarithm and exponential functions are available. A square root function is available. The java. and a few other miscellaneous operations. Of course.

Note that the constructor for a BigInteger expects the number to be passed to it as a String. while the American number includes only the federal debt.valueOf(n). What is a rational number? 345 . Instead. on the other hand.564.toString().BigInteger. it is not quite comparable to the American figure as the Canadian number includes federal. In both cases. has the constructors you would expect.668.000. int n = 40.com/debt). private BigInteger usDebt = newBigInteger("$12982626754668").982.com/SI/education/debt. To test BigInteger. valueOf is a static method within the BigInteger class. The Canadian national debt (as reported via a Java applet at http://www.red).754.000. 40). g.setColor(Color. you must use the valueOf method.drawString("US debt " + usDebt. the American debt rose by approximately $3. You would need a BigDecimal to represent this exactly. Rational numbers There are two types of numbers which java.000. one without any commas or any other punctuation signs.02. import java. While this is a large number.000. but we can round it to the BigInteger value of $12.Math does not support. via http://www. provincial.754. it has a constructor which accepts a double as its argument. This is an example of the Factory pattern.ndir. you will find there is no constructor which accepts an int or a long. followed by a period and the method.982. a recession happened during the last of those three years.brillig. First we‘ll look at the rational numbers. Between writing this chapter and editing it three years later. BigInteger b = BigInteger.000. that means we use the name of the class. The BigDecimal class.626. g.000.When you look through the methods available in the BigInteger class you see all the variety. I created an applet. If you wish to create a BigInteger from a value already stored in an int or a long.lang. When I checked (2010-05-21. Of course.000.math.000 while the Canadian dropped by approximately $35. the USA national debt it was $12. the same way abs is a static method within the Math class.shtml on the same date) was approximately $702. For example. 20. Then we‘ll look at complex numbers.000.668.626. In it I placed the following statements. and municipal debt.

you are left with ¾. /** * class RationalNumber.  A negative rational number will have its numerator negative and denominator positive. After you remove the common factor (12) from the numerator and denominator. num = n.  Common factors will be removed from the numerator and the denominator. So let‘s create a rational number class. Note that there are some numbers which are not rational numbers.  A rational number with both numerator and denominator negative will be replaced by one with both denominator and numerator positive. // the denominator /** * Constructor for objects of class RationalNumber. if (denom < 0) { 346 . * * @author rick gee * @version may 2006 */ public class RationalNumber { // instance variables private int n. we begin with a constructor and the toString method. denom = d. Following my usual practice. This is a standard programming example in many introductory programming courses. // the numerator private int d. The numerator (36) may be written as 12 * 3. Perhaps the simplest irrational number is the square root of 2. Yes. These are called irrational numbers. int d) throws NumberFormatException { int num. I know that you can find many examples of a RationalNumber class on the Internet. as is 36/48. */ public RationalNumber(int n. The denominator (48) may be represented as 12 * 4.  A zero denominator is not allowed. int denom. those two rational numbers are the same. if (d == 0) throw new NumberFormatException( "RationalNumber: denominator may not be zero"). In fact. ¾ is a rational number.  Zero is represented as 0/1.It is any number which can be expressed as the ratio of two integers. Some rules we will adopt for our rational numbers.

Uses Euclid's algorithm. } return num1. } if (num == 0) denom = 1. For now. else num2 = num2 .n = num. divisor = gcd(Math. int num2) { while (num1 != num2) { if (num1 > num2) num1 = num1 . the constructor should work properly for each.abs(num). } } We‘ll look at the gcd method in more detail later. write unit tests.denom.abs(denom)). num = num / divisor. this. Math. } // initialise instance variables this.num2. denom = . else { int divisor.num1. Consider the following values for the numerator and denominator. } /** * @return a String representation of a rational number */ public String toString() { return n + "/" + d.d = denom. You‘ll need quite a few since the constructor makes many decisions.// handles both -5/-4 and 5/-7 num = . To test this class.    0 and 5 (result should be 0 and 1) 0 and 0 (result should be an exception) 0 and -3 (result should be 0 and 1) 347 . denom = denom / divisor.num. } /** * compute the greatest common divisor of the two * positive parameters. trust me that it works. */ private int gcd (int num1.

n * r.d * r. this method does not need to concern itself with removing common factors at the end. } Notice that we need two getter methods. Have we missed any combinations? Adding rational numbers How do you add together two rational numbers? The mathematical definition of 𝑎 𝑐 𝑎 ∗ 𝑑 𝑏 ∗ 𝑐 + = 𝑏 𝑑 𝑏 ∗ 𝑑 translates into /** * Add two rational numbers. * @param r The second rational number * @return this + r */ public RationalNumber add(RationalNumber r) { RationalNumber result = new RationalNumber( this. nor does it need to concern itself with negative signs. one for the numerator and one for the denominator. multiplying. return result. Notice also that by using the constructor.getDenominator() + this.    1 and 7 (result should be 1 and 7) -1 and -8 (result should be 1 and 8) 2 and -9 (result should be -2 and 9) 2 and 8 (result should be 1 and 4). this.getDenominator()). and dividing rational numbers We leave it as an exercise to implement subtraction 𝑎 𝑐 𝑎 ∗ 𝑑 − 𝑏 ∗ 𝑐 − = 𝑏 𝑑 𝑏 ∗ 𝑑 multiplication 𝑎 𝑐 𝑎 ∗ 𝑐 ∗ = 𝑏 𝑑 𝑏 ∗ 𝑑 348 .d * r.getNumerator(). Subtracting.

if you have a rational number a/b. as are -5 + 5i. That is. we have assumed the numerator and denominator are both ints. the real part and the imaginary part. Being able to make changes like this without disturbing code which uses our code is a result of a design principle called information hiding. (0. 6 + 4i is a complex number. (-5. we could always change them to longs. and 2 – 7i. 4). Recall that a complex number has two parts. the reciprocal is b/a. while at the same time inconveniencing users of this class as little as possible? Complex numbers Another type of numbers that java.lang. 349 .Math does not handle is complex numbers. and (2. and the letter i. What if ints are not big enough? In the RationalNumber class. 𝑎 𝑏 𝑎 ∗ 𝑑 𝑐 = 𝑏 ∗ 𝑐 𝑑 What should happen when you attempt to divide by the rational number 0/1? Does it? Inverting a rational number Implement a method to invert (or calculate the reciprocal of) a RationalNumber. The letter i represents the square root of -1. the sign of the imaginary part. the absolute value of the imaginary part. a number which does not exist. 0 + 0i. Complex numbers are usually displayed as a String containing the real part. -7). What changes would you need to make to the RationalNumber class to use BigIntegers. hence is called an imaginary number.and division. 5). If necessary. But in some mathematics an imaginary number can be very useful. It is also due to the use of the design pattern Loose Coupling. What should happen if you try to invert 0/1? Does it? Converting a rational number to a double Implement a method to convert a RationalNumber to its equivalent double value. without disturbing the code of anyone who uses this class. Thus we have two choices for the implementation of the toString method. 0). For example. Complex numbers sometimes are represented as (6.

d)i (a + bi) * (c + di) = (a * c – b * d) + (b * c + a * d)i Division is a little more complicated. thus extending the areas in which it is applicable. Summary Java is useful for many types of applications.Arithmetic operations and complex numbers Various operations are defined on complex numbers. 350 . (a + bi) + (c + di) = (a + c) + (b + d)i (a + bi) . The real part of (a + bi) / (c + di) is (a * c + b * d) / (c2 + d2) and the imaginary part is (b * c – a * d) / (c2 + d2) Implementing ComplexNumber Make it so. Note that while my first examples show integer values for both the real and imaginary parts.c) + (b . One of its strengths is the ease with which you may add libraries. We have seen this by creating RationalNumber and ComplexNumber classes.(c + di) = (a . they should actually be doubles.

Complex numbers may be represented by x and y as we have done. Learn something about quaternions and implement a Quaternion class. That is. 3.Exercises 1. Just as complex numbers are the extension of real numbers from 1-space into 2-space. The angle may be calculated as the inverse tangent of y over x. Supplement the ComplexNumber class to include accessors for the angle and the radius. but they may also be represented as an angle and a radius. one which accepts x and y and one which accepts the angle and the radius. Complete the RationalNumber class. Why not? 4. 2. Change the datatype to BigInteger. add two new getters. Change the datatype for its instance variables to long. octonions are their extension into 8-space. Just as complex numbers are the extension of real numbers from 1-space into 2-space and quaternions are their extension into 4-space. Describe the effects. quaternions are their extension into 4-space. Describe the effects. Complete the ComplexNumber class. 5. You cannot write a ComplexNumber class that has two constructors. 351 . Learn something about octonions and implement an Octonion class. and the radius is the square root of x squared plus y squared. one for radius and one for angle.

352 .

―Analysis of Algorithms‖ is the study of algorithms (understanding which are better and when) and the development of new algorithms. 353 . use the name AlgorithmCollection. etc. Imagine a class that contained the various constants used in physics and chemistry.Mathematical methods Learning objectives By the end of this chapter. Avogadro‘s number. If that really bothers you. An algorithm will solve the problem in a finite number of steps and it will solve the problem in a finite amount of time. But I‘d like to look at a collection of simple algorithms and the methods which implement those algorithms. the speed of light. you will be able to:         Define algorithm Write methods to implement mathematical algorithms Define iteration.) What is an algorithm? An algorithm is a set of rules that you can follow to solve a problem. Let‘s create a class called Algorithms. (Yes. Planck‘s constant. I know that once upon a time I said the name of a class should be a singular noun. This is similar to the way we have seen different Java statements to accomplish the same result. Imagine a class that contained information on all the chemical elements. Frequently there are several algorithms which solve the same problem. Define recursion Write iterative methods Write recursive methods Write methods that use formulas. Use dynamic programming Introduction Sometimes a class can be a collection of useful constants or methods. It is often a course taken in the second half of your postsecondary (tertiary) study.Chapter 20 .

354 . int num2) { while (num1 != num2) { if (num1 > num2) num1 = num1 .wikipedia.org/wiki/Euclidean_algorithm This method implements an iterative solution to the problem. } return num1. We saw a recursive method in an earlier chapter. All recursive methods have these two parts:   One or more stopping case(s) for which we know the answer. */ private int gcdIterative (int num1.) /** * compute the greatest common divisor of the two * positive parameters. An iterative solution is one in which you perform one step after another. and A statement that calculates an answer by calling the method with a smaller argument. } This algorithm is the Euclidean (or Euclid‘s) algorithm. return gcdRecursive(num2. The code we used is repeated below (but I have changed the name of the method. A recursive greatest common divisor method However. a method develops the solution by making a smaller case of the problem and calling itself again to solve the smaller case. num1 % num2). Here is a recursive solution to the gcd problem. there is also a recursive solution as well. under the control of a loop of some kind. to reverse a String. until you reach your solution. else num2 = num2 . You‘ll see why in a moment.num2. This continues until a smallest case is reached in which you know the solution. Euclid was a Greek mathematician and the algorithm dates back to around 300 BCE and is described in http://en. in this case a while loop. public static int gcdRecursive(int num1. int num2) { if (num2 == 0) return num1. we needed a method to find the greatest common divisor of two numbers.num1. Uses Euclid's algorithm. In a recursive solution.Greatest common divisor (gcd) While creating the RationalNumber class.

since 2 goes into 11 five times. 355 . Now num1 is larger than num2. so it becomes 987 – 42 or 945 while num1 remains 42. and num2 is larger.        We start with num1 = 1071 and num2 = 1029. The second number is zero. num1 and num2 are not the same. The second number is not zero. since it has a number of unterminated methods in memory at one time. 1071 = 3 * 17 * 21 and 1029 = 7 * 7 * 21 so 21 is the largest integer which divides both. The second number is not zero. 21. and 1071 % 1029 is the remainder when we divide 1071 by 1029. The numbers are not the same. 21). Both forms of the algorithm produce the same answer (That‘s good!) but the second requires more memory. Now both num1 and num2 are 21 so the algorithm terminates and the greatest common divisor is 21. In fact. num1 and num2 are not the same. so becomes 42 – 21 or 21. Before we can return an answer. 42. and 1029 % 42 is 21. For the iterative solution.       We start with num1 = 1071 and num2 = 1029. greatest common divisor. while num2 remains 1029. or 42. and num2 is the larger. and 42 % 21 is zero. but now num2 is the larger. Hence the name. Sample greatest common divisor calculations Perhaps we should work out an example to see how the iterative and recursive methods work.} Remember that the modulus operator (%) calculates the remainder when you divide the first integer argument by the second. Before we can return an answer. Before we can return an answer. For example. we need to calculate gcdRecursive(1029. and so num1 becomes the difference. 11 % 2 is 1. num1 and num2 are not the same. so we return the first number. since it requires more steps. 42). The first may require more time. For the recursive solution. until it becomes 63. The second number is not zero. we need to calculate gcdRecursive(42. so it becomes 1029 – 42 or 987 while num1 remains 42. removing 42 from num2 each time. Wikipedia uses 1071 and 1029 as the two numbers for which we wish to find the greatest common divisor. This continues. 0). unterminated. with a remainder of 1. methods can return 21. num1 is the larger. we need to calculate gcdRecursive(21. Now all the waiting. so num2 becomes 63 – 42 or 21 while num1 remains 42.

F(n) = F(n . 1. If we are going to use it in outside our class. The series derives its name from Leonardo of Pisa. F(1) = 1. 21. The values in the series are 0. 2. in functional notation: F(0) = 0.org/wiki/Fibonacci. This is because Fibonacci was dealing with questions about the breeding behaviour of pairs of rabbits and it is difficult to breed more rabbits if you have no pairs. Fibonacci wanted to know how many pairs you would have.gcdRecursive(int. Declaring a method static says that this method is a method belonging to the class. Fibonacci numbers If you read or saw The da Vinci Code.wikipedia. which are described below. dating back to 200 BCE. you will soon have many. 356 . 1. meaning son of Bonaccio). Leonardo was posthumously given the nickname Fibonacci (derived from the Latin words filius Bonacci. the second (F1) is one. other classes may call the method using the Algorithms. Of course.Once you have the algorithm explained in a recursive form. In combination with declaring the method public. 3. 2. It is a singleton. 34. 55. Wikipedia has some interesting examples at http://en. where the first number (F0) is zero. etc. functioning as the answer to the secret question if you forget your account number. 5. This series of numbers occurs in many places in the world. it will need to become a public static method also. Note that the iterative method was a private method. 8. it seems like magic the way the method works. if you have one pair. Mathematicians tell us that the worst performance for the gcd function occurs when the numbers are consecutive Fibonacci numbers. the series starts at 1.2) when n > 1 Sometimes. That is. 13. both natural and mathematical.1) + F(n . It is not a method which belongs to instances of the class.. you have seen Fibonacci numbers. They were the first line of numbers written on the floor of the Louvre. int). and every subsequent Fibonacci number is the sum of the previous two. 1. His father was nicknamed Bonaccio (―good natured‖ or ―simple‖).

public static int iFib(int n) { int f0 = 0. One of the bits is the sign bit. int f1 = 1. /** * recursive Fibonacci. it may change from a positive number to a negative one. and there are one or more ―smallest‖ problems for which we know the answer. 357 . That‘s what happens here. When the calculations in the other bits result into a carry into the sign bit. int t. How long does it delay the problem? Recursive Fibonacci method Here is a recursive method to find the nth Fibonacci number. How can two positive numbers added together become negative? It has to do with the way numbers are stored as bits. Changing from int to long only delays the problem. } return f0. f1 = t. * @param n The position of the number we wish * @return the nth Fibonacci number */ public static int rFib(int n) { if (n == 0) return 0. iFib(46) looks okay. } We know that there is a limit to the size of ints so we would expect there is a limit to which Fibonacci numbers we can calculate. if (n == 1) return 1. i < n. The result is obviously wrong.Iterative Fibonacci method Here is an iterative method to find the nth Fibonacci number. but iFib(47) is negative. f0= f1. return rFib(n-1) + rFib(n-2). } Recall that recursive method work by trying to solve successively smaller problems using the same method. i++) { t = f0 + f1. The definition of Fibonacci numbers provides a blueprint for a recursive implementation. for (int i = 0.

We‘ll see how to do that later. If we are going to use these Fibonacci methods for large values of n. The recursive definition of factorial is:  Zero factorial is defined. you‘ll find that it works.2) The plus or minus signs are equally likely and are chosen independently. Perhaps your machine is faster than mine. T(1) = 1.5. written in mathematics as n!. 358 .If you run this method. we will need to go to BigIntegers. Note that the Fibonacci numbers we discussed have an interesting.ams. I never did see what it would calculate for rFib(46). it is possible to calculate F(n) via a formula.1) ± T(n . but different. for convenience. as 1. but he proves that they have an interesting behaviour. His article (available at http://www. n factorial is defined as n times n . This is an example of the factorial function. pronounce ―feye‖ or ―fee‖) or approximately 1. behaviour themselves.1 factorial. you will find that this ratio comes closer and closer to the golden ratio (φ. T(n) = ± T(n . I was too frustrated waiting for it to finish. and we will have to do something about the speed of the recursive method. but it gets very slow for larger values of n. In addition.  For any other positive value n. The factorial function How many ways are there of arranging 10 people in a line? The answer is 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 or 3628800. The Wikipedia article mentioned at the beginning of this section also has some interesting generalizations of the Fibonacci series. The iterative definition of factorial is:  Zero factorial is defined. F(n) is the largest integer less than (φn/√5) + 0. n factorial is defined as the product of all integers from 1 up to and including n. When you calculate the ratio F(n + 1) / F(n) for a number of values of n. One that I find particularly interesting was explored by Divakar Viswanath. The random Fibonacci sequences are defined by: T(0) = 1.html) points out that it is not clear what will happen to the numbers in this series.618034. for convenience. as 1.org/mcom/2000-69-231/S0025-5718-99-01145X/home.  For any other positive value n. perhaps using a cointoss.

written 5!). i++) result = result * i. } Both of these calculate 16! successfully and then overflow when you attempt to calculate 17!. This unusual expression is evaluated as 15! / (10! * 5 359 . i <= n. for (int i = 1. * @param n The value whose factorial * @return n factorial */ public static int rFactorial(int n) { if (n == 0) return 1. 15 .The first of these definitions leads to this implementation of the iterative factorial function. int result = 1. return n * rFactorial(n-1). * @param n The value whose factorial * we wish to calculate * @return n factorial */ public static int iFactorial (int n) { if (n == 0) return 1. return result. /** * recursive factorial. } The second definition leads to this implementation of the recursive factorial function. how much further could we go? The choose function How many ways can you choose five volunteers from a group of 15 people? Assume that the order of the volunteers doesn‘t matter. If we used long instead of int. /** * iterative factorial. The answer is 15 choose five.

if (n == k) return 1. } Unfortunately it does not give correct answers in many cases. Note that 1 if k = 0. * @param n the size of the pool * @param k the number to be chosen from the pool * @return n choose k */ public static int rChoose(int n. but a formula that uses one of the factorial methods.org/wiki/Choose for a discussion on this form of the algorithm. k). and 𝑛 𝑘 𝑛 𝑘 is also defined as: = 𝑛−1 𝑘−1 + 𝑛−1 𝑘 otherwise.n)). this method is very simple to write. k .A Formula! In Java. It is simply a formula.the number of ways to * choose k items from n.1) + rChoose(n .wikipedia. or n = 0.1. See http://en. due to the overflow problems we have noticed earlier. or n = k. * @param m the size of the pool * @param n the number to be chosen from the pool * @return m choose n */ public static int choose(int m. Recursive choose method One such more-intelligent algorithm is a recursive one. return rChoose(n . } 360 . or we could use a more-intelligent algorithm. We‘ll use a more-intelligent algorithm. It is neither iterative nor recursive.1. int k) { if (k == 0) return 1. which gives rise to this recursive method. /** * the number of ways to choose n items from m. if (n == 0) return 1. How could we modify it to work properly? I suppose we could use longs or BigIntegers. /** * recursive choose . int n) { return iFactorial(m) / (iFactorial(n) * iFactorial(m .

if (n == 0) return A(m-1. The function is fully-described at http://en.This method gives valid answers in many of the cases for which the previous version did not. return A(m-1. that is. A(4. n) is n + 1 for any non-negative n. A(m. The definition of the Ackermann function tells us that A(0. 1) A(m. n) is defined for non-negative m and n as follows:    A(0.1. n . } But the table referred to above does offer some ideas on how to calculate this function more efficiently. First. /** * Ackermann function. unless you have some time to wait. Addition is less likely to overflow than multiplication since the numbers involved are smaller. int n) { if (m == 0) return n + 1. the numbers become very large very quickly. Definition of the Ackermann function The Ackermann function A(m.1)) Recursive implementation of the Ackermann function This leads to the obvious recursive implementation. * @param m The first parameter * @param n The second parameter * @return A(m. The Ackermann function This is a truly fascinating function.Do not try to calculate the Ackermann function for large values of m and n. Look at the table on that page to see why you should not calculate this function for large values of m and n. it has been done. n) = n +1 A(m.1) is too large. Secondly. Sometimes there are closed forms for the function. Warning . there is a formula which gives you an answer immediately. A(m. n-1)). n) = A(m . n) */ public static int A(int m. It has its origin in the design of operating systems and was designed specifically to produce problems while running programs. 0) = A(m . 361 .wikipedia. 1).1.org/wiki/Ackermann.

n) = 2(n+3) – 3 This last equation would be implemented as Math.0. n + 3 is not. although there are a few values calculated which we could use. n) as well. (double(n + 3)) – 3. A(2. n + 3) to be doubles. Thus. a technique which remembers the results of previous calculations. a data structure we have used earlier. A(1. We want a data structure that is efficient in returning values. and Fib(n)). Dynamic programming Dynamic programming. there are no simple formulas.0 is a double.Fibonacci We want a data structure that allows us to store two ints (n.0 instead of 3. As we have seen. a description which even mentions the Fibonacci numbers we have examined already. We will use n as the index and Fib(n) will be the value in the element. That idea of calculating and saving values is the idea behind dynamic programming. however. n). 362 .0) and the exponent (in this case. Here‘s the new version of the recursive Fibonacci method.wikipedia.0 Note that the Math. What type of data structure do we use for the table? When do we create it? Do we want to save it and if so.org/wiki/Dynamic_programming. n) = n + 2 A(2. create an ArrayList<Integer>. and A(3. We can. 2. rFib. the Algorithms class needs the following statement. how do we save it? Storing the data . Why does it mention them? Obviously because to calculate Fib(100) you need all the Fibonacci numbers less than Fib(100). is described at http://en. One such data structure is the ArrayList. n).pow method expects both the base (in this case 2.pow(2. it would be much more efficient to simply look up the value in a table rather than to recalculate it. This statement conceals several questions. We want a data structure that will grow without any special effort on our part.The table gives us closed forms for A(1. so we must cast it to a double. So if you follow up the calculation of Fib(100) with a request for Fib(50). Dynamic programming involves calculating and keeping the table. n) = 2 * n + 3 A(3. We could have the same effect by using 3. But we can‘t create an ArrayList<int>. private static ArrayList<Integer> fibData = new ArrayList<Integer>(). For other values of m and n. Integer is a wrapper class for the primitive datatype int.

Then right-click the Algorithms class in the class diagram. But what if we wish to serialize the data so that we can use it again next week or next month? 363 . this places an instance of the class on the Object Bench. The constructor I used above creates an ArrayList of 10 elements. and choose rFib to calculate some Fibonacci number. Any time we calculate another value. right-click the object on the Object Bench. return x. follow these slightly-strange instructions.add(n. not on the Object Bench. } // is the answer in the arrayList? // if not. new Integer(1)). it grows. fibData. Finally.intValue(). and inspect it. but the details of how it grows are not described in the documentation.add(1./** * recursive Fibonacci * @param n The position of the number we wish * @return the nth Fibonacci number */ public static int rFib(int n) { int result.add(0. To see that this actually works. } } We have loaded the ArrayList with the smallest set of values.isEmpty()) { // Contains no values so load a few fibData. and choose new Algorithms(). return result. we will add it to the ArrayList. new Integer(0)). calculate it and put it there try { Integer x = fibData. new Integer(result)). if (fibData. Right-click the Algorithms class in the class diagram.get(n). What is the size of the ArrayList and what are its contents? The answer depends on which Fibonacci number you calculated and which numbers you have calculated in the past. you will sometimes find a number of null elements at the end of the ArrayList. } catch (Exception e) { result = rFib(n-1) + rFib(n-2). the values specified in the definition of the function. As a result of this growth. fibData. particularly its static fields. When it needs more elements.

If the method were associated with an object. i < fibData. When we restore the file. when we serialized various classes in our college model. we will restore the value to the correct place. This section uses XML serialization.bean.writeObject(fibData. As such. // fibdata exists.trimToSize(). try { XMLEncoder e = new XMLEncoder( new BufferedOutputStream( new FileOutputStream("fibonacci.xml"))).XMLEncoder. we could use the finalize method which is invoked by the garbage collector.util.writeObject(i). While this may seem overly complicated for a couple of integers (and it is). Recall that we are using a static method. Thus we need to add the following statements to our static method. We need to have three import statements. We declare the table of data values.Fibonacci We have seen how to serialize data before. for the List.close(). } catch (IOException e) { // can't write.util. the ArrayList. import java.List. it must read and write its own files. 364 .xml. so remove any extra elements // and then try to serialize it fibData.Serializing the data . in fact. it will work well as we deal with functions of more than one variable. import java. maybe in an applet } // end catch } This will create the file.get(i)). When we create the file. } e. But this does not work with static methods. // private instance variables private static List<Integer> fibData = new ArrayList<Integer>(). and for the XMLEncoder. e. we will store the index and the value.size(). import java. for (int i = 0. previous chapters contained two ways to serialize data. fibonacci.ArrayList. i++) { e.

fibData. it checks if the file the method wrote earlier exists. so start with // minimal set of values fibData. } catch (IOException e) { } // end catch } When we use the method. fibData.add(i.isEmpty()) { try { // does the file exist and is it readable? XMLDecoder d = new XMLDecoder( new BufferedInputStream( new FileInputStream("fibonacci. } // end try catch (FileNotFoundException fnfe) { // cannot find file. Storing the data – Ackermann function The Fibonacci method implements a function of one variable. new Integer(0)). if (fibData.add(0. we need the following statements. new Integer(1)). it checks if there already is data in the table. Integer value. if so. while (more) { try { int i = (Integer) d. value).Run a unit test and see what is stored in the file.readObject(). we create the table ourselves by adding the two values we need. Deserializing the data .close(). we load the data from it into the table. } catch (Exception e) { more = false. If not. value = (Integer) d. of courses. at the beginning of the method. 365 . so we can use that one variable as the index for an ArrayList.readObject().add(1.Fibonacci To retrieve the data stored in the file. // read as much data from the file as possible boolean more = true.xml"))). and the value of the function is the element for the ArrayList. If not. } } d.

a result.Map.) import java. We declare the variable private static Map<Point.awt. Integer> ackData = new HashMap<Point. n).util.) The datatype Point. as the Ackermann function is a function of two variables. A(m. Recall that a HashMap provides a key (the two parameters to the function) and a value to which the key maps (the value of the function. new Integer(result)). import java. if (m == 0) { result = n + 1. n-1)).put(new Point(m.HashMap. n). n). } else { result = A(m-1. } else { if (n == 0) { result = A(m-1. import java. ackData. we serialize three. new Integer(result)). But instead of serializing two Integers. so we can‘t use an ArrayList.put(new Point(m. although designed for graphics. new Integer(result)). we need a HashMap. Integer>().But the Ackermann method implements a function of two variables.util.put(new Point(m. we add it to the table of remembered data. Deserializing the data – Ackermann function We can use the deserialization technique we used in the Fibonacci function to serialize the Ackermann function. 1). 366 . (Note that we could have used a HashMap with the Fibonacci function. Instead. ackData. } } Serializing the data – Ackermann function We can use the serialization technique we used in the Fibonacci function to serialize the Ackermann function. ackData. Whenever we calculate.Point. will serve as our key. the key would be one integer and the value would be the other.

Of course. it is always possible to create a number so large that the memory of the computer is not large enough to hold it. and using (for the Fibonacci and Ackermann functions) dynamic programming techniques. should we wish. The other methods in this class don‘t need. dynamic programming. 367 . The main problem some of these methods have is that the results become large very quickly. using iteration and recursion. there is always one bigger. We can address that with the BigInteger class.Summary We have seen how to write several mathematical functions. That‘s the fun of working with numbers. but could use.

1 items lined up. Modify your Fibonacci function to use at least longs if not BigIntegers. Explore Pascal‘s triangle and the functions associated with its elements. Explore the Sierpinski triangle. 3. until the last child gets all the items (if any) after the last item removed. The second child gets all the items (if any) up to the second item removed. Recursion appears in many graphics situations. The first child gets all the items (if any) up to the first item removed. 6. the number of ways to do it is +𝑛−1 calculated as 𝑚𝑛−1 . Write a method to calculate this function. Use your Fibonacci functions to explore the ratio F(n + 1) / F(n) as n increases. 5. Write a class that contains some of the chemical elements and their properties. Explore the Koch snowflake. How does this formula arise? Imagine m + n . Use this formula to allow you to calculate the expansion of (x + y) raised to the power n. If you wish to divide m presents among n children. 4. Implement a class that contains some of the physical or chemical constants.Exercises 1. Create a method which will draw the snowflake. And so on. in either its iterative or recursive form. 2. 368 . Remove n – 1 of them. Create a method which will draw the triangle. One such function is the choose function.

wikipedia. there are some issues relating to threads which we should discuss. Threads . It then reuses the memory for new variables. For now. and all the code we have seen works. 369 . other processes are running on my computer. In particular.) and both are running at the same time as the thread that allows me to type the document. which itself may have threads (checking for appointments and incoming mail. Simultaneously. You‘ll see how threads and processes interact in an operating systems course. but these processes are part of another program. we need to consider how threads work in Java. A spell-check thread is running at the same time as a grammar-check thread (or maybe one thread is doing both checks. But it is not all well-written Java. for example. and input using the Scanner class Introduction We have looked at many aspects of creating solutions using Java.org/wiki/Thread) defines a thread as ―a way for a program to split itself into two or more simultaneously (or pseudo-simultaneously) running tasks.Threads.definition Wikipedia (http://en. I don‘t know for sure. A phrase appears underlined (in my case in green) to indicate a grammar concern. and other topics Learning objectives By the end of this chapter you will be able to:      Define and use threads Define and use inner classes Define refactoring Explain public static void main(String[] args) Perform output using the System class.Chapter 21 .) The Java interpreter uses a garbage collection thread to identify objects for which there are no references.‖ Have you ever been working in your word processor and made a spelling or grammar mistake? A word appears underlined (in my case in red) to indicate a spelling mistake.

events may not be handled immediately if a previous event is being handled slowly or if many events are happening at the same time. the queue itself will keep the screen displayed until it is ended.setVisible(true). box. EventQueue. menus. an event-dispatch thread is listening for events and the notifying the appropriate handlers. Thus. 100). Events are placed in a queue (first in. box.setPreferredSize(500. it may be called from different threads without unwanted interaction between the threads. Here is the code to create a thread-safe GUI or applet. These have the potential to fail at some point because we did not consider threads. // // while (box. as indicated by the shading. The deleted statements made sure the data entry form remained on the screen. 300). We wrote a number of data entry screen and menus. we have added a few statements. first-out) and the event-dispatch thread removes them as appropriate. we responded to events which occurred to these components. box. That is. Then we have deleted a couple of statements. These create a Runnable object and then place that object on the event queue. For these components. 370 .Threads and Swing Threads are most relevant for our data entry screens. I have used the GUI for entering MyDate values.invokeLater(runner). } }.setLocation(100. public static void showDataEntryFrame() { Runnable runner = new Runnable() { public void run() { JFrame box = buildDataEntryFrame(). We wrote data entry screens for MyDate and for Section. using Swing components. Pay particular attention to the lines with shading and the commented lines.exit(0). and applets. Now that the data entry form is on the event queue. } Note that we have made only a few changes. First.isVisible()) {} System. In the background.

‖ There are several types of inner classes. Let‘s see how to do that. The actionPerformed method then is a series of if statements. but it is one we have been using occasionally from near the beginning of this book.demo program for COSC 111/121". if (source. "About". the one we have used the most is the anonymous class. As a consequence. identifying the source of the item.equals("Exit")) { System. } if (source. we needed to indicate that the CollegeMenu class was responsible for handling events associated with that menu item.exit(0).wikipedia.getText(). the class is required to implement an ActionPerformed method. JOptionPane. }. It was our use of inner classes that made it necessary to declare come components of the GUI as final.) are anonymous classes.INFORMATION_MESSAGE). The Comparators we have used while creating collections (and specifying the order of elements within the classes. when we created the Section data entry screen. } // do something for each menuItem return.getSource()). The first event handler we created in the GUI should have been a series of event handlers. Recall that we created a CollegeMenu class which implemented the ActionListener interface. implemented as anonymous classes.equals("About")) { // display message box JOptionPane. An inner class is defined in Wikipedia (http://en.getText(). public void actionPerformed(ActionEvent e) { JMenuItem source = (JMenuItem)(e.Inner classes This topic is often considered to be an advanced topic.org/wiki/Inner_class) as ―a class defined entirely within another class.showMessageDialog(null. menuItem. and doing an appropriate action. 371 . indicating they would not be changed by the actions in the inner class. The InputVerifiers we used are anonymous classes. Note that we have seen this trick. "CollegeMenu .addActionListener(this). For each item on the menu.

it would be better to simply assign the same ActionListener. Here is the listener for the exit menu. } }. After all.addActionListener(exitListener). you can use inner classes and create the actionListener as follows.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System. what if there were several ways to cause the same event to happen? You‘d need to repeat this code several times. We should specify a separate listener for each item on the menu.exit(0). we need to ensure the exit menu knows about this listener. this actionPerformed method becomes longer and longer. we have seen good code. and more and more complicated. 372 . and we do this with anonymous classes.exit(0). When we create that menu item. Refactoring Throughout this document. As we move listeners out of the original actionPerformed method. but not always great code.As the number of items causing events increases. we need menuItem. we need to add a comment to it. menuItem. We have seen code that a programmer would write if he or she was unaware of some of the latest advances in software engineering. } } But this is not something I‘d like to see. /** * handle events for which there is no separate listener */ If you wish to have very complicated Java code. Of course. It becomes less and less cohesive since it is making more and more decisions. /** *action listener for exit menu item */ ActionListener exitListener = new ActionListener() { public void actionPerformed(ActionEvent e) { System.

and the getters and setters. We will surely use these in other places. In each. Recall that we created unit tests for Student and Professor. we should move the Comparators to another class. In it we would have constructed one or more objects and then invoked the methods we wished to test. possibly better. Wikipedia (http://en. Suppose you wish to create a GUI for an application. We have developed them for year. We started to develop one for rooms. How do you run programs when you don‘t have BlueJ to help? You create a main method in your class.In particular. You will create a class which generates and displays the GUI. and then use them as necessary. But not everyone uses BlueJ. declare them static. We have used BlueJ to allow access to the methods of our classes and objects. Thus. and use them as necessary.wikipedia. as the College application expands. That class will contain a main method. However. you may be running from the command line. This idea of improving the structure of your design and its resulting program is the foundation of refactoring. Can you find other places in the code we have seen which would benefit from some refactoring? public static void main(String[] args) Now we can look at the statement with which most Java books begin. Depending on the testing you wish to do. day. too. one thing that we have done is to create Comparators within the class that needs them. we tested the constructors. you create a method whose name is main and whose signature is the heading for this section. while explicitly preserving its meaning or behavior. month. declare them static. there may be a main method for each class you wish to test. We have been fortunate that they were only used in that one class. Without an integrated development environment like BlueJ. example of InputVerifiers. So we should move them to another class.org/wiki/Refactoring) gives this definition. ―Refactoring is the process of rewriting a computer program or other material to improve its structure or readability. Suppose you are testing. That is. 373 . If we didn‘t have BlueJ we would have needed a main method. and BlueJ has its limitations. we may find that we need those Comparators in other classes as well. the toString method. Similarly we have the. and time.‖ That definition would even include using constants like MAX_MEETINGS in place of the number 5.

If you are using the command line.java to compile the class. static tells us that there is only one copy of this method in this class. void tells us that when the method completes its processing. the arguments are placed on the command line after java SomeClass. To see how to use it. which is accessible within the main method. the second in args[1]. 374 . this will be the tool you use for input.out. the first one is placed in args[0]. The arguments are provided as elements of the array of String called args.println as a way to display output. BlueJ created this for us in the background. Input and output We have seen System. It has to be so that others can invoke it. But Scanner is occasionally useful in the BlueJ IDE. it just completes. String[] args tells us that we can provide arguments to the main method. public static void main(String[] args) public tells us that this method is available outside the class. main tells us the name of the method. Yes. it doesn‘t return any special value to the operating system. To execute the main method of SomeClass. The Java interpreter expects to find a main method. How do we input from the command line? The Scanner class is used for input. We have not needed it since we are using the BlueJ IDE. If you will be using your program in a command line environment. look it up in the Java online documentation for more details. you‘ll need to use the command java SomeClass and the Java interpreter will look for a method named main. similar to the way we provide arguments to applets.You‘ll need to use the command javac SomeClass. Let‘s examine the parts of the header for this main method.

Summary This chapter completes our discussion of the Java language. 375 . Now you have a good basis for going forward and using Java. since this is only an introduction to Java. and for learning more about Java.

376 . 4. Modify the CollegeMenu so that it uses inner classes.Exercises 1. 3. 2. Modify the data entry screen for the Section class so that it is thread-safe. Modify the data entry screen for the MyDate class so that it uses inner classes. Modify the data entry screen for the Section class so that it uses inner classes.

Customisation – How do you allow people to change the colours of your interface? How do you allow them to change the way courses and rooms are numbered? Program standard OO examples. Databases.In Conclusion Now we have seen how the basic (and some not-so-basic) techniques of Java allow us to implement our ideas. The most common one is different types of bank accounts. Sports players and their teams. Include subjects taught and when as a separate class. Here are some possible areas you may wish to explore to build upon the knowledge you have gained here. degrees (where. A related example of inheritance. See the appendix for the labs I used while teaching a course using this textbook for the first time. How to normalize them and how to use them with Java programs. phone number. subject. when). This environment will use inheritance and the Singleton pattern to provide interest rates. 377 .      Professor class – office number. Go forth and expand your knowledge.

378 .

4-8 Metsker. Design Patterns: Elements of Reusable Object-Oriented Software. 3rd ed. James H. Testing First: Emphasizing Testing in Early Programming Classes. 2007 Paterson. No Starch Press. number 3. Let’s Modify the Objects-First Approach into Design-Patterns-First. number 3. Code Craft. volume 51. Brian. The C Programming Language 2nd ed. ACM SIGCSE Bulletin. Chenglie. 2007 Gamma. and Greg Wilson. Communications of the ACM. 280-4 Pecinovský. Pete. 2002 Oram. 3rd ed. and Dennis Ritchie. and Amber Settle. Craig. Prentice-Hall 1988 Larman. Andy.. Timothy Java phrasebook. Richard Helm. Addison-Wesley. volume 37. Ralph Johnson. Addison-Wesley. John Haddow. Jarmila Pavlíčková.References Printed Reference materials Fisher. Prentice Hall Ptr 2004 Marrero. O‘Reilly. 19-21 Kernighan. John Vlissides. John The Definitive Guide to Java Swing. Will. A Design Patterns Extension for the BlueJ IDE. Sams Publishing. Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development. 2007 Hu. 188-92 Zukowski. Beautiful Code: Leading Programmers Explain How They Think. Rudolf. Erich. Michael Nairn. ACM SIGCSE Bulletin. Steven John. 1995 Goodliffe. APress 2005 379 . volume 38 number 3. Design Patterns Java Workbook. ACM SIGCSE Bulletin. Just Say ―A Class Defines a Data Type‖. Luboš Pavliček. volume 38 number 3.

javapractices. http://java. James.org http://www. Java online documentation.com Paul.html Unicode.org 380 .onjava. Cay. http://en. and authors who need to produce simple UML diagrams quickly. Brian. Thomas.javaranch.html (viewed 2006-05-20) Elliott.junit.sun.html O‘Hanley. Inside RelativeLayout.com/javapro/2004_04/online/rule5_04_07_04/ Liu.sys-con. http://www. RelativeLayout. http://www. J.sun.wikipedia. Adam. http://java. http://code.ftponline. http://www.org/mhonarc/lists/gef-dev/msg00469.org.html.horstmann. RelativeLayout. Ganesh. James. Part 2 – The Set Interface http://www. and Anastassia Drofa. Java tutorial.html (viewed 2006-05-20) Ellis.com/pub/a/onjava/2002/11/27/layout2.html JUnit.com/p/relativelayout/ (viewed 2010-05-21).bluej.com/read/564291. Elliott.com/pub/a/onjava/2002/09/18/relativelayout. http://java.com/violet Violet is intended for students.com/javase/6/docs/api/index.onjava. Gina Assaf.org Kolawa.F.com/docs/books/tutorial/index.Online references BlueJ – the interactive Java environment. Rule 5: Make your clone() method final http://www.google.eclipse. http://dev. S. http://www. http://www. Collections in Java.htm (viewed 2008-05-27) Horstmann. Uncommon Java Bugs.org Wikipedia. John.org. a Constraint-Based Layout Manager. Rachael Bennett.unicode. and Roberto Scaramuzzi.com/newsletter/July2002/setinterface. http://www.G. teachers.

but not identical too. Modelling a lacrosse league presents many interesting problems in object-oriented analysis and design and lots of opportunities for student learning. In particular. I needed a series of lab assignments. a sport popular in Canada and parts of the United States. supplemented with additional information I had to provide to the students as they were not familiar with much of the material discussed. You may find the assignments useful. 381 . the examples used in the textbook. My son used to play box lacrosse. I provide the assignments I used. I needed some assignments which were similar to.Appendix 1 – Sample lab assignments Introduction The first time I taught a course (The course extended over two 13-week semesters. The slogan on the T-shirts was ―Real athletes play sports.) based on this book.‖ Details on lacrosse and links to teams and leagues will be given in lab assignment 1. A lacrosse league provided the first few assignments. great athletes play lacrosse. The subsequent assignments followed the topics in the textbook. In this appendix.

0 Documentation as well.) I encourage you to install this software on your home computer. a list of print requests.org/download/download. One reason for disappearing jobs is that your name is not visible on the job. Hint. and there may be others with a higher priority. What programs can you use once you have logged in? The College provides many programs. you also need to have an account. At the moment. Microsoft Office is available for your word processing. in YYMMDD format.html. When is this lab available? The answers for our labs are available online. I mention this as you may find it difficult to gain the access you need to the computer lab and you will be using the software a lot. So let‘s look at how we use BlueJ. Note that the two major programs we will be using in this course (and the following course) are available for free on the web. hint! The programs mentioned above may be used in many courses. Make sure that you download the J2SE 5. Do not submit a repeat request until you are sure that your job has disappeared. The BlueJ environment is available at www. but it will not remain that way if you abuse the privilege. This account has your student number as the username. As a result. and do not print multiple copies unless absolutely necessary. spreadsheet. your job may not start printing immediately. Ensure that you can log in to your account. and your date of birth as the password. There may be other jobs in the queue which arrive before yours. 382 . printing is free. that page also provides a link to download the Java software (you want the latest version). print only what you need to print. you need to become comfortable with a programming environment named BlueJ.sun. Maple is available for your calculus course. To use a computer lab.Lab Assignment 0 .Getting to know you Objectives: The purpose of this lab assignment is to see and become comfortable with the computing environment you will be using in this course. and database needs.com. The parts of the Java language are available from java. Procedure: Computer labs at the College are available during scheduled lab times and at other times. Both Internet Explorer and Firefox are provided for your web browsing. Note that your print requests are put into a queue. J2SE 6 became available. In particular. You may print from these programs to a shared printer. (During the course. when lab monitors are available.bluej. So.

BlueJ appears as a typical Windows application. You can see that the two species are related from the common family name Cyanocitta. maximise. Cyanocitta steller. Below the menu. Once we begin to work with a project. You will see something like the screen below. generally found in the eastern part of North America. on the left. show a bird called the Blue Jay. click the icon. A menu appears below the title bar. and close the program. these buttons will become enabled.The icon and the BlueJ website. it wanders as far west as British Columbia. Blue is … Anyways. BlueJ is a programming environment for programming in the language Java and J is an abbreviation for Java and.bluej. a collection of classes. On occasion. The title bar contains the name of the program plus buttons to minimise. Why is the Blue Jay on the icon? I guess it‘s a play on words. at www. The Steller‘s Jay is the official bird of British Columbia. Cyanocitta cristata. are a number of disabled buttons. In western Canada we have the Steller‘s Jay.org. 383 .

Below that is a message area. The ―View‖ option allows us to customise the appearance still further. Now we consider the Help menu. BlueJ displays a diagram representing the classes we use in our project.Below the menu. the ―Documentation‖ option analyzes the documentation we have created and formats it nicely. There are options for all these. translating them into the bytecode the Java interpreter processes. The first option is ―Project‖. in some cases a project will represent your work over several weeks. 384 . The ―Preferences‖ menu includes things you change less-frequently. This option allows you to create and remove classes. For example. Below the column of buttons and the class diagram is another window or two. let‘s look at the menu. including the class diagram and/or the source code. Perhaps we need to compile them all. For now. This documentation is created from simple statements we insert in the code. empty project (―New Project‖). The ―Testing‖ option allows us to run some or all of the tests we create. If a project has several classes. ―Preferences‖ allows us to set many preferences in the appearance and working of BlueJ. currently saying ―Package saved‖. The Project menu allows you to create a new. We will be creating projects. There are several categories on this menu. To run and test the Java classes we write. The choices on this menu are things which you may wish to change frequently. we need to compile them. a project will represent your work for a one-week period. Documentation is very important when writing code and Java supports a very nice type of documentation. In this area. to open an existing project (―Open Project‖). we may need to compile only one or we may need to compile many. as well as to close and save projects. Testing is also very important when writing code. You will get to know all of these intimately by the end of the course. I have old eyes so I have modified the font size to 20. You can also print a project. collections of classes. In some cases. on the right is the class diagram. beginning with its ―About BlueJ‖ option. The third option is ―Tools‖. The ―Project‖ menu also allows you to quit BlueJ (―Quit‖). to open a project on which you have worked recently (―Open Recent Project‖). The second option is ―Edit‖. as well as create new arrows on the class diagrams.

The next Help menu option is ―Copyright‖. To dismiss the About box.bluej. Use this to decide if there is a newer version of BlueJ than the one you are using. The BlueJ project started at Monash University. The next Help menu option is ―Installed Extensions‖. Deakin University (www. 385 . in Canterbury and other parts of England. so the information from this choice is for information only.We see that BlueJ is a product of teams at two universities.au/).ac. For more about extensions.deakin.uk/). It then shows a few other pieces of information. in Australia and migrated to Deakin and Kent.edu. in Melbourne and other parts of Australia. and the University of Kent (www.html.kent. Notice that there are only a small number of people involved in the BlueJ project. At Okanagan College. newer versions of both are probably available. At home. you do not have the authority to install software. you can keep it up to date if you wish. The About box shows the version of BlueJ you are using and the version of Java you are using. check http://www. It may be better to keep the same version at home and school. The next Help menu option is ―Check Version‖. including the BlueJ website. click Ok or press .org/extensions/extensions.

sun.1. neatly-formatted. Hand-in:  A note to me stating that you have completed the first three sections of the tutorial.bluej. Note that you can download the documentation to your own computer and have this menu option link to your local copy. Yes. a site which describes everything you would like to know about the Java language. Read and follow the steps in that tutorial. Now that you have quickly seen the menu. We will be visiting this site regularly.0/docs/api/index. Due date: Two weeks 386 . Note that I will not be repeating material from the tutorial in subsequent labs. the tutorial is for BlueJ 2. The next Help menu option is ―BlueJ Tutorial‖. The main task of this lab assignment is to complete the tutorial.org. perfectly-speled.X and we are using 2. and free of grammar mistakes. This is a very complete tutorial on how to use BlueJ. it‘s time to use BlueJ. displaying the site in your default browser. This could be handy should you be using BlueJ while you are not connected to the Internet.0. Rather than create my own tutorial. Complete the first three sections of the tutorial.X but I haven‘t found any differences.The next Help menu option is ―BlueJ Web Site‖. This provides a direct link to www. I will direct you to the ―BlueJ Tutorial‖ option on the Help menu. This is a very important link.5. so you should complete the rest of the tutorial when it is appropriate. The final Help menu option is ―Java Class Libraries‖. Make sure that the note is word-processed. It leads us to http://java.com/j2se/1.

you should investigate the websites for the three professional box lacrosse leagues with Canadian teams. Look at the statistics for the New Westminster Salmonbellies to see the type of statistics kept for goalies. (www. To see what modelling a box lacrosse league involves.Players Objectives: To design. Procedure: Lacrosse players all have first and family names.  The National Lacrosse League (www.  Major Series Lacrosse.Lab Assignment 1 .com) has teams in Canada and the United States which play their season during the winter. has teams in British Columbia which play their season during the summer. The numbers shown for the Salmonbellies goalies are the sum of a number of single-game statistics. So that they can be paid. you may have noticed two types of player statistics. or WLA. Goalies have one type of statistics. or MSL.majorserieslacrosse. and many players switch summer leagues from time to time. Create and test a class called Player. Many players play both summer and winter. field lacrosse is more similar to the original sport played by First Nations in Eastern Canada.) A website which describes how this came to be is http://www. The 2006 Mann Cup playoffs were scheduled for September 8 through 16.com/canada/symbols_facts&lists/symbols.com). Feel free to use any classes from the textbook if they are useful. the number of shots faced. you will use Java classes to model a box lacrosse league. reflecting the two different types of players.com) has teams in Ontario which also play their season during the summer. 387 .craigmarlatt. and box lacrosse is a variant played in hockey arenas during the summer. when there is no ice in place. formerly the Ontario Lacrosse Association.theboxrocks. When you looked at the league websites. In the next series of lab assignments. and test classes using the BlueJ environment. The champions of the WLA and MSL play off for the Mann Cup.nll. create. Background: Lacrosse is the official Canadian summer game (as ice hockey is the official Canadian winter game. including the number of games played. they also provide their Social Insurance Number.  The Western Lacrosse Association (www. and the number of goals allowed.html Lacrosse comes in two varieties.

The alternative is for a Player object to contain a collection of PlayerStatistic objects. Goal. and Penalty classes from PlayerStatistic. and the number of goals allowed.Teams and Leagues 388 . Also provide any other classes you have developed to support these classes. Assist. one assist. including goalies. Assist. Which is the class which contains these collections? Following the model in the textbook. two-minute penalty at 11:23 of second period. As for the goalies. the number of shots faced. We will create one in the next assignment. You may find you have a better design. Goalie. While the second is easier. You will need collections of GoalieStatistic objects and PlayerStatistic objects. This design may possibly cause difficulties later. Penalty.Scoring and penalty statistics are the second kind of player statistics. The second is to record the number of events in each game. the numbers shown on the websites represent the sum of separate statistics. Since a goalie is a player. In August 2006. Hand-in: Provide me with the Player. Due date: TBA Lab Assignment 2 . you might suggest a League object. can receive penalties. Create and test a class called Goalie. the first is more flexible. GoalieStatistic. All players on a lacrosse team. But we don‘t have a league object yet. goal at 12:45 of first period. One of the observations that came up from this was the length of time between the first and the last goals. assist at 1:53 of second period. this is best accomplished by deriving a Goalie class from the Player class. The find is to record each event (goal. Thus. For example. so we will not pursue it further except that we will need a Goalie object. and score and assist on goals. if you derive Goal. and PlayerStatistic classes. Create and test a class called PlayerStatistic. For example. assist. A GoalieStatistic object contains details for a single game. These details should include at least the date of the game. Kerry Susheski scored nine goals in a playoff game. five-minute penalty at 7:25 of third period. There are two different ways to do this. seven minutes of penalties. penalty) separately. we can see that the WLA is using the first way of recording these statistics. and for a Goalie object to contain a collection of GoalieStatistic objects. one goal. Create and test a class called GoalieStatistic. the number of minutes played.

com/teams/brampton. What are appropriate structures for these collections? Each team needs to know its schedule against all the other teams in its league. the profile for the Brampton Excelsiors of the MSL. The type of information necessary for a Team class is shown at http://majorserieslacrosse. there are three professional lacrosse leagues with Canadian teams. Create and test a League class. When a player joins a team he/she is assigned a jersey number. Each team needs to know the players it has on the team. create. A Team may change its name from time to time. For example. Procedure: Create and test a Team class. Recall that the League also contains collections of PlayerStatistic objects and GoalieStatistic objects. Background: As we mentioned in the previous lab assignment.ArrayList<Team>> to store this collection. Jersey number is the key to use when setting up a HashMap<String. The Integer refers to the year and the ArrayList is the list of teams. Occasionally a goalie will prefer 00. 389 . The type of information necessary for a League class is shown on any of the three league websites mentioned in the previous assignment. often like the number 0. In that case. I used a HashMap<Integer. The two numbers 0 and 00 are different. fired) or placed on/removed from an ―injured-players‖ list at any time. You may find it easier to just model one season. Thus a League object needs to know the teams it contains in each year. I created a ScheduleEntry class. being unusual people. we will create Team and League classes. In this assignment. Assume that players may be traded (to another team) or released (essentially. and then stored a team‘s schedule in an ArrayList<ScheduleEntry>. and it may or may not participate in a league in any particular year. They moved back to the Lower Mainland and changed their name to the Langley Thunder. you simply need to use an ArrayList<Team>.Objectives: To design.html. Note that a League contains a collection of Team objects. Goalies. the North Shore Indians were a team in the WLA. They moved to the Okanagan and changed their name to the Okanagan Thunder. Player> of players on a team. despite what mathematicians say. and test classes using the BlueJ environment.

not the teams. Hand-in: Provide me with the Team and League classes and their unit tests. assists. Due date: TBA 390 . active players. You may wish to use exceptions to detect a violation of the rules. we would require some form of persistence to remember data from one run of the program to another. Implement these rules as part of League. not including those on the injured-players list) goalies a team has. and injured players) and leagues. and penalties. If you would like a challenge: Each league has its own rules about the number of active (that is. We can use unit tests to populate teams (including their schedules. You will need static variables. If this were a real application.Consideration: Is it better for the League to know the schedule for all games in the season. Each league has its own rules about the number of active players (including goalies) a team has. or is it better for the League to construct a schedule by asking all the Teams for their own schedule? Patterns say that the League should own the schedule. Ensure your Team and League classes support all the above information. Implement persistence. Include persistence for the goals.

Team. Sometimes an object will have to ask other objects for help in answering the questions. The save percentage is (shots faced – goals allowed) / shots faced. we can use them to produce a few reports. Modify Team to include a method that will determine which of its goalies allows the fewest goals. PlayerStatistic. Assist. Goal. and League classes. Which goalie has the best save percentage? Which goalie allows the fewest goals? Which players win their team scoring championships? Which player wins the league scoring championship? Which team wins the league championship? To answer these questions we need to ask the right questions to the right objects. Background: Now that we have created Player. The league can then combine those answers and produce its own answers. GoalieStatistic. as some teams alternate their goalies. Penalty. and test classes using the BlueJ environment. 391 . Note that two or more goalies may have the same number of goals allowed. Procedure: Which goalie has the best save percentage? In your GoalieStatistic class. The league can then combine those answers and produce its own answers. Make it so. Goalie. That is. modify Team to include a method that will determine which of its goalies has the best save percentage. with each goalie playing half the season. Which players win their team scoring championships? Which player wins the league scoring championship? The league knows the teams it contains and it can ask each of those teams about its own scoring.Lab Assignment 3 .Reporting Objectives: To design. you probably have the number of shots the goalie has faced and the number of goals he/she has allowed. on a team or in a league. Note that two or more goalies may have the same save percentage. Modify League to include a method to use these new Team methods. Which goalie allows the fewest goals? The league knows the teams it contains and it can ask each of those teams about its own goalies. Note that several players may be tied. on a team or in a league. create. In fact. although this would be unusual. Note that several goalies may be tied. this could be quite common.

asp for the summer 2006 results in the WLA. Which team wins the league championship? This is harder since the rules in the leagues are slightly different. one for an assist) each player earns.nll. Modify and test the Team class so that the results of games are known. If two teams are tied. use a random number to simulate a coin toss.) But we don‘t know the placing of the teams since we have not recorded the winners and losers of the games played.and fourth-place teams play a best-of-seven series. and zero for a loss. and modify League to determine the player(s) with the highest points total.and third-place teams play a single-elimination game. and zero for a loss. modify Player to include a method to calculate the number of points (two for a goal.and third-place teams play a best-of-seven series. there are two divisions. Hand-in: Provide me with the revised Team and League classes.Make it so. In each. If the teams are still tied.com/l_play_offs. the second. the first. Due date: TBA 392 . second-. with the winners playing a single-elimination game for the division championship. Then use WLA/MSL rules to determine which teams are in first-. and the winners of those two series play a best-of-seven series for the championship. That is. and fourth-places.) In the NLL. consider only the games they have played against each other.theboxrocks. (See http://www. In the WLA and MSL (both of which have only a few teams) the first.com/playoffs. each approximately the size of the WLA or MSL. third-. one for a tie. one for a tie. again with two points for a win.and fourth-place teams play a single-elimination game and the second.shtml for the winter 2006 results. Add playoff data to the League class so that the League can identify the champion teams and produce a report showing the results of all playoff games. (See http://www. The division champions then play a single-elimination game for the league championship. modify Team to determine the players(s) with the highest points total. assuming two points for a win.

)  Team name. create. Hand-in: Provide me with all the code necessary to create and test your data entry screen(s).  Player placed on or removed from injured list (This will include type of injury and expected return date.)  Scoring statistics (These have been described in an earlier assignment. and test classes using the BlueJ environment. but that is not suitable for real world use. or create another screen which is appropriate. date of birth . address. contact info. etc. Background: How do we enter much of that data we have been manipulating? We can create test cases using setters.) Imagine a Trade class which contains two collections of Players objects. along with player and goalie statistics. and the other for the Player(s) the team receives. and Social Insurance Number)  Player trade information (A player may be traded for several players.Lab Assignment 4 .)  Results of games (This will include who won and who lost. one for the Player(s) the teams gives up. Due date: TBA 393 . A player may be part of a trade for several other players.Data Entry Screens Objectives: To design.)  Goalie statistics (These have been described in an earlier assignment. Procedure: Create a data entry screen to allow for entry of some of the data we have identified. Instead. Create one or more of the screens identified above. we should create a data entry screen. That data includes:  Player demographics (This will include name. There should also be a comments field. Assume there are no ―future considerations‖ trades.

Hebrew. and test classes using the BlueJ environment.altavista. you will explore several applets. For a larger challenge. Korean. embedding programs into web pages. 394 . have the applet display in only one language. which require Unicode characters. Now we will examine an area where Java shines. we have been developing an application which could have been developed in many languages. Australia ( ). We‘ll create some applets. For the second applet. Create a web page to use the applet. create a flag applet that displays either the French ( ) or the Italian ( ) flags.And now for something completely different Objectives: To design. While following that example. create. The difference doesn‘t show up in black and white. Macedonia ( ) and Nepal Then create the flag of the United Kingdom ( ). or you could look at http://world. Japanese. In this assignment. choose one or more of the languages from those such as Chinese. while the bar on the left of the Italian flag is green. Have the applet display the message in several different languages. create and run the HelloWorld applet as it is given in the textbook. For the first applet. and New Zealand ( ) and use it to create the flags of Niue ( ). but the bar on the left of the French flag is blue. but have that language change (among a few different languages) as you run the applet again and again. Background: We have finished with the lacrosse league example. ).Lab Assignment 5 .com/tr For an extra challenge. The centre bar on both is white and the bar on the right is red. or Arabic. More challenging are the flags of the Seychelles ( ( ). Procedure: Chapter 7 of the textbook discusses applets and how to create them. You could ask around for different translations.

Illustrations of these and other flags are at many places on the Internet. Pay particular attention to the stars on the last two flags.gov/cia/publications/factbook/docs/flagsoftheworld.net (loading quickly since there is a page for each letter of the alphabet) and https://www. including www. Due date: TBA 395 .This illustrates the important topic of reuse.html (loading more slowly since all flags appear on one page).flags. Hand-in: Your HelloWorld and Flag applets and the web pages to run them.cia.

and test classes using the BlueJ environment. Implement and test an inverse operation for RationalNumbers. you will complete the RationalNumber and ComplexNumber classes. Due date: TBA 396 . Can you do this in a way that is totally transparent to the users of your class? Implement and test a ComplexNumber class. Hand-in: The RationalNumber and ComplexNumber classes.Lab Assignment 6 . multiplication. Procedure: The textbook implementation of RationalNumber omits the implementation of subtraction. Ensure the method is documented. In particular. Ensure the methods are documented. and division. create. Ensure all your work is documented. Background: The textbook speaks about the use of computers in numerical computation. In this assignment you will complete the missing parts of chapter 9. Implement each of these operations and test them thoroughly. Modify your RationalNumber class so that it uses BigIntegers. This will input a/b and return b/a. expressed as a double.Mathematics I Objectives: To design. plus software to test them. Ensure the method is documented. Implement and test a method to convert a RationalNumber to its decimal equivalent.

Hand-in: 397 . How well does this approximation work? That is. e = 1/0! + 1/1! + 1/2! + 1/3! + 1/4! + … How well does this approximation work? That is.Lab Assignment 7 . http://mathworld. Develop a Catalan class which calculates these numbers using the formulas numbered (2) and (3).1/3 + 1/5 . perhaps with some people getting 0 presents? Hint: use the choose function. Prove that statement is true.1/7 + 1/9 .wolfram. how many ways are there to divide the presents amongst the people. so you may wish to rethink the data types in the factorial methods. Then develop mathematical methods for the Catalan numbers.com/CatalanNumber. One approximation to e is given by the following formula. One approximation to π is given by the following formula. π/4 = 1 . π has an infinite decimal expansion. how many terms in the series do you need to have three digits after the decimal point correct? Five digits? 10 digits? The constant e also has an infinite decimal expansion.Mathematics II Objectives: To design. and test classes using the BlueJ environment. how many terms in the series do you need to have three digits after the decimal point correct? Do you need five digits? Do you need 10 digits? The last sentence of chapter 10 implies there is no largest integer.. Note that (2n)! increases very rapidly. Procedure: What is the ratio of Fib(n+1)/Fib(n) as n increases? If you have m presents and n people.. Background: Use the mathematical functions in the textbook and those you created in the previous assignment to answer the following questions. create.html introduces Catalan numbers and gives several formulas used to calculate these numbers.

Due date: TBA 398 .

399 . We had two available for them. I have not included them here. The second environment uses Eclipse.Subsequent lab assignments Students will not be working within the BlueJ environment all the time. The first is straight-forward UNIX environment where they use emacs as the editor. and compile either from within it or from the command line. Thus it is important they see other environments. Since these labs are quite institution-dependent.

400 .

345. 267. 124. 394 autoboxing. 397 Assist. 83. 389. 265. 221. 156 addBinding. 215. 343. 199. 320. 236 assertNotNull. 150. 21. 331 assertEquals. 211 Bangladesh. 315. 123. 7. 149. 319. 74. 247. 311. x. 294. 73. 338 BlueJ. 255. 7. 108. iii. 386. 202. 255. 25. 267. 89. 219. 389 Aruba. 84. 392 addActionListener. 287. 354. 261. 198. 98. 257. 314. 362. 190. 323 architecture. 347 abstract. 254. 141 BigDecimal. 152. 211 BadMinuteException. 259. 258. ii. 372 Apple. 260. 119. 52. 234. 344. 71. 10. 283. 72. 373. 266. 294. 185. 28. 351. 401 . 353 AWT. 48. 388. 150. 345 BigInteger. 39. 92. 367 ActionCommand. 248. 227. 98. 331. vii. 250. 235. 38. 236. 262. viii. 243. vi. 323. 120. 29. 380. 334 ArrayIndexOutOfBoundsException. 79. 312. 353. 92. 91. 300. 365. 221. 126. 210. 328. 139 accessibility. 256. 318. 139. x. 257. 372 ActionListener. 391 association. 366. 150 assignment. 46. ix. 295. 331 aggregation. 265. 322 Abstract Window Toolkit. 320. 74. 92. 168. 46. 187. 117. 323. 313. 211 assertNull. 80. 304. 245. 14. 151. 260. 136. 253. 271 autounboxing. 345. 219. 254. 4. 317. 155. 220. 248. 314 BadHourException. 10. 184 Albania. 385. 319. 47. 105. 361. 95. 317 AbstractButton. 292. 84. 2. 274. 237. 331 bank account. 355. 55. 227 Avogadro. 88. 217. 341 Add. 49. 52 assertTrue. 91. 104. 114. 88. 51. 347. 299.Index abs. 219. 251. 315. 105. 338. 363. 324.뫰327. 227. 3. 50. 283. 187. 367 Binding. 105 Adapter. 55. 371. 339. 282. 43. 310. 265. 166. 292. 312. 304. 85. 18. 324 AppletViewer. 156. 331 African Union. 294. 88. 268. 371. 75. 258. 261. 381. 394. 388. 40. 126. 371. 317. 374. 331 algorithm. 372 ad hoc. 287. 303 Ackermann. 212. 365. 348. 321. 266. 110. 77. 269. 343. 291. 52. 254. 344. 226. 292 abstraction. 197. 75. 379. 67. 289 BindingFactory. 210. 37. 322. 95. 93. 364. 158 anonymous class. 13. 71. 275. 210. 42. 65. 141. 275 Afghanistan. 67. 232. 282. 217. ii. 163. 266 addBindings. 360 ALPHABETIC_ORDER. 293. 382. 52 assertSame. 382. 26. 77. 366. 101. 129 Applet. 269 Australia. 160. 258. 86. 261. 104. 203. 259. 204. 297. 155. 321 ArrayList. 169. ii. 140. 253. 220. vii. 221. 101. 301. 184. 153. 288 Address. 87. 150. 74. 251. 109. 41. 125. 29. 333. 218. 62. 52. 230. 161. 267. 171. 396. xi. 304. 143. 225. 185. 54. iv. 90. 321. 371. 292 ActionEvent. 252. 182. 152. 140. 372 addAll. 393. 377 base class. 233. 282.

196. 347. 103. 279. 175 constant. 93. 178 call stack. 65. 121. 388. 341 bundle. 56. 91. 374. 92. 274. 169. 282. 129. 191. 339 coupling. 120. 389. 140. 182. 308. 289. 132. 26. 293 Cloneable. 208. 346. 100. 315. 258. 210. 232. 226. 299. 155. iv. 384. 55. 391. 263. 156. 109. 211. 170. 72. 171. 78. 318. 331 ButtonGroup. 341 British Columbia. 100. 163. 330. 187. 201. 70. 349. 127. 243. 280. 158. 356. 47. iii. 98. 276. 218. 314. 228. 160. 147. 280. 208. 166. 339. 108. 166. 268. 99. 199. 220. 100. 321. 161. 1. 163. 91. 335 Comparator. 399 Comparable. 128. 363. 272. 17. 123. 154. 66. 185. 393. 281. 129. 88. 312. 270. 13. 149. 158. 223. 88 Cohesion. 268. 205. 181. 290. 127. 265. 306. 341 Character. 123. 199 charAt. 42. 80. 151. 268. 394. 167. 116. 3. 381. 62. 152. 306. 262. 282 BorderFactory. 341 command line. 126. 61. 123. 122. 98. 258. 143. 301. 63. 109. 306. 169. 167. i. 27. 396. 281 BoxLayout. 387 BufferedOutputStream. 96. 345. 157. 184 concrete. 281 Braces. 136. 66. 199. 185 compare. 13. 254. 42. 152. 237. 86. 72. 113. 159. 129 boolean. 38. 323. 75. 219. 234. 156. 168. 30. 184. 152. 26. 252. 364 Builder. 115. 72. 5. 2. 202. 52. 295 content pane. 134. 257. 195. 310 Compile. 60. 102. 157. 166. 28. 124. 130. 282. 118. 90. x. 233. 134. 307. 206. 283. 379 Code Pad. 65. 150. 236. 353. 51. 384 ClassNotFoundException. 233 clearSelection. 185. 276. 261. 114. 105. 106. 175. 184. 287. 297 Checkstyle. vi. 67. 164. 38. 88. 217. 337 Class. 169. 54. 206 Canada. vi. 2. 239. 168. 265. 125. 72. 37. 141 condition. 397 constraint. 84. 147. 91. 145. 176. 84. 153. 242. 222. 117. 65. 143. 338 BorderLayout. 205. 234. 353. 218. 65. 238. 59. 345 Command. 34. 77. 40. 233. 68. 386. 41. 65 Bridge. 259. 130. 77. 123. 137. 281. 104. 151. 279 Box. 227. 70. 132. 191. 223. 282 constructor. 178 402 . 341 collection. 171. 148. 288. 182. 286. x. 70. 59. 36. 148. 29. 167. 306 Burkina Faso. 180. 71. 325. 198. 163. 180. 184. 210. 23. 300. 292. 159. 341 composition. 379. 49. 220. 18. 263. 154. 121. iv. 88. 66. 365 Border. 135. 249. 351 Composite. 86. 105. 202. 386 class diagram. viii. 287. 280. 11. 284. 98. 71. 293 Calendar. 178. 287 checkbox. 268. ix. 158. 129. 19. 348. 204. 312. 24. 62. 126. 107. 277. 19. 195. 62.383. 147. 146. 387 Chain of Responsibility. v. 214. 226. 383. 207. 183. 336. 169. 45 Code. 212 Close. 42. 54. iv. 323 Complex number. 260. 322. 166. 235. 39. 40. 308. iii. 145. 316. 261 controller. 385. 2. 64. 336 CloneNotSupportedException. 77. 150. 209. 149. 383. 189. 130. 383. 84. 248. 153. 149. 159. 73. 319. 48. 237. 250. 397. 173. 363 container. 182. 176. 67. 389 Color. 139. 148. 74. 29. 142. 399 Boole. 78. 68. 250. 156. 40. 387. 173. 67. 43. 224. 127. 27. 41. 259. 168. 292. 150. 133. 98. 323. 98. 55. 373.

205. 143. 356. 190. 349. 263. 131. 318. 87. 318.course. 277. 280 currentThread. 339. 211. 344. 146. 325. 79. 187 Formula. 362. 133. 224. 286. 255. 110 deriveFont. 185. 388 EventQueue. 3. 397 DecimalFormat. 275. 232. 194. 282. 330. 139. 364. 345. 42. 205. 362. 368 Factory. 226. 213. 203. 65. 55. 102. 314. 355. 207. 219. 315. 70. 227. 174. 323. 341. 369. 166. 261. 330. 46. 10. 302. 250. 236. 217. 14. 306. 14. 301. 223. 158. 47. 300. 280. 317. 265. 150. 88. 204. 304. 316. 368 File. 125. 29. 19. 220. 33. 396 drawPolygon. 366. 236. 360 Frame. 331. 122. 228. 322 deserialize. 273. 263. 381. 172. 97. 354 event. 117. 84. 225 destroy. 345 decimal. 145. 144. 205. 382 FlowLayout. 125. 140. 208. 91. 193. 266. 60 Fibonacci. 116. 282. 267. 256. 147. 187. 193. 239. 322. 79. 219. 55. 210. 2. 371. 228. 217. 187. 54. 254. 235. 219. 336. 13. 370 Exception. 372. 86. 140. 56. 140. 250. 372. 201. 236. 271. 283 double. 280. 296. 74. 382 DataFormatException. 166. 217. 30. 362. 145. 347. 202. 113. 44. 339. 140. 233. 4. 21. 126. 67. 146. 388. 217. 353. 278. 42. 371. 365 Explore. 271. 214. 114. 226. 338. 28. 233. 266. 259. 294. 194. 189. 230. 117 Direction. 140. 357. 31. 139. 351. 224. 389. 217. 234. 20. 62. 295. 61. 211 datatype. 297. 356. 228. 367. 193. 233. 38. 84. 291. iv. 191. 55. 282. 319. 1. 362. 9. 365. 291. 196. 290. 341. 308. 215. 114. 152. 48. 210. 43. 314. 384. 17. 338. 136. 341. 164. 215. 358. 365 FileOutputStream. 239. 218. 4. 139. 377. 47 createVerticalBox. 369. 220. 101. 319. 142. 305. 7. 115. 240. x. 103. 224. 396. 239. 362. 247. 322 For. 41 Create Test Class. 349. 269 dictionary. 235. 70. 36. 26. 62. 315. 152. 173. 254. 180. 87. 10. 147. 358. 244. 40. 336. 283 Efficient. 36. 363 Firefox. 160. 260. 236. 1 Euclid. 177. 382. 116. 128. 190. 114. 26. 173. 36. 214. 178. 95. 107. 77. 264. 363. 48. 209. 142. 343. 235. 385. 11. 128. 137. 101. 244. 294 403 . 249. 222. 233. 353. 115. 256. 265. 172. 78. 292. ii. 289. 293 Flyweight. 33. 364 fillRect. 158. 328 Finally. 59. 51. 394 for-each. 118. 162. 176. 271. 193 Decorator. 245. 111. 264. 280. 329. 338. 99. 27. 27. 330. 175. 370. 141. 367. 279. 125. 31. 328 drawString. 335. 231. 207. 282. 116. 190. 345. 310. 105. 162. 363. 367 Edge. 245. 366 Date. 258. 220. 347. 144. 365 FileNotFoundException. 292. 103. 267. 300. 205. 84. 384 CPU. 32. 281. 232. 207. 230 derived class. 11. ix. 344. x. 275. 250. 245. 161. 170. 113. 153. 274. 134. x. 165. 99 Deakin. 341 Department. 208. 306 FileInputStream. 111. 345 dynamic programming. 168. 109. 2. 163. 385 debt. 192. 283. x. 315. 319 dialog. 266. 341 Font. 141. 154. 52. 226. 44. 239 database. 345. 33. 23. 98. 141. 52. 370. 116. 20. 183. 117. 80. 343. 344. 234. 184. 75. 220. 76. 252. 77. 345 False. 109. 339. 322.

317. 121. iii. 293. 140. 205. 168 greatest common divisor. 201. 366. 388. 164 Import. 197. 363. ii. 237 hasNext. 15. 120. 273. 300. 66. 317. 223. 306 garbage collection. 16. 328. 339. 251. iii. 321 Interpreter. viii. i. 132. 302. 286 getModel. 344. 148. 131. 228 Integer. 290. 30.Frame. 11. 1. 44. 80. 355 GregorianCalendar. 317. 341 intValue. 13. 38. 117. 249. 364. 100. 111. 324. 55. 291. 223. 158. 341 JApplet. 168. v. 369 GB. 117. 166. 141. 2. 117. 192. 235. 359. 365. 11. 292. 128. 155. 273. 301. 129 Information Expert. 333. 116. i. 134. 321. vii. 319 getClassLoader. 63. 50. x. 217. 19. 227. 354. 292 getParameter. 247. 83. v. 72. 272. 39. 315. 126. 118. 336. 117. 252. 353. 321. 272. 33. 231. 62. 43. 6. 42. 20. 151. 289. 322 Graphics. 376 InputVerifier. 226. 266. 3. 314. 401 Indirection. 207. 42. 141. 292. 193. 316. 32. 393 GoalieStatistic. 224. 371 Goal. 225. 145. 388. 248. 101 Instance. 40. 44. 23. 10 hashCode. 131 help. 268. 341 infinite loop. 129. 250 Guava. 318. 292 getAppletInfo. 380 Internet Explorer. 404 . 26. 291. 320. 391. 111. 120. 117 GUI. 370. 229. 86. 164 instanceof. 271. 74. 355. 234. 55. 320 Java. ii. 122. 275. 72. 9. 103. 216. 316. ix. 16. 271. 123. 369. 358. 102. 18. 368 Iterator. 373 Hardware. 101. 327 getParameterInfo. 65. 251. 319. 371. 10 GCD. 145. 205. 291. 129. 233. 325 i18n. 27. 297 GridLayout. 311. 166. 235. 29. 299. 126. 97. 130. 371. 135. ix. 103. 119. 253 increment. 360. 308 Identity. 388. 69. 130. 213. 373. 152. 174. 124 HashMap. 207. 247. 208. 132. 103. 227. xi. 35. 59. 271. 314 getSource. 25. 236. 123. 357. 322 getInstance. 193. 119. 89. 277. 120 getAccessibleContext. 125. 118. 87. 304. 354. 149 HTML. 108. 169. 302. 290. 239 getFont. 270. 316. 356. 220. 237. 314. 219. 167. 200. 196. ix. 137. 391 hexadecimal. 124. 248. 305. 76. 41. 372. 370 IOException. 323. 328 getRootPane. 226. 274 GridBagLayout. 290. 4. 84. 391 Goalie. 318. 296 Inspect. 292. 121. 327. 223. 7. 250. 199 isSelected. 329. i. 203. 131. 275. 264 France. 251.MAXIMIZED_BOTH. 335. 73 inner class. 13. 389 Interface. 391 Google. 272. 362. 226. 12. 315. 123. 341 Inheritance. 363 invokeLater. 99. 169. 305. 365 isLetter. 102. 276. 175 Index. 77. 128. 319. 389 HashSet. 98. 133. 63. 389. 26. ix. 65. 172. 156. 218. 245. 9. 222. 366. 197. 250. ix. 37. vii. 128. 303 getActionCommand. 317. 128. iii. 17. 364. 173. 72. 1. 2. 328 greater than. 257. 129. 28. 382 Interpret. 123. 157. 227. 98. 344 Generic. 179. 292 iterative. iii. 92. 187. 347.

290. 274.util. 248. 163. 329. 210. 80. 230. 252. 248. 341. 261. 59. 101. 370 JLabel. 192. 283 JList. 358 MB. 345. 250. 251. 387. 267. 13. 103. 287. 345.bean. 318. x. 218. 304. 155. 270. 301 JMenuItem. 171. 290 JFormattedTextField. 267. x.pow. 259. 129 Map. 263. 256. 221. 197 layout manager. 207. 303 JTextField. 277. 267. 260. 46. 19 astIndexOf. 141. 254. 300. 391. 222 java. 388. 372. 149. 241. 145. 369. 161. 371 JPanel. 10 Mediator. 390. x. 272. 358. 219. 289. 266. 3. 175. 249.security. 67. 152. 300 java. 261. 237. 336 Marker. 282. 386. 271.event. 239. 344. 282. 341 Meeting. 302. 305. vii. 288 JComponent. 289.swing. 243. 244. 294. 281. 334. 253. 349. 294. 300. 274. 143. 362 mathematics. 54. 286. 262. 265. 297 JFrame. 224. 281. 384. 272. 2. 147. 338. 295. 335. 296 JUnit. 249. 248. 258. 275. 233. 232. 243. 341. 117 mutable. 362 Libya. 275. 189. vii. 282. 347 Math. 142. 258.Math. 371 JOptionPane. 364. 242. 394 java. 239. 119. 281 JMenu. 379. 307 Long. 280. 299. 29. 237. 264. 322. 71. 293 JRadioButton. 314. 248. 264. 166. 304. 165. 4. 242. 279. 336 Math. 164. 275. 300. 252. 70. 350. 209. 383.Entry. 308. 277. 158. 331 List. 385 key-value. 63. 295. 263. 255. 136. 181. 248. 274. 287. 344. 297. 167.lang. 392 less than. 343. 340 Modelling. 257. 72. 182. 268. 277. 389. 387. ix. 291 JSeparator. 341 Method. 300. 355 Monash. 237 JavaHelp. 248. 148. 256. 243 Klingon. 238. 249. 247. 150. 170. 349 java. 305 javax. 339. 128. 260. 26. 250. 277. 52.text. 243 Mark. 205. 202. 382. v. 302. 330. 168. 221. 98. 280. 330 Loop. 301 JMenuBar. 344. 255. 248. 268. 227. 385 multimap. 284. 177 java. 329. 375. 117. 260. 187. 265. 166. 259. 50. 164. v. 143. 248. 185. 335. 381 modulus. 253. vi. 1. 364 ListSelectionModel. 299. 248. 377. 337. 347. 251. 193. 243. iv. 257. 331 Model. 295. 202. 268. 248. 245. 230 java. 187. 136.awt. 273. 380. 191. 299 League. 143. 272. 248.232. 345. 167. 362 Math. 280. v. 280. 248. 249. 230. 225. 279. viii. 184. 224. 340 405 . viii. 70. 344 Micronesia. 176. 353. 267. 211. 277. 194. 56. 279. 70. 115. 233.abs. 141. 245. 299. 290. 288. 293. 148. 104. 250. 217. 190. 331. 296 Memento. 281. 270. 330 JButton. 240. 222. 179. 385. 324. 208. 180. 169. 326. 194. 66. 17. 364 java. 360. 23. 307. 366 Map. 209. 373. 311. 307. 283. 380 Kent. vi. 374. 51. 270. 254. 344. 339. 317. 253. 300. 131. 254.io. 366 JavaBean. 293 JCheckBox. 248. 337. 121. 286. 280. 257. 295. 278. 270. 102. 126. 203. 309. 118. 259. 280 Locale. 172 MVC. 265. 117.

99. 100. 88. 341 Olympic Movement. 225. 37. 141 numerator. 121. 48. 121. 347. 109. 200. 108. 41. 243. 210. 356. 223. 170. 136. 268. 37. 220. 118. 222. 158. 107. 339. 232. 33. 64. 159 Object. 287. 89. 292. 167. 28. 154. 156. 337. 75. 51. 186. 197. 109. 267. 209. 240. 34. 77. 124. 12. 222. 126. 228. 90. 226. vi. 85. 316. 144. 91. 134. 223. 239. 95. 262. 34. 166. 220. 50. 334. 67. 172. 212. 243. 379 Object Bench. 133. 32. 315. xi. 186. 192. 174. 148. 71. 157. 254. 341 postcondition. 77. 184. 179. 301. vi. 115. 143. 28. 244. 125. 148. 129. 134. 120. 62. 243 Observer. 127. 394 normalization. 284. 2. 24. 141. 279. 291 parenthesis. 337. 154. 33. 122. 198. 104. 343. 215. 306. 42. 300. 327. 76. 198. 131. 44. 366 professor. 238 Prototype. 122. 264. 219. 146. 302. 145. 152. 199. 132. 314. 256. 363. 257. 219. 232. 105. 30. 17. 235. 338. 130. 257. 235. 133. 233. 161. 225. 106. 346. iv. 227. 149 precondition. 238. 7. 150. 7. 109 pattern. 406 . 203. 354. 214. 219. 376 native2ascii. 59. 226. 305. 68. 102. 362. 382. 347. 22. 211. 107. 123. 30. 140. 384 package. 236. 152. 84. 377 penalty. 220. iii. 89. 243. 102. 119. 249. 4. 217. 346. 235. 344. 167. 167. ix. 9. 364. 26. 341. 362 print. 124. 227. 268. 328. 270. 132. 1. 102. 196. 223. 334. 329. 32. 122. 209. x. 327. 290. 15 parameter. 126. 106. 232. 63. 71. 133. 26. 218. 191. 164. 357. 221. 30. 206. 150. 237. 126. 217. 271. 159. 345. 27. 222. 263. 97. 202. 141. 123. 147. 384 println. 234. 237. 142. 19. 354. 101. 242. 390 person. 108. 40. 141. 324. 143. 102. 348. 168. 31. 391. 97. 118. 125. 217. 389. 347. 95. 252. 151. 208. 215. 217. 234. 131. 83. 71. 72. 3. 155. 224. 42. 333. 227. 91. 51. 341 public. 210. 221. 224. 346. 159. 86. 149 primitive. 353 player. 105. 183. 14. 50. 213. 304. 275. 344 Paint. 318. 320. 300. 196. 308. 126. 104. 193. 226. 105. 145. 119. 218. vi. 303. 349 NUMERIC_ORDER. 165. 340. 363 ObjectInputStream. 2. 237. 230. 308. 101. 231. 243 ObjectOutputStream. 122. 307. 252. 224. 113. 146. 331. 123. 108. 222. 392. 366 Polymorphism. 356. 31. 88. 190. 106. 45. 336. 370. iii. 127. 85. 78. 156. 236. 224. 22. 50. 348. 111. 196. 341 Proxy. 48. 116 NumberFormat. 43. 314. 155. 217. 289. 32. 225. 361 parentheses. 16. 230. 206. 333. 107. 216. 121. 153. 62. 101. 107. 10. 393 PMD. 122. 116. 149. 105. 75. 270. 18 Point. 301. 185. 222. 55. 300. 127. 294. 156. 219. x. 210. 239. 102. 335. 251. 311. 33. 374 private. 217. 153. iii. 91. 226. iv. 40. 71. 106. 98. 212. 43. 86. 349. 20. 123. 130. 248. 31. 345. 272. 24. 387. 199 paradigm. 111. 316. 89. 92. 215. 154. 321. 108. 258. 40. 315 palindrome. 169. 226.MyDate. 388 persistence. 77. 13. 307 New Zealand. 128. 49. 254. 220. 263. 90. 103. 388. x. 133. 336 protected. 330. 274. 66. 166. 126. 331 Open. 51. 107. 11. 174. 132. 294. 296 Planck. 101.

51. 198. 257. 252. 235. 361 Refactoring. 270.359. 357. 296 setVisible. 87. 308 Retirement. 282. 301. 238. 200. iv. 181 setColor. 187. 261. 293 setMinimumSize. 196. 157. 282. 185. 256. 265. 19. 203. 183. 223. 322. 84 Risks. 267. 245 Singleton. 256. 180. 228. 372. 199. 339 Smoke testing. 287. 153 ROM. 336. 291. 254. 242. 75. 146. 223. 360. 167. 283 State. 370 showMessageDialog. 407 . 221. 333. 179. 24. x. 223. 227. 168. 89. 368 Recursive. 102. 156. 260. 72. 239 setPreferredSize. 267. 290. 168 RAM. 294. 184. 117. 152. 345. 197. 220. 235. 225. 124. 269. 271. 85. 169. vi. 282. 370 setSelected. 254. 304. 164. 180. 272. 345 setContextClassLoader. 324. 40. 282. 181. 201. 226. 178. 271. 202. 55. 371. 228. 274. 335. 363. 155. 131. 302 setMnemonic. 236. 293. 195. 315. 136. 20. 178. 153. 76. 206. 318. 290. 121. 157. 307. 226. 266. iv. 280. 231. 211. 101. 256. 239 setDisplayedMnemonic. 281. 295. 291 setLabelFor. 281. 221. 33. 86. 132. vi. 243. 302. 15. 347. 106. 274. 191. i. 158. 268. 92. 238. 78. 336 Set. 233. 294. 53 Software. v. 158. 242. x. 210. 264 setFont. 139. 225. 239 Stop. 262. 335. 38. 341 Statement. 187. 183. 371. viii. 170. 133. 239. 279. 371 Sighting. 360. x. 373. 142. 164. 296. 28. 380 Replace. 194. v. 78. 66. 174. 222. 189. 250. 144. 277. 319. 258. ii. iii. 224. iv. 295 Serializable. 232. 32. 111. 130. 334. 272. 259. 26. 369. 218. 104. 172. 380 setAccessibleDescription. 115. 227. xi. 151. 279. 341 String. 197 RelativeConstraints. xi. 379 Spring. 90. 322 setInputVerifier. 158. 264 setExtendedState. 166. 374 question mark. 44. 374 Section. 182. 28. 125. 232. 88. 119. 3. 269 resource bundle. 163. 287. 377 Smalltalk. 143. 365 Recursion. 10. 7. 294. 50. 240. 264 setLayout. 84. 243. 71. 226. 142. 330. 209. 109. 369. 339 ResourceBundle. 348. 303 setBorder. 376 Security. 370. 155. 293 setCharAt. 339. vi. 166. xi. 217. 284. 178. 129. 343. 230. 269. 196. 239. 144. 346. 237. 292 setVerifyInputWhenFocusTarget. 107 Return. 29. 245 Scanner. 131. 370. 187. 262. 156. 159. 254. 373 Reference. 216 rational number. 37. 31. 190. 187. 293. 193 Start. 370 Scalable Vector Graphics. 335. 242. 292 setText. 34. 27. 156. 257. 83 Strategy. 118. 62. 338. 74. 163. 157. 64. 284. 251. vii. 10. vi. 235. 303. 255. 98 readObject. 63. 208. 125. 133. 146. 152. 379 regular expression. 341. 227. 271. 288 RelativeLayout. 236. 279. 158. 160. 169. 237. 10 RSA. 273. 141. 266. 148. 302. 272. 265. 239. 145. 372. 224. 30. 301 setPersistenceDelegate. 270. 349 Reading. 343 Runnable. 77. 289. 83. 361. 218. 283. 219. 170. 253.

100. 91. 156. 81. 56. 64. 380 understanding. 371. 379. 52. 220. 168. 13. 196. 228. 277. 19. 107. 84. 3. 37. 15. 320. 220. 374 System. 226. 121. 77. 95. 31. 389 StringBuffer. 221. 189. 235. 96. 42. 331. 269. 182. 92. 380. 21. 50. 31. 185. 88. 62. 102. 93. 55. 349. 155. 179. 70. 243. 232. 221. 224. 133. 153. 232. 54 Team. 237. 33. 204 transient. xi. 307 value. 345. 25. 100. 242. 336. 7. 223. 237. 317. 103. 183. 219. 219 Thread. 87. 275. 49. 53. 224. 61. 165. 90. 109. 24. 99.뫰194. 225. 369 TIME_ORDER. 180. i. 227. 49. 104. 37. 200 typeface. 197. 224. 245 subscribe. 209. 65. 306 System. 146. 226. 223. 139. 18. 373 transaction. 236. 220. 219. 245. 294. v. 88. 88. 60. 184. 93. 275. 43. 74. 201 superscript. 243. 72. 392. 240 System. 145. 66. 54. 247. 46. 164. 150. 169. 114. 17. 236. 147. 116. 163. 57. 128. 127. 158. 179. 141. 134. 22. 152. 151. 211. 176. 304. 239. 160. 20. 390 United Arab Emirates. ii. 226. 91. 129. 127. 167. 93. 369. 26. 104. 49. 225. 79. 171. 175. 40. 142. 63. 221. 123. 333. 48. 373. 25. 280. 353 Unicode. 224. 55 SVG. 100. 43. 394 unit test. 196. 331. 274. 243. 92. 320. 185. 33. 303.exit. 217 Uses. 102. 304. 23. 134. 140. 119. 126. 155. 47. 122. 235. 107. 1. 83. 210. vi. 222. 169. 227. 347. 196. 148 URL. 51. 200. 83. 125. 175. 231. 117. 172. 335. 111. 152. 122. 177. 219. 145. 153. 226. 172. 365. 372 System. 195. 236. 26. 329 True. 117. 275. 48. 263. 391. 169. 236. 56. 260. 148. 50. 322. 173. 319. 55. 331 UML. 30. 53. 354 UTF-8. 233. 369. 51. 20. 300. 187 StringBuilder. 55. 36. 156. 337 substring. 78. 292. 226. 155. 41. 136. 150. 39. 237 trigonometry. 256. 202. 116. 233. 79. 189. 199. 408 . 78. 185. ii. 158. 209. 373 Style. 92. 78. 187. 23. ii. 94. 105. 274. 238. 389. 29. 187. 374 Tacoma Narrows Bridge. 394 United States. 297 transcript. 88. 239. 79. 28. 294. 261 Ukraine. 34. 26. 48. 232.307. 220. 155. 349. 219. 182. 203. 347. vi. 185. 219. 236. 203. 272. 337. 328. 35. 346. 76. 201. 370. 135. 64. 291. 190. 371. 172. 232. 379 Switzerland. 354. 155. 347. 235. 370. 155. 37. 50. 200. 327. 88. 184. 190. 87. 89. 153. 236. 76. 129. 101. 42. 17. 75. 37. 27. 159. 75. 225. 259. 172 Try. 117. v. 181. 331 United Kingdom. 253. 191. 187 Student. 224. 126. 103. 53. 248.out. 139. 59. 55. 28. 247. 224 TreeSet. 263. 329. 154. 56. 131. 373. 145. 59. v. 191. 31. 103. 307. 191. 256. 198. 109. 29. 46. 101. 71. 372. 271. 147. 387 Uppercase. 370. 235. 47. 67. 199. 223. 237. 282. 32. 167. 18. 90. 240. 236. 345.err. 75. 105. 126. 43. iii. 233. 347. i. 126. 115. 106. 77. 36. 182. 31. 233. 44. 157. 321. 43. 235. 32. 67. 393 template. 233. 316. 224. 334 Terminal. 240. 374. 381. 46. 101. 157. 191. 63. 225. 223. 36. 196. 54. 27. 62. 284. 161. 134. 218. 102. 56. 268. 173. 319. 299. 208. 90. 104. 183. 63. 192. 308. 166. 54. 73. 237. iv. 22. 89. 235. 159. 105. 245 Swing. 390. 108. 182. 140. 66. 22. 33. 52. 153. 100. 126. v. 124. 23. 134. 95. 86. 240. 237 toString. 92. 19. 32. vi. 55. 108. 327. 72. 88. 49. 150.

242. 240. 7. 345. 221. 355. 354. 364 XMLDecoder. 272. 218.344. 228. 238. 153. 362. 242. 105. 279. 243. 240. 237. 273. 54. 239. 232. 338. 235. 334. 224. 364. 249. 339. 126. 365 XMLEncoder. 243. 233. 369. 248 Wikipedia. 225. 341 While. 234. 337. 198. 41. 384 virtual machine. 271. 233. 323. 46. 218. 72. 187. 289. 220. 193. 244. 115. 234. 155. 283 verify. 250. 243. 223. 236. 371. 104. 358. 233. 325. vi. 237. 366. 236. 291. vi. 248. 239. 232. 237. 50. 345 Vector. 380 writeObject. 345. 364. 358. 199. 359. 251. 129. 374 valueOf. 235. 245. 296 View. vi. 247. 373. 364 409 . 88. 198. 219. 388. 25. 231. 239. 365. 117. 174. 222. 240. 364 XML. 356. 236. 234. 231. 243. 232. 232. 42 Visitor. 242. 233. 349. 290. 236. 11. 94. 120. 394 Widget. vi. 270. 220. 270. 363. 87. 95. 172.

410 .

Sign up to vote on this title
UsefulNot useful