This online teaching and learning environment integrates the entire digital textbook with the most effective instructor and student resources WRÀWHYHU\OHDUQLQJVW\OH With WileyPLUS: Students achieve concept mastery in a rich, structured environment that’s available 24/7 Instructors personalize and manage their course more effectively with assessment, assignments, grade tracking, and more manage time better study smarter save money From multiple study paths, to self-assessment, to a wealth of interactive visual and audio resources, WileyPLUS gives you everything you need to personalize the teaching and learning experience » F i n d o u t h ow t o M A K E I T YO U R S » www.wileyplus.com ALL THE HELP, RESOURCES, AND PERSONAL SUPPORT YOU AND YOUR STUDENTS NEED! 2-Minute Tutorials and all of the resources you & your students need to get started www.wileyplus.com/firstday Student support from an experienced student user Ask your local representative for details! Collaborate with your colleagues, find a mentor, attend virtual and live events, and view resources www.WhereFacultyConnect.com Pre-loaded, ready-to-use assignments and presentations www.wiley.com/college/quickstart Technical Support 24/7 FAQs, online chat, and phone support www.wileyplus.com/support Your WileyPLUS Account Manager Training and implementation support www.wileyplus.com/accountmanager MAKE IT YOURS! Java th edition Concepts This page intentionally left blank th edition Java Concepts Cay Horstmann JOHN WILEY & SONS, INC SAN JOSE STATE UNIVERSITY VICE PRESIDENT AND EXECUTIVE PUBLISHER EXECUTIVE EDITOR EDITORIAL ASSISTANT PRODUCTION SERVICES MANAGER PRODUCTION EDITOR EXECUTIVE MARKETING MANAGER CREATIVE DIRECTOR SENIOR DESIGNER PHOTO EDITOR MEDIA EDITOR PRODUCTION SERVICES COVER DESIGNER COVER ILLUSTRATION Donald Fowley Beth Lang Golub Michael Berlin Dorothy Sinclair Janet Foxman Christopher Ruel Harry Nolan Madelyn Lesure Lisa Gee Lauren Sapira Cindy Johnson Howard Grossman Susan Cyr This book was set in Stempel Garamond by Publishing Services, and printed and bound by RRD Jefferson City The cover was printed by RRD Jefferson City This book is printed on acid-free paper ∞ Copyright © 2010, 2008, 2006, 2003 John Wiley & Sons, Inc All rights reserved No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, website www.copyright.com Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, (201) 748-6011, fax (201) 748-6008, website www.wiley.com/go/permissions Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in their courses during the next academic year These copies are licensed and may not be sold or transferred to a third party Upon completion of the review period, please return the evaluation copy to Wiley Return instructions and a free of charge return shipping label are available at www.wiley.com/go/returnlabel Outside of the United States, please contact your local representative Library of Congress Cataloging-in-Publication Data: Horstmann, Cay S., 1959Java concepts : compatible with Java 5, 6, and / Cay Horstmann — 6th ed p cm Includes index ISBN 978-0-470-50947-0 (pbk.) Java (Computer program language) Electronic data processing I Title QA76.73.J38H6754 2010 005.13'3 dc22 2009042603 ISBN 978-0-470-50947-0 Printed in the United States of America 10 PREFACE This book is an introductory text in computer science, focusing on the principles of programming and software engineering Here are its key features: • Teach objects gradually In Chapter 2, students learn how to use objects and classes from the standard library Chapter shows the mechanics of implementing classes from a given specification Students then use simple objects as they master branches, loops, and arrays Object-oriented design starts in Chapter This gradual approach allows students to use objects throughout their study of the core algorithmic topics, without teaching bad habits that must be un-learned later • Reinforce sound engineering practices A focus on test-driven development encourages students to test their programs systematically A multitude of useful tips on software quality and common errors encourage the development of good programming habits • Help students with guidance and worked examples Beginning programmers often ask “How I start? Now what I do?” Of course, an activity as complex as programming cannot be reduced to cookbookstyle instructions However, step-by-step guidance is immensely helpful for building confidence and providing an outline for the task at hand The book contains a large number of “How To” guides for common tasks, with pointers to additional worked examples on the Web • Focus on the essentials while being technically accurate An encyclopedic coverage is not helpful for a beginning programmer, but neither is the opposite—reducing the material to a list of simplistic bullet points that give an illusion of knowledge In this book, the essentials of each subject are presented in digestible chunks, with separate notes that go deeper into good practices or language features when the reader is ready for the additional information • Use standard Java The book teaches the standard Java language—not a specialized “training wheels” environment The Java language, library, and tools are presented at a depth that is sufficient to solve real-world programming problems • Provide an optional graphics track Graphical shapes are splendid examples of objects Many students enjoy writing programs that create drawings or use graphical user interfaces If desired, these topics can be integrated into the course by using the materials at the end of Chapters 2, 3, 9, and 10 vii viii Preface New in This Edition This is the fourth edition of Big Java, and the book has once again been carefully revised and updated The new and improved features include: More Help for Beginning Programmers • The How To sections have been updated and expanded, and four new ones have been added Fifteen new Worked Examples (on the companion web site and in WileyPLUS) walk students through the steps required for solving complex and interesting problems • The treatment of algorithm design, planning, and the use of pseudocode has been enhanced Students learn to use pseudocode to define the solution algorithm in Chapter • Chapters have been revised to focus each section on a specific learning objective These learning objectives also organize the chapter summary to help students assess their progress Annotated Examples • Syntax diagrams now call out features of typical example code to draw student attention to the key elements of the syntax Additional annotations point out special cases, common errors, and good practice associated with the syntax • New example tables clearly present a variety of typical and special cases in a compact format Each example is accompanied by a brief note explaining the usage shown and the values that result from it • The gradual introduction of objects has been further improved by providing additional examples and insights in the early chapters Updated for Java • Features introduced in Java are covered as Special Topics so that students can prepare for them In this edition, we use Java or for the main discussion More Opportunities for Practice • The test bank has been greatly expanded and improved (See page xi.) • A new set of lab assignments enables students to practice solving complex problems one step at a time • The LabRat code evaluation feature, enhanced for this edition, gives students instant feedback on their programming assignments (See page xvi.) 652 Index invoking programs See starting programs is-a relationships, 334, 449–450 isDigit method, java.lang.Character class method summary, 609 reading text, line by line, 412–413 testing characters, 173 isEditable method javax.swing.JComboBox class, 624 javax.swing.text.JTextComponent class, 628 isLetter method, java.lang.Character class, 173, 609 isLowerCase method, java.lang.Character class, 173, 609 isSelected method, javax.swing.AbstractButton class, 623 isUpperCase method, java.lang.Character class, 173, 609 isWhiteSpace method, detecting whitespace, 413 iteration See enumeration types; for loops; loops; while loops iterator method, java.util.Collection interface, 618 iterators, linked lists, 557–559 J Java language See also Java programs code name “Green,” collections of code See libraries portability, safety, security, versions, summary of, 10t Java operators, summary of, 593t– 594t See also specific operators Java programs See also Java language; programs; specific elements basic structure, 10–13 case sensitivity, 14 class files, 15 collections of code See libraries compiling, 14–16 creating and modifying code, 14 free-form layout, 14 “Hello World” example, 10–13 JVM (Java Virtual Machine), 7–8 running, 14–16 source code, 15 Java Virtual Machine (JVM), 7–8 java.applet package, 311t, 600 java.applet.Applet class, method summary, 600 See also specific methods java.awt package, 311t, 600–603 java.awt.BorderLayout class, method summary, 600 See also specific methods java.awt.Color class drawing in color, 61–63 method summary, 600 See also specific methods java.awt.Component class frame title bar, visibility, 55 method summary, 601 See also specific methods preferred size, setting, 356 repainting graphic components, 356 java.awt.Container class, method summary, 601 See also specific methods java.awt.Dimension class, method summary, 601 See also specific methods java.awt.event package, 603–604 java.awt.event.ActionListener interface application buttons, 353 method summary, 603 See also specific methods java.awt.event.MouseEvent class, method summary, 604 See also specific methods java.awt.event.MouseListener interface, method summary, 604 See also specific methods java.awt.FlowLayout class, method summary, 601 See also specific methods java.awt.Font class, method summary, 602 See also specific methods java.awt.Frame class frame size, setting, 55 method summary, 602 See also specific methods java.awt.geom package, 604–605 java.awt.geom.Ellipse2D.Double class drawing ellipses and circles, 59–60 method summary, 604 See also specific methods java.awt.geom.Line2D class, method summary, 604 See also specific methods java.awt.geom.Line2D.Double class drawing lines, 60 method summary, 605 See also specific methods java.awt.geom.Point2D class, method summary, 605 See also specific methods java.awt.geom.Point2D.Double class drawing lines, 60 method summary, 605 See also specific methods java.awt.geom.RectangularShape class, method summary, 605 See also specific methods java.awt.Graphics class colored drawings, 61–63 description, 57 examples, 57–59 method summary, 602 See also specific methods java.awt.Graphics2D class casting, 57 colored fills, 61 description, 57 drawing an ellipse, 60 drawing strings, 60 examples, 57–59 method summary, 602 See also specific methods java.awt.GridLayout class, method summary, 602 See also specific methods java.awt.Rectangle class, method summary, 602–603 See also specific methods java.awt.Shape interface, 603 javadoc utility, 84 java.io package, 311t, 606–608 java.io.EOFException class, method summary, 606 See also specific methods java.io.File class See also java.util.Scanner class method summary, 606 See also specific methods reading text files, 408–410 Index 653 class, method summary, 606 See also specific methods java.io.FileNotFoundException class description, 409 input/output files missing, 409 summary, 606 java.io.FileOutputStream class, method summary, 606 See also specific methods java.io.InputStream class, method summary, 606–607 See also specific methods java.io.InputStreamReader class, method summary, 607 See also specific methods java.io.IOException class checked exceptions, 421–423 reading Web pages, 411 summary, 607 java.io.ObjectInputStream class, method summary, 607 See also specific methods java.io.ObjectOutputStream class, method summary, 607 See also specific methods java.io.OutputStream class, method summary, 607 See also specific methods java.io.PrintStream class libraries, 16 method summary, 607–608 See also specific methods java.io.PrintWriter class automatic object closing, 428 closing output files, 409 method summary, 607–608 See also specific methods writing text files, 408–410 java.io.RandomAccessFile class, method summary, 608 See also specific methods java.lang package, 311t, 609–615 java.lang.Boolean class, method summary, 609 See also specific methods java.lang.Character class method summary, 609 See also specific methods reading text, line by line, 412–413 testing characters, 173 java.lang.Cloneable interface implementing the clone method, 396 java.io.FileInputStream summary, 609 java.lang.CloneNotSupportedException class, 609 interface implementing, 545–546 method summary, 609 See also specific methods parameterized type, 547 sorting real data, 545–546 java.lang.Double class, method summary, 610 See also specific methods java.lang.Error class, summary, 610 java.lang.Comparable java.lang.IllegalArgumentException class method summary, 610 See also specific methods throwing exceptions, 419 unchecked exceptions, 421–423 java.lang.IllegalStateException class summary, 610 throwing an exception, 419–421 java.lang.Integer class converting strings to integers, 135 maximum values, finding, 116 method summary, 610–611 See also specific methods minimum values, finding, 116 java.lang.Math class, method summary, 126t, 611–613 See also specific methods java.lang.NullPointerException class summary, 613 unchecked exceptions, 421–423 java.lang.NumberFormatException class reading numbers, 414 summary, 613 unchecked exceptions, 421–423 java.lang.Object class, method summary, 613 See also specific methods java.lang.RuntimeException class summary, 613 unchecked exceptions, 421–423 java.lang.String class method summary, 614 See also specific methods overview, 134–135 java.lang.System class libraries, 16 method summary, 615 See also specific methods out object, 11, 16 java.lang.Throwable class catching exceptions, 425 method summary, 615 See also specific methods retrieving error messages, 429 java.math package, 615–616 java.math.BigDecimal class, method summary, 615–616 See also specific methods java.math.BigInteger class, method summary, 616 See also specific methods java.net package, 311t, 616 java.net.URL class, method summary, 616 See also specific methods java.swing package, 311t java.util package, 311t, 616–622 java.util.ArrayList class adding array elements, 250, 263 array lists, 250 examples, 250t removing array elements, 250, 262 syntax enhancements, 253 java.util.ArrayList class, method summary, 616–617 See also specific methods java.util.Arrays class copying arrays, 264 method summary, 617 See also specific methods java.util.Calendar class, method summary, 618 See also specific methods java.util.Collection interface, method summary, 618 See also specific methods java.util.Collections class, method summary, 619 See also specific methods java.util.Comparator interface comparing objects, 547 method summary, 619 See also specific methods java.util.EventObject class, method summary, 619 See also specific methods java.util.GregorianCalendar class, method summary, 619 See also specific methods java.util.HashMap class, method summary, 619 See also specific methods 654 Index class, method summary, 619 See also specific methods java.util.HashSet java.util.InputMismatchException class, 619 java.util.Iterable interface, 561 java.util.Iterator interface, method summary, 619 See also specific methods java.util.LinkedList class, method summary, 620 See also specific methods java.util.List interface, method summary, 620 See also specific methods java.util.ListIterator interface implementing linked lists, 564–572 method summary, 620 See also specific methods java.util.logging package, 622–623 java.util.logging.Level class, 622 java.util.logging.Logger class logging trace messages, 180–181 method summary, 622–623 See also specific methods java.util.Map interface, method summary, 620–621 See also specific methods java.util.NoSuchElementException class, 423 reading text numbers, 414 summary, 621 java.util.PriorityQueue class, method summary, 621 See also specific methods java.util.Random class, method summary, 621 See also specific methods java.util.Scanner class See also java.io.File class automatic close, 428 creating with a string, 410–411 method summary, 621–622 See also specific methods patterns for word boundaries, specifying, 412 testing calls to NextDouble method, 174 java.util.Scanner class, reading input character by character, 415 from a keyboard, 138–140 line by line, 412–413 reading text numbers, 414 regular expressions, 415–416 text files, 408–410 word by word, 411–412 java.util.Set interface, 622 java.util.TreeMap class, method summary, 622 See also specific methods java.util.TreeSet class, method summary, 622 See also specific methods javax.swing package, 623–627 javax.swing.AbstractButton class, method summary, 623 See also specific methods javax.swing.border package, 627 javax.swing.border.EtchedBorder class, method summary, 627 See also specific methods javax.swing.border.TitledBorder class, method summary, 627 See also specific methods javax.swing.ButtonGroup class, method summary, 623 See also specific methods javax.swing.event package, 628 javax.swing.event.ChangeEvent class, 628 javax.swing.event.ChangeListener interface, method summary, 628 See also specific methods javax.swing.ImageIcon class, method summary, 623 See also specific methods javax.swing.JButton class buttons, 352–355 method summary, 623 See also specific methods javax.swing.JCheckBox class, method summary, 623 See also specific methods javax.swing.JComboBox class, method summary, 624 See also specific methods javax.swing.JComponent class, method summary, 624 See also specific methods javax.swing.JFileChooser class, method summary, 624 See also specific methods javax.swing.JFrame class default close operation, setting, 55 frame size, setting, 55 frame title, setting, 55 frame visibility, setting, 55 method summary, 625 See also specific methods javax.swing.JLabel class buttons, 352–355 method summary, 625 See also specific methods javax.swing.JMenu class, method summary, 625 See also specific methods javax.swing.JMenuBar class, method summary, 625 See also specific methods javax.swing.JMenuItem class, method summary, 625 See also specific methods javax.swing.JOptionPane class, method summary, 626 See also specific methods javax.swing.JPanel class button panels, 353 summary, 626 javax.swing.JRadioButton class, method summary, 626 See also specific methods javax.swing.JScrollPane class, method summary, 626 See also specific methods javax.swing.JSlider class, method summary, 626 See also specific methods javax.swing.JTextArea class, method summary, 627 See also specific methods javax.swing.JTextField class, method summary, 627 See also specific methods javax.swing.text package, 628 javax.swing.text.JTextComponent class, method summary, 628 See also specific methods javax.swing.Timer class, method summary, 627 See also specific methods JButton constructor, javax.swing.JButton class, 623 JCheckBox constructor, javax.swing.JCheckBox class, 623 JComboBox constructor, javax.swing.JComboBox class, 624 Index 655 JFileChooser constructor, javax.swing.JFileChooser java.io.RandomAccessFile class, 624 JLabel constructor, javax.swing.JLabel class, 625 JMenu constructor, javax.swing.JMenu class, 625 JMenuBar constructor, javax.swing.JMenuBar class, JMenuItem constructor, javax.swing.JMenuItem 625 class, 625 JRadioButton constructor, javax.swing.JRadioButton java.lang.String class, 614 less-than operator (