Introduction To Programming Using Java Version 4.1, June 2004

Transcription

Cover PageIntroduction to Programming Using JavaVersion 4.1, June 2004(With minor changes from Version 4.0 of July 2002)Author: David J. EckDepartment of Mathematics and Computer ScienceHobart and William Smith CollegesGeneva, New York 14456Email: eck@hws.eduWWW: http://math.hws.edu/eck/This PDF file or printout contains parts of a free textbookthat covers introductory programming with Java.The entire text is available on the World-Wide Web,for use on-line and for downloading,at this Web address:http://math.hws.edu/javanotes/The PDF file and printouts that are made from it do not show Java applets that areembedded throughout the text. Also not included are Java source code examples fromAppendix 3 and solutions to the quizzes and programming exercises. This version of thetextbook requires Java 1.3 or higher. 2002 and 2004, David J. Eck. This is a free textbook. There are no restrictions on using orredistributing a complete, unmodified copy of this material. There are some restrictions onmodified copies. To be precise: Permission is granted to copy, distribute and/or modify thisdocument under the terms of the GNU Free Documentation License, Version 1.1 or any laterversion published by the Free Software Foundation; with no invariant sections, front covertext, or back cover front-page.html [6/11/2004 11:05:08 AM]

Java Programming, Main IndexPlease Note: This is the Fourth Edition of this textbook.Many applets in this version require Java 1.3 or higher.The Third Edition, which only requires Java 1.1, is still available uction to Programming Using JavaVersion 4.1, June 2004(With minor changes from Version 4.0 of July 2002)Author: David J. Eck (eck@hws.edu)WELCOME TO Introduction to Programming Using Java, the fourth edition of a free, on-line textbookon introductory programming, which uses Java as the language of instruction. Previous versions have beenused as a textbook for an introductory programming class at Hobart and William Smith Colleges. Seehttp://math.hws.edu/eck/cs124/ for information about this course. This on-line book contains Java applets,many of which require Java 1.3 or higher. To see these applets, you will need a Web browser that uses arecent version of Java. To learn more, please read the preface.Links for downloading copies of this text can be found at the bottom of this page.Search this Text: Although this book does not have a conventional index, you can search it for termsthat interest you. Note that this feature searches the book at its on-line site, so you must be working on-lineto use it.Search Introduction to Programming Using Java for pages.Containing all of these words:Short Table of Contents: Full Table of Contents Preface Chapter 1: Overview: The Mental Landscape Chapter 2: Programming in the Small I: Names and Things Chapter 3: Programming in the Small II: Control Chapter 4: Programming in the Large I: Subroutines Chapter 5: Programming in the Large II: Objects and dex.html (1 of 3) [6/11/2004 11:06:27 AM]Search

Java Programming, Main Index Chapter 6: Applets, HTML, and GUI's Chapter 7: Advanced GUI Programming Chapter 8: Arrays Chapter 9: Correctness and Robustness Chapter 10: Advanced Input/Output Chapter 11: Linked Data Structures and Recursion Chapter 12: Generic Programming and Collection Classes Appendix 1: Other Features of Java Appendix 2: Some Notes on Java Programming Environments Appendix 3: Source Code for All Examples in this Book News and Errata 2002 and 2004, David J. Eck. This is a free textbook. There are no restrictions on using or redistributing orposting on the web a complete, unmodified copy of this material. There are some restrictions on modifiedcopies. To be precise: Permission is granted to copy, distribute and/or modify this document under the terms ofthe GNU Free Documentation License, Version 1.1 or any later version published by the Free SoftwareFoundation; with no invariant sections, front cover text, or back cover text.The most recent version of this book is always available, at no charge, for downloading and for on-line use atthe Web address http://math.hws.edu/javanotes/. The previous edition, which covered Java 1.1, can be found ading LinksUse one of the following links to download a compressed archive of this textbook: Windows: .zip (1.8 Megabytes), with textfiles in Windows/DOS format. This archive can be used directly in Windows XP. On any versin ofWindows, this archive can be extracted with WinZip, or with the free program, Aladdin StuffitExpander for Windows, available from http://www.stuffit.com/expander/.Linux/UNIX and MacOS X: .tar.bz2(1.0 Megabytes), with text files in Linux/UNIX format. If you have the bzip2 program, you shouldbe able to extract this archive with the commands "bunzip2 javanotes4.tar.bz2" followed by"tar xf javanotes4.tar". On Macintosh, this archive will probably be extracted automatically whenyou download it, or it can be extracted using Aladdin Stuffit Expander for Macintosh, availablefrom http://www.stuffit.com/expander/.Linux/UNIX: .tar.Z (2.0 Megabytes), withtext files in Linux/UNIX format. If you can't use the previous archive, try this one. You can extractthis archive on most UNIX systems with the commands "uncompress javanotes4.tar.Z" followed by"tar xf javanotes4.tar". (Note: javanotes4.tar.Z contains Version 4.0, not Version 4.1.)I know from experience that a lot of people will want to print all or part of the text. The following PDF fileis provided to make this a little easier. This is nothing fancy -- just the Web pages captured in a single file.To use this file, you need Adobe Acrobat Reader Version 4 or later. (When you click on this link, the filemight open in your Web browser; to download it, right-click the link and choose "Save Link As" or notes4/index.html (2 of 3) [6/11/2004 11:06:27 AM]

Java Programming, Main Index .pdf (2.1 Megabytes; over 550 pages)David Eck (eck@hws.edu)Version 4.0, July 2002Version 4.1, with minor changes, June .html (3 of 3) [6/11/2004 11:06:27 AM]

Java Programming: ContentsIntroduction to Programming Using Java, Fourth EditionTable of ContentsTHIS IS THE FULL TABLE OF CONTENTS for version 4.1 of an on-line introductory programmingtextbook. For more information about the text, please see its front page. The text is available on-line athttp://math.hws.edu/javanotes/.PrefaceChapter 1: Overview: The Mental Landscape Section 1: The Fetch-and-Execute Cycle: Machine Language Section 2: Asynchronous Events: Polling Loops and Interrupts Section 3: The Java Virtual Machine Section 4: Fundamental Building Blocks of Programs Section 5: Objects and Object-oriented Programming Section 6: The Modern User Interface Section 7: The Internet and World-Wide Web Quiz on this ChapterChapter 2: Programming in the Small I: Names and Things Section 1: The Basic Java Application Section 2: Variables and the Primitive Types Section 3: Strings, Objects, and Subroutines Section 4: Text Input and Output Section 5: Details of Expressions Programming Exercises Quiz on this ChapterChapter 3: Programming in the Small II: Control Section 1: Blocks, Loops, and Branches Section 2: Algorithm Development Section 3: The while and do.while Statements Section 4: The for Statement Section 5: The if Statement Section 6: The switch contents.html (1 of 4) [6/11/2004 11:06:35 AM]

Java Programming: Contents Section 7: Introduction to Applets and Graphics Programming Exercises Quiz on this ChapterChapter 4: Programming in the Large I: Subroutines Section 1: Black Boxes Section 2: Static Subroutines and Static Variables Section 3: Parameters Section 4: Return Values Section 5: Toolboxes, API's, and Packages Section 6: More on Program Design Section 7: The Truth about Declarations Programming Exercises Quiz on this ChapterChapter 5: Programming in the Large II: Objects and Classes Section 1: Objects, Instance Variables, and Instance Methods Section 2: Constructors and Object Initialization Section 3: Programming with Objects Section 4: Inheritance, Polymorphism, and Abstract Classes Section 5: this and super Section 6: Interfaces, Nested Classes and Other Details Programming Exercises Quiz on this ChapterChapter 6: Applets, HTML, and GUI's Section 1: The Basic Java Applet and JApplet Section 2: HTML Basics and the Web Section 3: Graphics and Painting Section 4: Mouse Events Section 5: Keyboard Events Section 6: Introduction to Layouts and Components Programming Exercises Quiz on this ChapterChapter 7: Advanced GUI Programming Section 1: More about Graphics Section 2: More about Layouts and Components Section 3: Basic Components and Their tents.html (2 of 4) [6/11/2004 11:06:35 AM]

Java Programming: Contents Section 4: Programming with Components Section 5: Menus and Menubars Section 6: Timers, Animation, and Threads Section 7: Frames and Applications Programming Exercises Quiz on this ChapterChapter 8: Arrays Section 1: Creating and Using Arrays Section 2: Programming with Arrays Section 3: Dynamic Arrays, ArrayLists, and Vectors Section 4: Searching and Sorting Section 5: Multi-Dimensional Arrays Programming Exercises Quiz on this ChapterChapter 9: Correctness and Robustness Section 1: Introduction to Correctness and Robustness Section 2: Writing Correct Programs Section 3: Exceptions and the try.catch Statement Section 4: Programming with Exceptions Programming Exercises Quiz on this ChapterChapter 10: Advanced Input/Output Section 1: Streams, Readers, and Writers Section 2: Files Section 3: Programming with Files Section 4: Networking Section 5: Programming Networked Applications Programming Exercises Quiz on this ChapterChapter 11: Linked Data Structures and Recursion Section 1: Recursion Section 2: Linking Objects Section 3: Stacks and Queues Section 4: Binary Trees Section 5: A Simple Recursive-descent tents.html (3 of 4) [6/11/2004 11:06:35 AM]

Java Programming: Contents Programming Exercises Quiz on this ChapterChapter 12: Generic Programming and Collection Classes Section 1: Generic Programming Section 2: List and Set Classes Section 3: Map Classes Section 4: Programming with Collection Classes Programming Exercises Quiz on this ChapterAppendix 1: Other Features of JavaAppendix 2: Some Notes on Java Programming EnvironmentsAppendix 3: Source code for all examples in the textNews and ErrataDavid J. Eck (eck@hws.edu), July 2002 and June nts.html (4 of 4) [6/11/2004 11:06:35 AM]

Java Programming: Preface to the Fourth EditionIntroduction to Programming Using Java,Fourth Edition (Version 4.1)Preface"INTRODUCTION TO PROGRAMMING USING JAVA" is a free, on-line textbook. It is suitable foruse in an introductory programming course and for people who are trying to learn programming on theirown. There is probably enough material for a full year College programming course. There are noprerequisites beyond a general familiarity with the ideas of computers and programs.In style, this is a textbook rather than a tutorial. That is, it concentrates on explaining concepts rather thangiving step-by-step how-to-do-it guides. I have tried to use a conversational writing style that might becloser to classroom lecture than to a typical textbook. You'll find programming exercises at the end of mostchapters, and you will find a detailed solution for each exercise, with the sort of discussion that I wouldgive if I presented the solution in class. (I strongly advise that you read the exercise solutions if you want toget the most out of this book.) This is certainly not a Java reference book, and it is not even close to acomprehensive survey of all the features of Java. It is not written as a quick introduction to Java for peoplewho already know another programming language. Instead, it is directed mainly towards people who arelearning programming for the first time, and it is as much about general programming concepts as it isabout Java in particular. I believe that Introduction to Programming using Java is fully competitive with theconventionally published, printed programming textbooks that are available on the market. (Well, all right,I'll confess that I think it's better.)This version of the book covers "Java 2", the version of Java that was introduced with version 1.2 of theJava Software Development Kit. It was written using version 1.3 of the development kit and should workwith later versions as well. The current version, which as of June 2004 is J2SE SDK 1.4.2, can bedownloaded from Sun Microsystem's Java page at http://java.sun.com/. ("J2SE SDK 1.4.2 stands forJava 2 Standard Edition Software Development Kit Version 1.4.2, and it is often referred to by its olderacronym, JDK, which stands for Java Development Kit. Sun has not exactly been sensible about the way itnames things.)The previous versions of this book used Java 1.1. For a long time, I was reluctant to move to Java 2because it has been much less widely supported and because most of the new features don't represent newprogramming concepts. I have finally decided to make the change for several reasons. First of all, there isone genuinely new concept in Java 2: generic programming. I have added a chapter on this topic. Second,Java 2 is, after some initial roughness, working well and can be used with a variety of Web browsers.Third, there is the upcoming switch from C to Java in the High School Advanced Placement Test inComputer Programming. I have taken the opportunity of a new version to make the book more compatiblewith the requirements of that test. There is more information below on the changes that I have made in thenew version.There are applets embedded in the pages of this book. If you want to see the applets running in your Webbrowser, you will need one that supports Java 2. Unfortunately, Microsoft's version of Java, which is usedby default in Internet Explorer on Windows, does not support it. However, if you install the Java SoftwareDevelopment Kit, the installer will give you a chance to use Sun's version of Java with Internet Explorer. Ifyou do that, Internet Explorer will be able to run all Java applets, not just old ones. (This might not work inall versions of Windows.) As far as I know, all Web browsers for MacOS X use Apple's version of Java,which supports Java 2, and should work fine. MacOS 9 and earlier, however, will never run Java 2. OnLinux, the new Mozilla 1.0 Web browser runs Java 2 reasonably well, but in my experience, it still crashesregularly when it is used with Java. (I have a lot of experience since I use Mozilla on Linux as my primarybrowser.) Every version of Java seems to get bigger. If you are unable to run Java 2, remember thatVersion 3 of this book only requires Java 1.1, and it covers most of the same basic programming preface.html (1 of 4) [6/11/2004 11:06:43 AM]

Java Programming: Preface to the Fourth EditionThere are several approaches to teaching Java. One approach uses applets and graphical user interfaceprogramming from the very beginning. Some people believe that object oriented programming should alsobe emphasized from the very beginning. This is not the approach that I take. The approach that I favor startswith the more basic building blocks of programming and builds from there. I cover proceduralprogramming in Chapters 2, 3, and 4. Object-oriented programming is introduced in Chapter 5. Chapters 6and 7 cover the closely related topic of event-oriented programming and graphical user interfaces. Arraysare covered in Chapter 8, with more coverage of data structures in Chapters 11 and 12. Chapter 10 coversfiles and input/output streams. Chapter 9 covers exception handling, which is a prerequisite for using filesin Java, and uses the opportunity for a more general discussion of the problem of writing correct and robustprograms.The current edition of Introduction to Programming using Java will always be available at the followingWeb address:http://math.hws.edu/javanotes/All editions are still available and are permanently archived at the following Web addresses:First edition: http://math.hws.edu/eck/cs124/javanotes1/Second edition: http://math.hws.edu/eck/cs124/javanotes2/Third edition: http://math.hws.edu/eck/cs124/javanotes3/Fourth edition: http://math.hws.edu/eck/cs124/javanotes4/Changes from Version 4.0Version 4.1 of the text incorporates corrections for a small number of errors that have been found since thepublication of Version 4.0. I have also taken the opportunity to add a few comments on new features ofJava that have been added since the release of Version 4.0. Since that release, Java 1.4 has been introducedand Java 1.5 is in the final stages of testing before its official release. (Note that these new topics are notcovered in any detail; for more information, see the documentation at java.sun.com.)Java 1.4 introduced assertions into the Java language, and I have added a short discussion of assertions inJava to Section 9.4. This is the only change that I cover from Java 1.4.As for Java 1.5, I have added short notes about: a new formatted printing capability (Section 2.4); anenumerated type facility (Section 4.7); templates for type-safe generic programming (Section 12.1); a newfor-loop syntax for use with Collections (Section 12.1); and automatic conversion between primitive andwrapper types (Section 12.1).Changes from the Third EditionThe big change in the fourth edition, of course, is the switch from Java 1 to Java 2. Java 2 did not changethe fundamentals of the Java language, but it did introduce many new features. The two that affect this bookare the "Swing" graphical user interface library and the framework for generic programming. Java 1 usedsomething called the AWT for GUI programming. Swing has more features and is more sophisticated. Ihave rewritten all the GUI programming examples to use Swing, and I have extensively rewritten the partsof the book that cover GUI programming. Because Swing is so complex, there are many parts of it that I donot cover, but I do cover enough to write real GUI programs. The other important new feature is a set of"Collection" and "Map" classes that represent generic, reusable data structures. Generic programming hasbecome an important topic, and I have added a new chapter to cover this preface.html (2 of 4) [6/11/2004 11:06:43 AM]

Java Programming: Preface to the Fourth EditionJava is scheduled to be used as the programming language for the High School Advanced Placement test incomputer science starting in the academic year 2003-2004. I've heard from several high school teacherswho have used the previous version of this book in their classes, and of several more who are consideringusing it. Although the previous version already covered most of the AP material, I have made a few changesto improve the coverage. For example, I moved preconditions and postconditions for subroutines fromChapter 9 to Chapter 4, I changed examples that used the Vector class to use the ArrayList classinstead, and I briefly introduce the class java.util.Random. There are two versions of the AP test. Acourse that covered Chapters 1 though 5 and Chapter 8 would include essentially all the material requiredfor the "A" test. Sections 5.5 and 5.6 could be omitted. For the "AB" test, all of Chapter 5 and topics fromChapters 9 through 12 should be added. The AP exam does not require any GUI programming, so Chapters6 and 7 could be omitted entirely. But a Java course with no graphical programming would be missing outon a lot of the fun.Here is more detailed chapter-by-chapter description of the changes: Chapters 1, 2, and 3 are almost unchanged, except for mentions of Swing in Sections 1.6 and 3.7. Chapter 4: I've added some material to Section 4.6 on preconditions and postconditions forsubroutines and included a mention of the javax package in Section 4.5.Chapter 5: I added some material on java.util.Random and ArrayList and rewrote anexample, ShapeDraw, to use ArrayList instead of Vector. I moved material on nested classesfrom Chapter 7 to Chapter 5. This material plus Section 5.5 was then split into two sections, 5.5and 5.6. Some of the material from the old 5.5 has moved into Section 5.4.Chapter 6 and 7 were throughly rewritten to use Swing, although the set of concepts that is coveredis actually not much changed. Besides the more significant changes, I dropped most of the coverageof threads in favor of timers, since timers are used instead of threads for animation in Swing. I alsodropped material on using double-buffering for animation, since double buffering is automatic inSwing. I dropped Section 6.7, which was a short description of event-handling in Java 1.0.Chapters 8 through 11: Mostly unchanged, although all graphical examples and exercises have beenrewritten to use Swing. Also, I added ArrayLists to Section 8.3, and I rewrote the material onnetworking in Sections 10.4 and 10.5. Some of the material on threads that I dropped fromChapter 7 is now in Section 10.5.Chapter 12, on generic programming, is all new.Appendices: I removed the old Appendix 1, which was a description of C for Java programmers,and replaced it with a short description of some of the advanced features of Java that are not coveredin the text. I rewrote Appendix 2, which is about Java programming environments. And of course,many of the source code files in Appendix 3 have been rewritten to use Java 2.Usage RestrictionsIntroduction to Programming using Java is free, but it is not in the public domain. As of Version 4.0, it ispublished under the terms of the GNU Free Documentation License. This license allows redistribution andmodification under certain terms. For example, you can: Post an unmodified copy of this textbook on your own Web site. Give away or sell printed, unmodified copies of this book, as long as they meet the requirements ofthe license. Post on the web or otherwise distribute modified copies, provided that the modifications are clearlynoted in accordance with the license.While it is not actually required by the license, I do appreciate hearing from people who are using ordistributing my ace.html (3 of 4) [6/11/2004 11:06:43 AM]

Java Programming: Preface to the Fourth EditionProfessor David J. EckDepartment of Mathematics and Computer ScienceHobart and William Smith CollegesGeneva, New York 14456, USAEmail: eck@hws.eduWWW: http://math.hws.edu/eck/Version 4.0, July, 2002Version 4.1, with minor changes, June 2004[ Main Index html (4 of 4) [6/11/2004 11:06:43 AM]

Java Programming: Chapter 1Chapter 1Overview: The Mental LandscapeWHEN YOU BEGIN a journey, it's a good idea to have a mental map of the terrain you'll be passingthrough. The same is true for an intellectual journey, such as learning to write computer programs. In thiscase, you'll need to know the basics of what computers are and how they work. You'll want to have someidea of what a computer program is and how one is created. Since you will be writing programs in the Javaprogramming language, you'll want to know something about that language in particular and about themodern, networked computing environment for which Java is designed.As you read this chapter, don't worry if you can't understand everything in detail. (In fact, it would beimpossible for you to learn all the details from the brief expositions in this chapter.) Concentrate on learningenough about the big ideas to orient yourself, in preparation for the rest of the course. Most of what iscovered in this chapter will be covered in much greater detail later in the course.Contents of Chapter 1: Section 1: The Fetch-and-Execute Cycle: Machine Language Section 2: Asynchronous Events: Polling Loops and Interrupts Section 3: The Java Virtual Machine Section 4: Fundamental Building Blocks of Programs Section 5: Objects and Object-oriented Programming Section 6: The Modern User Interface Section 7: The Internet and World-Wide Web Quiz on this Chapter[ First Section Next Chapter Main Index ]http://math.hws.edu/eck/cs124/javanotes4/c1/ [6/11/2004 11:07:45 AM]

Java Programming: Section 1.1Section 1.1The Fetch and Execute Cycle: Machine LanguageA COMPUTER IS A COMPLEX SYSTEM consisting of many different components. But at the heart -or the brain, if you want -- of the computer is a single component that does the actual computing. This is theCentral Processing Unit, or CPU. In a modern desktop computer, the CPU is a single "chip" on the order ofone square inch in size. The job of the CPU is to execute programs.A program is simply a list of unambiguous instructions meant to be followed mechanically by a computer.A computer is built to carry out instructions that are written in a very simple type of language calledmachine language. Each type of computer has its own machine language, and it can directly execute aprogram only if it is expressed in that language. (It can execute programs written in other languages if theyare first translated into machine language.)When the CPU executes a program, that program is stored in the computer's main memory (also called theRAM or random access memory). In addition to the program, memory can also hold data that is being usedor processed by the program. Main memory consists of a sequence of locations. These locations arenumbered, and the sequence number of a location is called its address. An address provides a way ofpicking out one particular piece of information from among the millions stored in memory. When the CPUneeds to access the program instruction or data in a particular location, it sends the address of thatinformation as a signal to the memory; the memory responds by sending back the data contained in thespecified location. The CPU can also store information in memory by specifying the information to bestored and the address of the location where it is to be stored.On the level of machine language, the operation of the CPU is fairly straightforward (although it is verycomplicated in detail). The CPU executes a program that is stored as a sequence of machine languageinstructions in main memory. It does this by repeatedly reading, or fetching, an instruction from memoryand then carrying out, or executing, that instruction. This process -- fetch an instruction, execute it, fetchanother instruction, execute it, and so on forever -- is called the fetch-and-execute cycle. With oneexception, which will be covered in the next section, this is all that the CPU ever does.The details of the fetch-and-execute cycle are not terribly important, but there are a few basic things youshould know. The CPU contains a few internal registers, which are small memory units capable of holdinga single number or machine language instruction. The CPU uses one of these registers -- the programcounter, or PC -- to keep track of where it is in the program it is executing. The PC stores the address of thenext instruction that the CPU should execute. At the beginning of each fetch-and-execute cycle, the CPUchecks the PC to see which instruction it should fetch. During the course of the fetch-and-execute cycle, thenumber in the PC is updated to indicate the instruction that is to be executed in the next cycle. (Usually, butnot always, this is just the instruction that sequentially follows the current instruction in the program.)A computer executes machine language programs mechanically -- that is without understanding them orthinking about them -- simply because of the way it is physically put together. This is not an easy concept.A computer is a machine built of millions of tiny switches called transistors, which have the property thatthey can be wired together in such a way that an output from one switch can turn another switch on or off.As a computer computes, these switches turn each other on or off in a pattern determined both by the waythey are wired together and by the program that the computer is executing.Machine language instructions are expressed as binary numbers. A binary number is made up of just twopossible digits, zero and one. So, a machine language instruction is just a sequence of zeros and ones. Eachparticular sequence encodes some particular instruction. The data that the computer manipulates is alsoencoded as binary numbers. A computer can work directly with binary numbers because switches canreadily represent such numbers: Turn the switch on to represent a one; turn it off to represent a 1.html (1 of 2) [6/11/2004 11:07:46 AM]

Java Programming: Section 1.1Machine language instructions are stored in memory as patterns of switches turned on or off. When amachine language instruction is loaded into the CPU, all that happens is that certain switches are turned onor off in the pattern that encodes that particular instruction. The CPU is built to respond to this pattern byexecuting the instruction it encodes; it does this simply because of the way all the other switches in the CPUare wired together.So, you should understand this much about how computers work: Main memory holds machine languageprograms and data. These are encoded as binary numbers. The CPU fetches machine language instructi

Introduction to Programming Using Java Version 4.1, June 2004 (With minor changes from Version 4.0 of July 2002) Author: David J. Eck (eck@hws.edu) WELCOME TO Introduction to Programming Using Java, the fourth edition of a free, on-line textbook on introductory programming, which uses Java as the language of instruction. Previous versions have been