Fundamentals of Computer Science Using Java David Hughes JONES AND BARTLETT PUBLISHERS Fundamentals of Computer Science Using Java David Hughes Brock University World Headquarters Jones and Bartlett Publishers 40 Tall Pine Drive Sudbury, MA 01776 978-443-5000 info@jbpub.com www.jbpub.com Jones and Bartlett Publishers Canada 2406 Nikanna Road Mississauga, ON L5C 2W6 CANADA Jones and Bartlett Publishers International Barb House, Barb Mews London W6 7PA UK Copyright © 2002 by Jones and Bartlett Publishers, Inc Library of Congress Cataloging-in-Publication Data Hughes, David (David John Frederick), 1952Fundamentals of computer science using Java / David Hughes p cm ISBN 0-7637-1761-4 Computer science Java (Computer program language) I Title QA76.H789 2001 005.2'76—dc21 2001029710 8888 All rights reserved No part of the material protected by this copyright notice may be reproduced or utilized in any form, electronic or mechanical, including photocopying, recording, or any information storage or retrieval system, without written permission from the copyright owner Chief Executive Officer: Clayton Jones Chief Operating Officer: Don W Jones, Jr Executive V.P and Publisher: Robert W Holland, Jr V.P., Design and Production: Anne Spencer V.P., Manufacturing and Inventory Control: Therese Bräuer Editor-in-Chief: J Michael Stranz Production Manager: Amy Rose Marketing Manager: Nathan Schultz Associate Production Editor: Tara McCormick Editorial Assistant: Theresa DiDonato Cover Design: Kristin Ohlin Composition: Northeast Compositors, Inc Text Design: Mary McKeon Printing and Binding: Courier Westford Cover Printing: John Pow Company, Inc This book was typeset in Quark 4.1 on a Macintosh G4 The font families used were Adobe Garamond, Univers, and Prestige Elite The first printing was printed on 50# Courier Opaque Printed in the United States of America 06 05 04 03 02 10 To my wife Chris, for all those times I was too busy with “the book.” iii This page intentionally left blank Preface Why this Book In the summer of 1996, our Computer Science department made the decision to use Java as the core language for our Computer Science program, beginning that fall Although there were many Java books available, we soon discovered that most were “trade” or “hobby” books, not designed for university courses and certainly not intended to serve as introductions to Computer Science It became clear to us that someone needed to write a “Fundamentals of Computer Science Using Java” book, and I thought, “why not me?” And now, after years of researching, testing, and writing, I can provide the book that we searched for years ago: a truly Java-based introduction to Computer Science In a first course in Computer Science, the primary goal is to teach the fundamentals of the field Basic concepts are introduced with the help of a programming language that is often viewed as simply a medium through which algorithms are expressed From that perspective, it does not matter which language is used in an introductory course, because any would suffice In practice, however, the language can have a profound impact on the students’ learning experience First, the style of the language constrains the way and the order in which topics can be introduced Further, the language taught in the first course must support the rest of the curriculum For these reasons and more, a language-defined text is an important component in an introductory course Object-oriented languages in particular are useful in introductory textbooks and are certainly appropriate at this time Having an object-oriented language as the core programming language supports many courses at the higher level (e.g., software engineering, user interfaces, databases) The question is, then, which object-oriented language? v PREFACE Our decision to use Java was based on a number of factors First, we recognized Java as a pure object-oriented language, as opposed to C++, which is a hybrid, and thus does not allow the programmer to fall back into procedural habits Further, it has a relatively clear and common syntax that can be understood without having to learn a large class hierarchy Finally, Java has compilers available on a great many platforms that are inexpensive, not overly resource hungry, and the code is platform-independent All of these things make Java ideal for a first university course The approach taken in this book is what might best be called an “object-based” approach It is my belief that students need to master the skill of method writing before they can craft meaningful classes Objects occur right from the start The student’s code, however, is written as a client of another class, and thereby makes use of objects through the delegation model rather than the inheritance model The text introduces methods as early as possible and then introduces the control structures and types necessary for writing methods When classes are fully introduced, the students are completely capable of writing the methods for a class and are familiar with writing one class as a client of another They soon master writing a class as a supplier Once classes are available, the text introduces object-oriented software development using classes for the decomposition Responsibility-based design is also introduced using CRC cards as the design methodology The pedagogical approach applied to this text is grounded in the idea that the learning process can be facilitated through the use of examples Each new topic is introduced through a number of complete program examples Examples are kept as simple as possible to illustrate important concepts At the same time, the examples are realistic, and allow for meaningful use of new constructs Students can often use the examples as a starting point for coding of assignment problems What is Covered and What is Not Java, like any programming language, is fairly large and this book does not attempt to provide complete coverage of all Java topics As an object-oriented language, Java has many standard class libraries and many other APIs, and therefore it would not be possible to provide complete coverage of the language even if I so wished The first decision I made was to exclude inheritance This might seem like heresy, however, I stand by this decision and believe it is appropriate to exclude inheritance from an introductory course In my experience, students have trouble understanding the true meaning of inheritance, and this often leads them to use inheritance as simply a mechanism for code borrowing This is very evident in the structure of many books that introduce Computer Science in an object-oriented language In an attempt to make the first programs interesting, these texts can overuse subclassing Code reuse through delegation is a much simpler, and often more desirable, approach In a first course, I prefer to foster in my students a clear understanding of the basic principles, and I leave inheri- vi PREFACE tance and subclassing for a later course In our program, inheritance and polymorphism are introduced in the second year One possible objection to excluding inheritance is that without it we cannot write applets This is a small loss, as it would be nice if the student’s programs could be demonstrated using a web browser The level of programming necessary for writing applets, however, is really too advanced for an introductory course, since it requires the use of graphical user interfaces to anything reasonable To allow interesting first programs, the class library TurtleGraphics is used This class library supports the turtle graphics model introduced in the programming language Logo The AWT and Swing are also not covered in this book GUI programming requires an event model for programming that allows apparent non-linear flow of control This is confusing for first-year students Instead, the I/O class library BasicIO is used This I/O class library provides a class for prompted input via the dialog box ASCIIPrompter and provides output to the scrollable window ASCIIDisplayer Even though inheritance is not covered, classes definitely are Classes are the fundamental decomposition mechanism in object-oriented design Of course, without inheritance the design model is incomplete; however, designing with inheritance is difficult and better learned when a student’s programming skills are more mature Exceptions are also a difficult concept for beginning students to grasp because they introduce a second path of execution Since Java requires that any exception (other than RunTimeException) be caught or thrown by the method, code dealing with exceptions obscures the expression of the algorithm The most common occurrence of exceptions is in I/O To remove the need to deal with exceptions too early, the BasicIO library does not throw exceptions Use of the Book At Brock, the material presented here forms the substance of a half-year (twelve-week) course meeting three hours per week The lectures are supplemented by a one-hour tutorial, which is primarily a question and answer period, and a two-hour laboratory where the students work on programming assignments The primary goal of our course is to introduce basic computer science concepts, while introducing language concepts as needed Chapter includes a brief history of computing and computing technology, and then describes the basic hardware and software organization of computer systems The material in Appendix A may be used to supplement this coverage, or can be introduced at a later time for a clearer understanding of the low-level execution of programs Chapter also provides a preview to the software development process, and the phases included in this chapter are repeated in the Case Studies of later chapters Chapter begins the coverage of Java It introduces the Java syntax notation so that students will be able to read the syntax descriptions that define the language Turtle Graphics are used to enhance the early examples Programs are written as clients of vii PREFACE Turtle objects and make use of simple looping and nesting of loops to produce interesting graphics Chapter introduces computations and the basic arithmetic operators of Java Since results of computations must be stored, it also introduces variables and assignment Chapter covers methods as a mechanism for procedural abstraction It covers simple methods, method invocation, parameter passing, and method results, as well as scope issues Chapter covers I/O, specifically the BasicIO package It describes streams as an abstraction of I/O and covers input and output streams and output formatting The stream concept is consistent with the java.io package, and so many of these concepts are transferable Chapter introduces control structures Some control structures have already been used in their simplest form, but here they are described in detail The chapter spends its time on the important structures, while only mentioning the less frequently used structures Chapter covers the boolean and char types and emphasizes the difference between primitive and reference types Boolean expressions are explained here in detail, building from their use in Chapter Some of the basic services of the Character class are introduced Chapter describes classes Classes have been used throughout the text, however, prior to this chapter, example programs involved a single class as a client of one or more library classes Here programs make use of multiple classes Additionally, class interaction and information hiding principles are explained Chapter introduces software development Classes are used as the decomposition mechanism using a responsibility-based approach to design The traditional seven phases of the software development life cycle are described Chapter 10 covers the String class and special processing for text manipulation Finally, Chapter 11 covers arrays, including both single- and two-dimensional arrays, and describes standard array processing techniques Each chapter represents approximately one week, or three lecture hours, of material Chapters 1, 4, 9, and 11 generally take a bit longer, while some of the other chapters take slightly less time By emphasizing or de-emphasizing certain material, the text can easily accommodate a ten- to thirteen-week course The sections marked with a star (*) are optional and can be omitted without loss of context in later chapters The material in Appendix A can be used to augment Chapter if this is seen as desirable The presentation is sequential and most chapters depend on material presented in previous chapters Some of the material from Chapter 1, specifically the sections on computer software and social issues, may be deferred and introduced wherever convenient Similarly, the section on syntax in Chapter can be de-emphasized as long as the syntax descriptions in later chapters are explained as they are introduced viii INDEX Empty string ("), 318 Encryption, 22, 360 End-of-file (EOF), 130, 208, 233-234, 355, 363 End-of-line (EOL), 133, 232, 240 English sentences, 35 English text analysis example, 334-336 e-notation, 57, 58 Enrollment statistics production example, 378-382 Environment, and computers, 23-24 EOF See End-of-file EOL See End-of-line Equality operator (==), 217, 218, 230, 336 equalsIgnoreCase method, 324, 325 equals method, 324, 336 Errors, 24, 279, 309 at boundary of condition, 207 execution, 21 link, 21 logic, 21 syntax, 20 Escape sequences, 229, 230 Euclid, Evens-Odds game case study, 224-228 Examples above-average rainfall with input method, 357 analyzing text, 334-336 averaging marks, 147-150 centering square, 64-67 class average revisited, 176-180 compound interest table revisited, 144-146 compound interest table with user input, 199-202 computing class average, 418, 419, 432 computing pay, 60-62, 424 computing root of equation, 423 converting uppercase to lowercase, 231-233, 426 copying text file, 322-323 counting letter frequencies, 360-362 counting pass and fail, 190-193 Dean’s list, 182-185 derivation of English sentence, 35 detecting palindromes, 325-327 determining class statistics (highest/lowest marks), 186-190 drawing a scene, 87 drawing beach umbrella, 104-106 drawing eight squares, 48-49 drawing nested squares, 99-101 drawing nested squares using method with parameter, 101 drawing rectangles, 106-109 drawing square, 32 drawing square using countable repetition pattern, 43 drawing square using method with parameter, 99 draw rectangles using method with two parameters, 108 filling a packing box, 165-169 finding average rainfall, 436, 438 finding highest mark, 434 finding roots of equation, 170-173 formatting name, 329-331 formatting table of squares, 135-138 function method, 109 generating compound interest table, 138-140 generating table of squares, 133-135 method for drawing square, 88 method reading data into variable-sized array, 358 method returning an array, 359 modified Course class, 368-369 modified MarkingScheme class, 371-372 modified Report class, 373-374 modified Student class, 369-371 of patterns, 415 pay calculation, using variables, 71-72 pay calculation with input, 78 producing compound interest table, 428 producing Dean’s List, 421 producing enrollment statistics, 378-382 producing marks report, 430 reversing string, 364, 431 511 INDEX Examples (continued) scene drawing, 93-95 scene with triangle, square, and pentagon, 95 tallying grades, 194-198 two methods for drawing a square, 97 university enrollment report, 375-377 Exchange Values pattern, 364, 431 Exclamation point (!) for not operator, 177 Executing instruction, 392, 393, 394 Executing the method, 86 Execution, 17, 21 of assembly-language program, 18 of high-level language program, 19 Execution errors, 21 Expressions, 58-66, 82 Java syntax for, 409-413 parentheses within, 223 sample, 61 Extended Binary Coded Decimal Interchange Code See EBCDIC F false value, 165, 166, 206 Fetching, 13 Fetching instruction, 392, 393 Field declarations, 41, 67, 251, 342 Fields, 40-41, 50, 135, 250, 270 Java syntax for, 400-401 of records, 186 width of, 135 File folders, 14 Filling a box example, 169 Financial profiles, 22 Find Maximum pattern, 434, 435 Find Minimum pattern, 434, 435 Finite state machine, 236, 241 First-generation languages, 17 First generation of computers, Fixed-point literals, 57-58 512 Fixed-point numbers, 56 Fixed-point types, 56-57, 63 Flicker, 23 Floating-point literals, 58 Floating-point numbers, 56 Floating-point types, 57 float type, 56, 57, 63, 216, 240 ForInit part, 199 Formal parameter, 98 Formal parameter declaration, 98 FormalParameterList, 98 Formal parameter lists, 342 Formatted output, 135 Formatting methods, 157 Formatting table of squares example, 135-138 Formula translation system See FORTRAN for statement, 42, 164, 198-199, 208 FORTRAN, 20 ForUpdate part, 199 forward method, 37, 86, 98 Fourth generation of computers, Freedom of expression, 22 Function, 109 Function method header, 109 Function method invocation, 65, 112 Function methods, 76, 109-112 arrays as results of, 359 with parameters, 112 Function plot program, revisiting, 111-112 Function plotting case study, 74-76 G Gamma, E., 415n1 Garbage, 261 Garbage collection, 261, 320 Gates, Bill, General array-traversal programming pattern, 346 get method, 266 Gosling, James, 2, 30 Grade report class design, 287 INDEX Grade-reporting system revisited case study, 365374 analysis and design, 365-366 implementation, 367 sample data file for, 366 sample report from, 367 testing and debugging, 374 GradeReport (main) class, 303-305 Grade report system case study, 279-305 analysis, 280 analysis model, 282 architectural plan, 286 candidate objects, 281 coding, 293 Course class, 298-300 Course class specification, 286, 288 CRC cards, 283-284 design, 283, 287 GradeReport (main) class, 303-305 identified objects, 281-282 MarkingScheme class, 293-295 MarkingScheme class specification, 290 problem statement, 280 refined problem statement, 280 Report class, 300-303 Report class specification, 291-293 Student class, 295-298 Student class specification, 288-289 testing, 305 Grades tallying example, 194-198 test data for, 207 Grammar, 33 See also Syntax Grammatical rules, 33 Graphical user interface, 8, 131 Graphic character, 229 Graphics, 30, 229 Greater than operator (>), 217 Greater than or equal to operator (>=), 182, 217 Green PCs, 23 GUI See Graphical user interface Gunther, Edmund, H Hackers, 24 Happiness message, 155 Hard disk, 130 Hard drive, 14 Hardware, 2, 8, 25, 318 components, Hate literature, 22 Hexagon drawing, 44-45 geometry of, 79 scaled, centered on turtle, 79-80, 81 scaling program modification, 77, 79-81 Hexagons nesting of, for drawing beach umbrella, 104-106 Hidden instance variables/methods, 119 Highest/lowest marks example, 186-190 High-level language program executing, 19 High-level languages, 19, 20, 30 Hypertext Markup Language (HTML), 30, 245 I IAR See Instruction address register IBM PC, 8, 49 Icons, 14 Identifiers, 34, 39, 58 method, 90 variable, 67 IDEs See Interactive development environments if statement, 180-182, 186, 208 if-then-elseif statement, 195, 206, 208 if-then-else statement, 180, 208 execution of, 181 if-then statement, 180, 208 execution of, 181 Immutable objects, 319, 336, 363 513 INDEX Implementing the interface, 268 import statement, 31 Increment, 199 Incrementation, 76 Indefinite loop, 164 Indentation of body of loop, 170 of constructor header, 40 of if statements, 186 of instance variable declarations, 41 of local variable declarations, 72 of method headers, 90 Index, 43, 328 Industrial Age, 21 Infinite loop, 166 Information, 3, 21 Information Age, 21 Information hiding, 262, 265-267, 270 Information processing systems, 277 Information systems, Inheritance, 270 Input, 4, 143-150, 157, 277 for grade report system, 280 Input and output (I/O), 129-162 input, 143-150, 157 output, 132-143, 157 purposes of, 132 streams, 130-132, 157, 268-269 Input devices, 10 Input/output patterns, 423-430 process line-oriented text file, 425-426 report generation, 428-430 stream I/O, 423-425 table generation, 427-428 Input streams, 157 Instances, 250 Instance variable declarations, 72 Instance variable identifiers, 41, 72 Instance variables, 41, 50, 68, 82, 118, 122, 270, 286, 342 Instruction address register, 392 514 Instruction processing, 391, 392 Instruction register, 392, 393 Integer division, 59, 70 Integer mode expression, 63 Integrated circuit, Intel, 391 Intellectual property rights, 23 Intent section, patterns, 415 Interactive development environments, 14, 21 Interfaces, 268 Java syntax for, 403-404 Internationalization, 229 Internet, 10, 20, 22 Internet addiction, 23 Internet Explorer, 49, 245 In-test loop, 175, 208 condition in, 180 execution of, 176 testing, 207 int expression, 63 int type, 56, 57, 63, 68, 81, 216, 240 int value, 63 int variable, 43 Invoking the method, 86 IR See Instruction register ISO standards, 228, 229 J Jacquard automated weaving loom, Java, 13, 20, 30-31, 229, 270 Java applets, 50 java.awt class Color class in, 106 Java bytecode, 49, 51 Java compiler, 51 JavaDoc comment, 38 JavaDoc processor, 265 Java interpreter, 49, 50, 51 Java I/O library, 268 java.lang library, 318 Character class within, 234 INDEX String class of, 324 java.lang.Object SimpleDataInput and extension of, 477 Java Language Specification, The, 33, 397 Java operators basic, 58-59 Java programming language, 2, 50 Java programs execution of, 20, 49, 50 Java runtime, 261 Java scope rules, 118 Java syntax, 397-413 blocks and statements, 405-409 classes, 399-400 constructors, 402 expressions, 409-413 fields and variables, 400-401 interfaces, 403-404 methods, 401-402 names, 405 notation, 397-398 packages, 398-399 reserved words, 413 types, 404 See also Style tips; Syntax java.util library, 332 Java virtual machine, 229 Java visibility rules, 119, 121 Jobs, and computers, 21 K Keyboard, 130 Keywords, 34 King, Ada Augusta, 4, 20 L Laptop computer, Large-scale software development, 276, 310 Lazy evaluation, 220 Left-hand sides, 397 left method, 37 Length, of dimension of array, 344 length attribute, 358, 376, 384 Less than operator (