1. Trang chủ
  2. » Khoa Học Tự Nhiên

The java programming language, 4th edition (2005)

1,3K 205 1

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 1.326
Dung lượng 4,94 MB

Nội dung

Key changes in this edition include New chapters on generics, enums, and annotations, the most powerful new language features introduced in J2SE 5.0 Changes to classes and methods throug

Trang 1

By Ken Arnold, James Gosling, David Holmes

Publisher: Addison Wesley Professional Pub Date: August 17, 2005

ISBN: 0-321-34980-6 Pages: 928

The authors systematically cover most classes in Java's main packages, java.lang.*,

java.util, and java.io, presenting in-depth explanations of why these classes work as they

do, with informative examples Several new chapters and major sections have been added, and every chapter has been updated to reflect today's best practices for building robust, efficient, and maintainable Java software.

Key changes in this edition include

New chapters on generics, enums, and annotations, the most powerful new language features introduced in J2SE 5.0

Changes to classes and methods throughout to reflect the addition of generics

Major new sections on assertions and regular expressions

Coverage of all the new language features, from autoboxing and variable argument methods to the enhanced for-loop and covariant return types

Coverage of key new classes, such as Formatter and Scanner

The Java™ Programming Language, Fourth Edition, is the definitive tutorial

introduction to the Java language and essential libraries and an indispensable reference for all programmers, including those with extensive experience It brings together insights you can only get from the creators of Java: insights that will help you write software of

exceptional quality.

Trang 2

By Ken Arnold, James Gosling, David Holmes

Publisher: Addison Wesley Professional Pub Date: August 17, 2005

ISBN: 0-321-34980-6 Pages: 928

Trang 8

Section 25.9 Utility Subpackages

Section 25.10 javax.* Standard Extensions

Section 25.11 javax.accessibility Accessibility for GUIs

Section 25.12 javax.naming Directory and Naming Services Section 25.13 javax.sound Sound Manipulation

Section 25.14 javax.swing Swing GUI Components

Section 25.15 org.omg.CORBA CORBA APIs

Appendix A Application Evolution

Section A.1 Language, Library, and Virtual Machine Versions Section A.2 Dealing with Multiple Dialects

Section A.3 Generics: Reification, Erasure, and Raw Types Appendix B Useful Tables

Trang 9

Further Reading

Java Platform Topics

Object-Oriented Design

Multithreaded Programming Generics

Regular Expressions

General Programming Techniques Related Languages

Software Engineering

Visual Design & GUI Design Colophon

Trang 10

Sun Microsystems, Inc (SUN) hereby grants to you a fully-paid,nonexclusive, nontransferable, perpetual, worldwide limitedlicense (without the right to sublicense) under SUN's intellectualproperty rights that are essential to practice this specification.This license allows and is limited to the creation and distribution

of clean room implementations of this specification that: (i)

include a complete implementation of the current version of thisspecification without subsetting or supersetting; (ii) implementall the interfaces and functionality of the standard java.*

materials; and (vi) do not include any SUN binary materialswithout an appropriate and separate license from SUN

Sun, Sun Microsystems, Sun Microsystems Computer

Corporation, the Sun logo, the Sun Microsystems Computer

Trang 11

Compliant, JavaOS, JavaBeans and HotJava are trademarks orregistered trademarks of Sun Microsystems, Inc UNIX® is aregistered trademark in the United States and other countries,exclusively licensed through X/Open Company, Ltd Apple andDylan are trademarks of Apple Computer, Inc All other productnames mentioned herein are the trademarks of their respectiveowners

THIS PUBLICATION IS PROVIDED "AS IS" WITHOUT WARRANTY

OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUTNOT LIMITED TO, THE IMPLIED WARRANTIES OF

MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, ORNON-INFRINGEMENT

THIS PUBLICATION COULD INCLUDE TECHNICAL

INACCURACIES OR TYPOGRAPHICAL ERRORS CHANGES AREPERIODICALLY ADDED TO THE INFORMATION HEREIN; THESECHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THEPUBLICATION SUN MICROSYSTEMS, INC MAY MAKE

IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S)

AND/OR THE PROGRAM(S) DESCRIBED IN THIS PUBLICATION

AT ANY TIME

Many of the designations used by manufacturers and sellers todistinguish their products are claimed as trademarks Wherethose designations appear in this book, and the publisher wasaware of a trademark claim, the designations have been printedwith initial capital letters or in all capitals

The authors and publisher have taken care in the preparation ofthis book, but make no expressed or implied warranty of anykind and assume no responsibility for errors or omissions Noliability is assumed for incidental or consequential damages inconnection with or arising out of the use of the information orprograms contained herein

The publisher offers excellent discounts on this book when

Trang 13

Dedication

This book is dedicated to the Java team From whose hard workand vision A mighty oak has grown

To SusanK.A.

To Judy and KateJ.A.G.

To Lee, Taylor, and CaitlinD.H.

Trang 15

The Java™ Language Specification, Third Edition

Doug Lea

Concurrent Programming in Java™, Second Edition: Design Principles and Patterns

Rosanna Lee, Scott Seligman

JNDI API Tutorial and Reference: Building Directory-Enabled Java™ Applications

Trang 16

Java™ Look and Feel Design Guidelines: Advanced Topics

Kathy Walrath, Mary Campione, Alison Huml, Sharon Zakhour

The JFC Swing Tutorial, Second Edition: A Guide to Constructing GUIs

Seth White, Maydene Fisher, Rick Cattell, Graham Hamilton,Mark Hapner

JDBC™ API Tutorial and Reference, Second Edition: Universal Data Access for the Java™ 2 Platform

Trang 17

Java™ Message Service API Tutorial and Reference: Messaging for the J2EE™ Platform

Inderjeet Singh, Beth Stearns, Mark Johnson, Enterprise Team

Designing Enterprise Applications with the Java™ 2 Platform, Enterprise Edition

Vlada Matena, Sanjeev Krishnan, Linda DeMichiel, Beth Stearns

Based Development for the J2EE™ Platform

Applying Enterprise JavaBeans™, Second Edition: Component-Bill Shannon, Mark Hapner, Vlada Matena, James Davidson,Eduardo Pelegri-Llopart, Larry Cable, Enterprise Team

Java™ 2 Platform, Enterprise Edition: Platform and Component Specifications

Rahul Sharma, Beth Stearns, Tony Ng

J2EE™ Connector Architecture and Enterprise Application

Integration

Trang 18

Beautiful buildings are more than scientific They are true organisms, spiritually conceived; works of art, using the

content providers Users of the Internet and World Wide Webbenefit from access to secure, platform-independent

applications that can come from anywhere on the Internet

Software developers who create applications in the Java

programming language benefit by developing code only once,with no need to "port" their applications to every software andhardware platform

For many, the language was known first as a tool to create

applets for the World Wide Web An applet is a mini-application

that runs inside a Web page An applet can perform tasks andinteract with users on their browser pages without using

resources from the Web server after being downloaded Someapplets may, of course, talk with the server to do their job, butthat's their business

The Java programming language is indeed valuable for

distributed network environments like the Web However, it

purpose programming language suitable for building a variety ofapplications that either do not depend on network features orwant them for different reasons The ability to execute

goes well beyond this domain to provide a powerful general-downloaded code on remote hosts in a secure manner is a

Trang 19

Other groups use it as a general-purpose programming

language for projects in which machine independence is lessimportant Ease of programming and safety features help youquickly produce working code Some common programmingerrors never occur because of features like garbage collectionand type-safe references Support for multithreading caters tomodern network-based and graphical user interfacebased

applications that must attend to multiple tasks simultaneously,and the mechanisms of exception handling ease the task ofdealing with error conditions While the built-in tools are

powerful, it is a simple language in which programmers canquickly become proficient

Trang 20

This book teaches the Java programming language to peoplewho are familiar with basic programming concepts It explainsthe language without being arduously formal or complete Thisbook is not an introduction to object-oriented programming,although some issues are covered to establish a common

terminology Other books in this series and much online

documentation focus on applets, graphical interfaces, Web sites,databases, components, and other specific kinds of

the main packages (java.lang, java.util, java.io) as implemented

in the J2SE™ Development Kit 5.0 (more commonly known as JDK

5.0, or in the older nomenclature JDK 1.5.0)

If you have already read the third edition of this book, you willfind some major changes, both in the language and the book,since the 1.3 release that the third edition covered There arenew chapters on generics, enums, and annotationsthe majornew language features introduced in the 5.0 releaseand majornew sections on assertions and regular expressions Some

existing material has been restructured to accommodate otherchanges and to improve the general flow of the textsuch as

introducing the new boxing and unboxing conversions But

every single chapter has been updated in some way, whether it

is a new language feature like variable argument methods; thenew enhanced for loop construct; a new class such as Formatter

for formatting text output; or changes to classes and methodscaused by the addition of generics (such as the collections

Trang 21

The Java programming language shares many features common

to most programming languages in use today The languageshould look familiar to C and C++ programmers because it wasdesigned with C and C++ constructs where the languages aresimilar That said, this book is neither a comparative analysisnor a "bridge" tutorialno knowledge of C or C++ is assumed.C++ programmers, especially, may be as hindered by what

on which examples through the rest of the book are built

Chapters 2 through 6 cover the object-oriented core features ofthe language, namely, class declarations that define

components of a program, and objects manufactured according

to class definitions Chapter 2Classes and Objectsdescribes the

basis of the language: classes Chapter 3Extending

Classesdescribes how an existing class can be extended, or

subclassed, to create a new class with additional data and

behavior Chapter 4Interfacesdescribes how to declare interface

types that are abstract descriptions of behavior that providemaximum flexibility for class designers and implementors

Trang 22

Variablesdescribes the tokens of the language from which

statements are constructed, the types defined by the languageand their allowed values, and the variables that store data inobjects, arrays, or locally within methods Chapter 8Primitives

as Typesexplores the relationship between the primitive types

and objects of their corresponding wrapper classes, and howboxing and unboxing can transparently convert between them

Chapter 16Reflectiondescribes the runtime type introspection

Trang 23

involved in dealing with the evolution of applications and theJava platform, and the impact this has on some of the new

Trang 24

programming with threads, software design, and other topics.

Trang 25

All the code examples in the text have been compiled and run

on the latest version of the language available at the time thebook was written, which was the JDK 1.5.0_02 product version.Only supported features are covereddeprecated types,

methods, and fields are ignored except when unavoidable orwhen knowledge of the past is necessary to understand thepresent We have also covered issues beyond writing programsthat simply compile Part of learning a language is to learn touse it well For this reason, we have tried to show principles ofgood programming style and design

In a few places we refer to online documentation Developmentenvironments provide a way to automatically generate

documentation (usually HTML documents) for a compiled classfrom its documentation comments This documentation is

normally viewed with a Web browser

Trang 26

Once again we are indebted to a group of people who took timeout from their hectic schedules (and even their own books!) togive us the benefit of their experiences in making this the bestedition yet Of course, some of those people were also

responsible for the huge volume of work required for us to

catch up with all the new language and library features, but wewon't hold that against them Much

On the reviewing side our thanks go first to Yoshiki Shibata.Yoshiki produced the Japanese translation of the third editionand in the process single-handedly discovered at least 85% ofthe errata To get the fourth edition as errata free as possible

we knew we needed Yoshiki onboard as a reviewer very early

on Yoshiki became our front-line reviewer and nothing went outfor general review without his nod of approval Not only did heprovide valuable corrections and feedback on the new material,

he also pointed out several areas where there had been

language changes that we hadn't been aware of!

Brian Goetz also rates special thanks not only for reviewing theentire edition, but also for re-reviewing various sections thattook several iterations to get right The turnaround times forthese re-reviews were very tight and we much appreciate

Brian's time at that critical stage

The remainder of the core reviewing team consisted of BethStearns and Kevin Davis, who were able to stay for the longhaul, while Bob Withers, Herb Jellinek, Ken Louden, Rich

Wardwell, and Kevin Hammond provided valuable feedback onthe earlier portions of the text Thank you all very much

We'd also like to thank Tim Peierls for supplying the chess

example used in the enum chapter; and Keith Lea and MartinBuchholz for valuable reviews of the generics materialthanks!

Trang 27

chapter (and the related part of the appendix) was the hardestpart of this edition Armed initially only with a draft of the third

edition of the Java Language Specification, it was never going to

be easy to fathom the depths of the new type system, so webrought in the big guns: Neal Gafter, Josh Bloch, Gilad Bracha,and Peter von der Ahé were all instrumental in educating usabout generics, and for that we thank them Peter's in-depthreview of the generics chapter was especially valuable and

warrants an additional thank you Of course, the teachers

cannot be blamed for the shortcomings of the student, so anyerrors or omissions in the description of generics are the soleresponsibility of the authors (We'd like to thank Phil Wadler forcatching two such omissions in the generics coverage just prior

to publication.)

We'd also like to thank the following technical experts for theirassistance in specific areas: Doug Lea for reviewing the Javamemory model material and providing assistance with

concurrent collections; Brian Goetz for checking the overview ofthe concurrent collections (in addition to everything else); Mike

"MadBot" McCloskey for the review of, and assistance with, theuse of the Scanner class and the associated regular expressionusage; and Jeremy Manson for trying to explain the

unfathomable relationship between finalization and the memorymodel

Rosemary Simpson seems to always manage to be around when

we need her It's starting to get difficult to find a creative way

to say how much we appreciate her indexing, but I'm sure we'llhave one by the fifth edition

On the production side, the path to the fourth edition was a

somewhat changeable one Mike Hendrickson held the reins

when the fourth edition was conceived, then handed the reins

to Ann Sellers Ann, with assistance from Ebony Haight, saw thefourth edition through its early gestation, then handed the reins

to Greg Doench Greg, with assistance from Noreen Regina,

Trang 28

And thanks as well to Kathy Kerby, Ben Littauer, and ArianaLittauer for being a valuable source of borrowed computrons.It's always nice to have neighbors from whom you can borrow acup of cycles

Last, but by no means least, thank you to our families for

putting up with the trials and tribulations of authorship onceagain

Trang 29

The third edition required yet more reviews and work, and thehelper list is equally critical Lisa Friendly continued her

attempts to keep the project in line; someday we will cooperatebetter The set of reviewers included new faces and old friends,all helpful: Joshua Bloch, Joseph Bowbeer, Gilad Bracha, KeithEdwards, Joshua Engel, Rich Gillam, Peter Haggar, Cay

Horstmann, Alexander Kuzmin, Doug Lea, Keith Lea, Tim

Lindholm, David Mendenhall, Andrew M Morgan, Ray Ortigas,Brian Preston, Mark Schuldenfrei, Peter Sparago, Guy Steele,Antoine Trux, and our Russian compatriots Leonid Arbouzov,Valery Shakurov, Viatcheslav Rybalov, Eugene Latkin, DmitriKhukhro, Konstantin Anisimov, Alexei Kaigorodov, Oleg Oleinik,and Maxim Sokolnikov Several people let us bend their ears tofigure out how to approach things better: Peter Jones, Robert

W Scheifler, Susan Snyder, Guy Steele, Jimmy Torres, and AnnWollrath Helen Leary made the logistics work smoothly, as

Trang 30

The cast of characters for this second edition is much like thefirst

Series Editor Lisa Friendly continued to be doggedly supportiveand attentive The set of reviewers was smaller, overlapping,and certainly as helpful and thorough Overall reviews by SteveByrne, Tom Cargill, Mary Dageforde, Tim Lindholm, and RobMurray were critical to clarity Brian Beck, Peter Jones, DougLea, Bryan O'Sullivan, Sue Palmer, Rosanna Lee, Lori Park, MarkReinhold, Roger Riggs, Ann Wollrath, and Ken Zadek contributedfocused reviews of important parts Guy Steele's support wasongoing and warm Rosemary Simpson's extensive and

intensive efforts to make a useful index are deeply appreciated.Carla Carlson and Helen Leary gave logistic support that kept allthe wheels on the tracks instead of in the ditch Gerry Wienerprovided the Tibetan word on page 550, and we also had help

on this from Craig Preston and Takao Miyatani All who

submitted errata and suggestions from the first edition werehelpful

For some inexplicable reason we left the friendly folks of

Addison-Wesley off the original acknowledgmentsluckily, most

of them were present again for this edition A merged list forboth editions includes Kate Duffy, Rosa Gonzales, Mike

Hendrickson, Marina Lang, Shannon Patti, Marty Rabinowitz,Sarah Weaver, and Pamela Yee Others did much that we areblissfully unaware of, but for which we are nonetheless

abidingly grateful

The revision was additionally aided by Josh Bloch, Joe Fialli,

Jimmy Torres, Benjamin Renaud, Mark Reinhold, Jen Volpe, andAnn Wollrath

And Peet's Coffee and Tea continued its supporting role as

Trang 31

purveyor to the caffeine-consuming connoisseur.

Trang 32

No technical book-writing endeavor is an island unto itself, andours was more like a continent Many people contributed

writing advice

technical help, excellent reviews, useful information, and book-Contributing editor Henry McGilton of Trilithon Software playedthe role of "chief editorial firefighter" to help make this bookpossible Series editor Lisa Friendly contributed dogged

perseverance and support

A veritable multitude of reviewers took time out of their

otherwise busy lives to read, edit, advise, revise, and deletematerial, all in the name of making this a better book KevinCoyle performed one of the most detailed editorial reviews at alllevels Karen Bennet, Mike Burati, Patricia Giencke, Steve

Gilliard, Bill Joy, Rosanna Lee, Jon Madison, Brian O'Neill, SuePalmer, Stephen Perelgut, R Anders Schneiderman, Susan Sim,Bob Sproull, Guy Steele, Arthur van Hoff, Jim Waldo, Greg

Wilson, and Ann Wollrath provided in-depth review Geoff

Arnold, Tom Cargill, Chris Darke, Pat Finnegan, Mick Jordan,Doug Lea, Randall Murray, Roger Riggs, Jimmy Torres, Arthurvan Hoff, and Frank Yellin contributed useful comments and

technical information at critical junctures

Alka Deshpande, Sharon Flank, Nassim Fotouhi, Betsy Halstead,Kee Hinckley, Dr K Kalyanasundaram, Patrick Martin, Paul

Romagna, Susan Snyder, and Nicole Yankelovich collaborated tomake possible the five words of non-ISO-Latin-1 text on pages

164 and 550 Jim Arnold provided research help on the properspelling, usage, and etymology of "smoog" and "moorge." EdMooney helped with the document preparation Herb and JoyKaiser were our Croatian language consultants Cookie

Callahan, Robert E Pierce, and Rita Tavilla provided the supportnecessary to keep this project going at many moments when it

Trang 33

Thanks to Kim Polese for supplying us the capsule summary ofwhy the Java programming language is important to computerusers as well as programmers

Support and advice were provided at critical moments by SusanJones, Bob Sproull, Jim Waldo, and Ann Wollrath And we thankour families, who, besides their loving support, would at timesdrag us out to play when we should have been working, forwhich we are deeply grateful

And thanks to the folks at Peet's Coffee and Tea, who kept usbuzzed on the best Java on the planet

Any errors or shortcomings that remain in this bookdespite thecombined efforts of these myriadsare completely the

responsibility of the authors

Results! Why, man, I have gotten a lot of results I know several thousand things that won't work.

Thomas Edison

Calvin and Hobbes quote (page 39) reprinted by permission ofUniversal Press Syndicate

"Mail Myself to You," (page 183) words and music by WoodyGuthrie trO 1962 (renewed), 1963 (renewed) by Ludlow Music,Inc New York, NY Used by permission

Trang 34

See Europe! Ten Countries in Seventeen Days!

Sign in a travel agent's window

This chapter is a whirlwind tour of the Java™ programminglanguage that gets you started writing code quickly We brieflycover the main points of the language, without slowing youdown with full-blown detail Subsequent chapters contain

detailed discussions of specific features

Trang 35

In the Java programming language, programs are built from

classes From a class definition, you can create any number of objects that are known as instances of that class Think of a

operate on the fields to manipulate the state Statements definethe behavior of the classes: they can assign values to fields andother variables, evaluate arithmetic expressions, invoke

program into bytecodes, the "machine language" for the Java

virtual machine (more on this later in this chapter) Details ofediting and compiling source vary from system to systemconsultyour system manuals for specific information On the system weuse most oftenthe Java™ 2 Platform, Standard Edition (J2SE™)

Trang 36

member: a method called main Class members appear betweencurly braces { and } following the class name

The main method is a special method: the main method of a class,

if declared exactly as shown, is executed when you run the

class as an application When run, a main method can createobjects, evaluate expressions, invoke other methods, and doanything else needed to define an application's behavior

The main method is declared publicso that anyone can invoke it(in this case the Java virtual machine)and static, meaning thatthe method belongs to the class and is not associated with aparticular instance of the class

Trang 37

value and so has no return type

Following the method name is the parameter list for the

methoda sequence of zero or more pairs of types and names,separated by commas and enclosed in parentheses ( and ) The

main method's only parameter is an array of String objects,

referred to by the name args Arrays of objects are denoted bythe square brackets [] that follow the type name In this case

args will contain the program's arguments from the commandline with which it was invoked Arrays and strings are coveredlater in this chapter The meaning of args for the main method isdescribed in Chapter 2 on page 73

Exercise 1.1: Enter, compile, and run HelloWorld on your

system

Trang 38

Exercise 1.2: Try changing parts of HelloWorld and see whaterrors you might get.

Trang 40

}

}

This example declares a Fibonacci class that, like HelloWorld, has a

main method The first two lines of main are statements declaring

two local variables: lo and hi In this program hi is the currentterm in the series and lo is the previous term Local variablesare declared within a block of code, such as a method body, incontrast to fields that are declared as members of a class Every

variable must have a type that precedes its name when the

variable is declared The variables lo and hi are of type intbit signed integers with values in the range 231 through 2311

, 32-The Java programming language has built-in "primitive" datatypes to support integer, floating-point, boolean, and charactervalues These primitive types hold numeric data that is

understood directly, as opposed to object types defined by

programmers The type of every variable must be defined

explicitly The primitive data types are:

boolean either TRue or false

char 16-bit Unicode UTF -16 character (unsigned)

Ngày đăng: 25/03/2019, 16:45

TỪ KHÓA LIÊN QUAN

w