Professional Documents
Culture Documents
Big Java
6/e Early Objects
1. Introduction
Fundamentals
2. Using Objects
Object-Oriented Design
Data Structures & Algorithms
Applied Topics
3. Implementing
Online Chapters
Classes
4. Fundamental
Data Types
5. Decisions
6. Loops
21. Advanced 23. Internet 24. Relational 15. The Java 14. Sorting
9. Inheritance
Input/Output Networking Databases Collections and Searching
Framework
26. Web
Applications 19. Stream
Processing
volumes, many instructors prefer that a textbook should give students additional
reference material valuable beyond their first course. Some institutions also teach a
second-semester course that covers more practical programming aspects such as data-
base and network programming, rather than the more traditional in-depth material
on data structures and algorithms. This book can be used in a two-semester course
to give students an introduction to programming fundamentals and broad coverage
of applications. Alternatively, the material in the final chapters can be useful for stu-
dent projects. The applied topics include graphical user-interface design, advanced
file handling, multithreading, and those technologies that are of particular interest to
server-side programming: networking, databases, XML, and web applications. The
Internet has made it possible to deploy many useful applications on servers, often
accessed by nothing more than a browser. This server-centric approach to application
development was in part made possible by the Java language and libraries, and today,
much of the industrial use of Java is in server-side programming.
Appendices
Many instructors find it highly beneficial to require a consistent style for all assign-
ments. If the style guide in Appendix E conflicts with instructor sentiment or local
customs, however, it is available in electronic form so that it can be modified. Appen-
dices F–J are available on the Web.
A. The Basic Latin and Latin-1 F. Tool Summary
Subsets of Unicode G. Number Systems
B. Java Operator Summary H. UML Summary
C. Java Reserved Word Summary I. Java Syntax Summary
D. The Java Library J. HTML Summary
E. Java Language Coding Guidelines
viii Preface
Web Resources
This book is complemented by a complete suite of online resources. Go to www.wiley.
com/college/horstmann to visit the online companion sites, which include
• Source code for all example programs in the book and its Worked Examples, plus
additional example programs.
• Worked Examples that apply the problem-solving steps in the book to other
realistic examples.
• Lecture presentation slides (for instructors only).
• Solutions to all review and programming exercises (for instructors only).
• A test bank that focuses on skills, not just terminology (for instructors only). This
extensive set of multiple-choice questions can be used with a word processor or
imported into a course management system.
• “CodeCheck” assignments that allow students to work on programming prob-
lems presented in an innovative online service and receive immediate feedback.
Instructors can assign exercises that have already been prepared, or easily add
their own.
Go to wiley.com/go/
bjeo6code to download
a program that dem-
onstrates variables
and assignments.
Walkthrough ix
provides complete programs for FULL CODE EXAMPLE Some people call this loop count-controlled. In con-
Go to wiley.com/go/ trast, the while loop of the preceding section can be
students to run and modify. bjeo6code to download
a program that
called an event-controlled loop because it executes
uses common loop until an event occurs; namely that the balance reaches
algorithms. the target. Another commonly used term for a
count-controlled loop is definite. You know from
the outset that the loop body will be executed a
definite number of times; ten times in our example.
In contrast, you do not know how many iterations it
takes to accumulate a target balance. Such a loop is
Annotated syntax boxes called indefinite. You can visualize the for loop as
an orderly sequence of steps.
provide a quick, visual overview
of new language constructs. Syntax 6.2 for Statement
In the same way that there can be a street named “Main Street” in different cities,
a Java program can have multiple variables with the same name.
evaluating proposed solutions, often Now how does that help us with our problem, switching the first and the second
using pencil and paper or other half of the array?
Let’s put the first coin into place, by swapping it with the fifth coin. However, as
artifacts. These sections emphasize Java programmers, we will say that we swap the coins in positions 0 and 4:
int width = 20; Declares an integer variable and initializes it with 20.
int perimeter = 4 * width; The initial value need not be a fixed value. (Of course, width
must have been previously declared.)
String greeting = "Hi!"; This variable has the type String and is initialized with the
Example tables support beginners
string “Hi”. with multiple, concrete examples.
height = 30; Error: The type is missing. This statement is not a declaration
but an assignment of a new value to an existing variable—see These tables point out common
Section 2.2.5.
errors and present another quick
int width = "20"; Error: You cannot initialize a number with the string “20”.
(Note the quotation marks.) reference to the section’s topic.
int width; Declares an integer variable without initializing it. This can be a
cause for errors—see Common Error 2.1 on page 40.
int width, height; Declares two integer variables in a single statement. In this
book, we will declare each variable in a separate statement.
Walkthrough xi
This means “compute the value of width + 10 1 and store that value in the variable
width 2 ” (see Figure 4).
Progressive figures trace code
In Java, it is not a problem that the variable width is used on both sides of the = sym-
bol. Of course, in mathematics, the equation width = width + 10 has no solution.
segments to help students visualize
the program flow. Color is used
1 Compute the value of the right-hand side
consistently to make variables and
width = 30
other elements easily recognizable.
width + 10
40
2 Check condition
for (int counter = 1; counter <= 10; counter++)
{
System.out.println(counter);
counter = 1 }
4 Update counter
for (int counter = 1; counter <= 10; counter++)
{
System.out.println(counter);
counter = 2 }
13. Write a for loop that prints all even numbers between 10 and 20 (inclusive).
14. Write a for loop that computes the sum of the integers from 1 to n.
Practice It Now you can try these exercises at the end of the chapter: R6.4, R6.10, E6.8, E6.12.
Optional science and business
exercises engage students with •• Business E6.17 Currency conversion. Write a program
realistic applications of Java. that first asks the user to type today’s
price for one dollar in Japanese yen,
then reads U.S. dollar values and
converts each to yen. Use 0 as a sentinel.
occur, and what to do about them. have to remember the correct syntax
for every data type. String a.length()
good programming practices, instance variable is set to 80,000 and status is set to MARRIED. Then the getTax method is called.
In lines 31 and 32 of TaxReturn.java, tax1 and tax2 are initialized to 0.
and encourage students to be 29 public double getTax()
30 {
and historical topics on computing—for of search engines, Internet shops, and who know how to work
social networks fill huge buildings with those computers.
Acknowledgments
Many thanks to Bryan Gambrel, Don Fowley, Jenny Welter, Jessy Moor, Jennifer
Lartz, Billy Ray, and Tim Lindner at John Wiley & Sons, and Vickie Piercey at Pub-
lishing Services for their help with this project. An especially deep acknowledgment
and thanks goes to Cindy Johnson for her hard work, sound judgment, and amazing
attention to detail.
I am grateful to Jose Cordova, The University of Louisiana at Monroe, Suzanne
Dietrich, Arizona State University,West Campus, Mike Domaratzki, University of
Manitoba, Guy Helmer, Iowa State University, Peter Lutz, Rochester Institute of
Technology, Carolyn Schauble, Colorado State University, Brent Seales, University
of Kentucky, and Brent Wilson, George Fox University for their excellent contribu-
tions to the supplementary materials.
Many thanks to the individuals who reviewed the manuscript for this edition,
made valuable suggestions, and brought an embarrassingly large number of errors
and omissions to my attention. They include:
Robin Carr, Drexel University
Gerald Cohen, The Richard Stockton College of New Jersey
Aaron Keen, California Polytechnic State University, San Luis Obispo
Aurelia Smith, Columbus State University
Aakash Taneja, The Richard Stockton College of New Jersey
Craig Tanis, University of Tennessee at Chattanooga
Katherine Winters, University of Tennessee at Chattanooga
Every new edition builds on the suggestions and experiences of prior reviewers and
users. I am grateful for the invaluable contributions these individuals have made:
Eric Aaron, Wesleyan University John Bundy, DeVry University Lennie Cooper, Miami Dade College
James Agnew, Anne Arundel Chicago Jose Cordova, University of
Community College Robert P. Burton, Brigham Young Louisiana, Monroe
Tim Andersen, Boise State University Valentino Crespi, California State
University Frank Butt, IBM University, Los Angeles
Ivan Bajic, San Diego State Jerry Cain, Stanford University Jim Cross, Auburn University
University Adam Cannon, Columbia Russell Deaton, University
Greg Ballinger, Miami Dade College University of Arkansas
Ted Bangay, Sheridan Institute Michael Carney, Finger Lakes Geoffrey Decker, Northern Illinois
of Technology Community College University
Ian Barland, Radford University Christopher Cassa, Massachusetts H. E. Dunsmore, Purdue University
George Basham, Franklin University Institute of Technology Robert Duvall, Duke University
Jon Beck, Truman State University Nancy Chase, Gonzaga University Sherif Elfayoumy, University of
Sambit Bhattacharya, Fayetteville Dr. Suchindran S. Chatterjee, North Florida
State University Arizona State University Eman El-Sheikh, University of
Rick Birney, Arizona State Archana Chidanandan, Rose- West Florida
University Hulman Institute of Technology Henry A. Etlinger, Rochester
Paul Bladek, Edmonds Community Vincent Cicirello, The Richard Institute of Technology
College Stockton College of New Jersey John Fendrich, Bradley University
Matt Boutell, Rose-Hulman Teresa Cole, Boise State University David Freer, Miami Dade College
Institute of Technology Deborah Coleman, Rochester John Fulton, Franklin University
Joseph Bowbeer, Vizrea Corporation Institute of Technology David Geary, Sabreware, Inc.
Timothy A. Budd, Oregon State Tina Comston, Franklin University Margaret Geroch, Wheeling Jesuit
University University
xiv Acknowledgments
Ahmad Ghafarian, North Georgia Joan McGrory, Christian Brothers John Santore, Bridgewater State
College & State University University College
Rick Giles, Acadia University Carolyn Miller, North Carolina Javad Shakib, DeVry University
Stacey Grasso, College of San Mateo State University Carolyn Schauble, Colorado State
Jianchao Han, California State Sandeep R. Mitra, State University University
University, Dominguez Hills of New York, Brockport Brent Seales, University of Kentucky
Lisa Hansen, Western New England Teng Moh, San Jose State University Christian Shin, SUNY Geneseo
College Bill Mongan, Drexel University Charlie Shu, Franklin University
Elliotte Harold John Moore, The Citadel Jeffrey Six, University of Delaware
Eileen Head, Binghamton Jose-Arturo Mora-Soto, Jesica Don Slater, Carnegie Mellon
University Rivero-Espinosa, and Julio-Angel University
Cecily Heiner, University of Utah Cano-Romero, University Ken Slonneger, University of Iowa
Guy Helmer, Iowa State University of Madrid Donald Smith, Columbia College
Ed Holden, Rochester Institute Faye Navabi, Arizona State Joslyn A. Smith, Florida
of Technology University International University
Brian Howard, Depauw University Parviz Partow-Navid, California Stephanie Smullen, University of
Lubomir Ivanov, Iona College State University, Los Angeles Tennessee, Chattanooga
Norman Jacobson, University of George Novacky, University Robert Strader, Stephen F. Austin
California, Irvine of Pittsburgh State University
Steven Janke, Colorado College Kevin O’Gorman, California Monica Sweat, Georgia Institute
Curt Jones, Bloomsburg University Polytechnic State University, San of Technology
Luis Obispo Peter Stanchev, Kettering University
Mark Jones, Lock Haven University
of Pennsylvania Michael Olan, Richard Stockton Shannon Tauro, University of
College California, Irvine
Dr. Mustafa Kamal, University of
Central Missouri Mimi Opkins, California State Ron Taylor, Wright State University
University Long Beach
Mugdha Khaladkar, New Jersey Russell Tessier, University of
Institute of Technology Derek Pao, City University of Massachusetts, Amherst
Hong Kong
Gary J. Koehler, University of Jonathan L. Tolstedt, North Dakota
Florida Kevin Parker, Idaho State University State University
Elliot Koffman, Temple University Jim Perry, Ulster County David Vineyard, Kettering
Community College University
Ronald Krawitz, DeVry University
Cornel Pokorny, California Joseph Vybihal, McGill University
Norm Krumpe, Miami University
Polytechnic State University,
Ohio Xiaoming Wei, Iona College
San Luis Obispo
Jim Leone, Rochester Institute Jonathan S. Weissman, Finger Lakes
Roger Priebe, University of Texas,
of Technology Community College
Austin
Kevin Lillis, St. Ambrose University Todd Whittaker, Franklin University
C. Robert Putnam, California State
Darren Lim, Siena College University, Northridge Robert Willhoft, Roberts Wesleyan
Hong Lin, DeVry University College
Kai Qian, Southern Polytechnic
Kathy Liszka, University of Akron State University Lea Wittie, Bucknell University
Hunter Lloyd, Montana State Cyndi Rader, Colorado School David Womack, University of Texas
University of Mines at San Antonio
Youmin Lu, Bloomsburg University Neil Rankin, Worcester Polytechnic David Woolbright, Columbus State
Kuber Maharjan, Purdue University Institute University
College of Technology at Brad Rippe, Fullerton College Tom Wulf, University of Cincinnati
Columbus Pedro I. Rivera Vega, University Catherine Wyman, DeVry
John S. Mallozzi, Iona College of Puerto Rico, Mayaguez University
John Martin, North Dakota State Daniel Rogers, SUNY Brockport Arthur Yanushka, Christian Brothers
University University
Chaman Lal Sabharwal, Missouri
Jeanna Matthews, Clarkson University of Science and Qi Yu, Rochester Institute of
University Technology Technology
Patricia McDermott-Wells, Florida Katherine Salch, Illinois Central Salih Yurttas, Texas A&M University
International University College
Scott McElfresh, Carnegie Mellon
University
CONTENTS
xv
xvi Contents
Removing Matches 348
7 ARRAYS AND ARRAY Choosing Between Array Lists and Arrays 349
LISTS 307 ST5 The Diamond Syntax 352
11.3 Command Line Arguments 533 13.3 The Efficiency of Recursion 604
HT1 Processing Text Files 536 13.4 Permutations 609
WE1 Analyzing Baby Names
© Alex Slobodkin/iStockphoto.
13.5 Mutual Recursion 614
11.4 Exception Handling 540
13.6 Backtracking 620
Throwing Exceptions 540
WE2 Towers of Hanoi
Catching Exceptions 542 © Alex Slobodkin/iStockphoto.
Checked Exceptions 543
Closing Resources 545 14 SORTING AND
Designing Your Own Exception Types 546 SEARCHING 635
ST6 Assertions 549
ST7 The try/finally Statement 549 14.1 Selection Sort 636
11.5 APPLICATION Handling Input Errors 549 14.2 Profiling the Selection Sort
Algorithm 639
14.3 Analyzing the Performance of the
12 OBJECT-ORIENTED
Selection Sort Algorithm 642
DESIGN 565
ST1 Oh, Omega, and Theta 644
12.1 Classes and Their Responsibilities 566 ST2 Insertion Sort 645
Discovering Classes 566 14.4 Merge Sort 647
The CRC Card Method 567
14.5 Analyzing the Merge Sort Algorithm 650
12.2 Relationships Between Classes 569 ST3 The Quicksort Algorithm 652
Dependency 569 14.6 Searching 654
Aggregation 570
Linear Search 654
Inheritance 571
Binary Search 655
HT1 Using CRC Cards and UML Diagrams in
Program Design 572 14.7 PROBLEM SOLVING Estimating the Running
ST1 Attributes and Methods in UML Time of an Algorithm 659
Diagrams 573 Linear Time 659
ST2 Multiplicities 574 Quadratic Time 660
ST3 Aggregation, Association, and The Triangle Pattern 661
Composition 574 Logarithmic Time 662
12.3 APPLICATION Printing an Invoice 575 14.8 Sorting and Searching in the Java
Requirements 575 Library 664
CRC Cards 576 Sorting 664
UML Diagrams 578 Binary Search 664
Method Documentation 579 Comparing Objects 665
Implementation 581 ST4 The Comparator Interface 666
WE1 Simulating an Automatic Teller Machine J81 Comparators with Lambda Expressions 667
© Alex Slobodkin/iStockphoto.
WE1 Enhancing the Insertion Sort Algorithm
© Alex Slobodkin/iSt
13 RECURSION 593
15 THE JAVA COLLECTIONS
13.1 Triangle Numbers 594
FRAMEWORK 677
HT1 Thinking Recursively 599
WE1 Finding Files 15.1 An Overview of the Collections
© Alex Slobodkin/iStockphoto.
13.2 Recursive Helper Methods 602 Framework 678
xx Contents
16.3 Implementing Stacks and Queues 741 18.2 Implementing Generic Types 825
Contents xxi
»Hajoittaisitko sen»?
»Isäni säästi koko ikänsä. Hän oli hyvin ahkera työmies ja kokosi
minulle suuren perinnön», sanoi András kehuvasti. »Ja kai teidän
korkeutenne sen tietää, että minulla on sitä riittävästi»?
»Ja minä sanon sinulle, hävytön mies, että jos minulle tahi
omaisilleni tapahtuu jotakin, on sinun oma kätesi suunnannut iskun
ja valehteleva kielesi suunnitellut teon. Ymmärrän selvästi alhaisen
saidan talonpoikaisluonteesi, joka on valmis vaikka mihin omaksi
hyödykseen…»
KOSTO.
»Muistat kai, äiti, nuo kolme velkakirjaa, jotka olen saanut kreiviltä
hänelle lainaamistani rahoista ja niille juoksevasta korosta»?