The Java Tutorial

Transcription

The Java Tutorial Sixth Editionpsn-gallardo.indb i11/12/14 1:48 PM

The Java SeriesVisit informit.com/thejavaseries for a complete list of available publications.Since 1996, when Addison-Wesley published the first edition of The JavaProgramming Language by Ken Arnold and James Gosling, this series hasbeen the place to go for complete, expert, and definitive information onJava technology. The books in this series provide the detailed informationdevelopers need to build effective, robust, and portable applications andare an indispensable resource for anyone using the Java platform.Make sure to connect with us!informit.com/socialconnectpsn-gallardo.indb ii11/12/14 1:48 PM

The Java Tutorial A Short Course on the BasicsSixth EditionRaymond GallardoScott HommelSowmya KannanJoni GordonSharon Biocca ZakhourUpper Saddle River, NJ Boston Indianapolis San FranciscoNew York Toronto Montreal London Munich Paris MadridCapetown Sydney Tokyo Singapore Mexico Citypsn-gallardo.indb iii11/12/14 1:48 PM

Many of the designations used by manufacturers and sellers to distinguish their products are claimed astrademarks. Where those designations appear in this book, and the publisher was aware of a trademarkclaim, the designations have been printed with initial capital letters or in all capitals.The authors and publisher have taken care in the preparation of this book, but make no expressed orimplied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumedfor incidental or consequential damages in connection with or arising out of the use of the information orprograms contained herein.For information about buying this title in bulk quantities, or for special sales opportunities (which may includeelectronic versions; custom cover designs; and content particular to your business, training goals, marketingfocus, or branding interests), please contact our corporate sales department at corpsales@pearsoned.com or(800) 382-3419.For government sales inquiries, please contact governmentsales@pearsoned.com.For questions about sales outside the U.S., please contact international@pearsoned.com.Visit us on the Web: informit.com/awLibrary of Congress Cataloging-in-Publication DataGallardo, Raymond.The Java tutorial : a short course on the basics / Raymond Gallardo, Scott Hommel, Sowmya Kannan,Joni Gordon, Sharon Biocca Zakhour.—Sixth edition.pages cmPrevious edition: The Java tutorial : a short course on the basics / Sharon Zakhour, Sowmya Kannan,Raymond Gallardo. 2013, which was originally based on The Java tutorial / by Mary Campione.Includes index.ISBN 978-0-13-403408-9 (pbk. : alk. paper)—ISBN 0-13-403408-2 (pbk. : alk. paper)1. Java (Computer program language) I. Title.QA76.73.J38Z35 2015005.13'3—dc232014035811Copyright 2015, Oracle and/or its affiliates. All rights reserved.500 Oracle Parkway, Redwood Shores, CA 94065Printed in the United States of America. This publication is protected by copyright, and permission mustbe obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, ortransmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. Toobtain permission to use material from this work, please submit a written request to Pearson Education,Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax yourrequest to (201) 236-3290.ISBN-13: 978-0-13-403408-9ISBN-10: 0-13-403408-2Text printed in the United States on recycled paper at Edwards Brothers Malloy in Ann Arbor, Michigan.First printing, December 2014psn-gallardo.indb iv11/12/14 1:48 PM

ContentsPrefaceAbout the AuthorsChapter 1Getting StartedThe Java Technology PhenomenonThe Java Programming LanguageThe Java PlatformWhat Can Java Technology Do?How Will Java Technology Change My Life?The “Hello World!” Application“Hello World!” for the NetBeans IDE“Hello World!” for Microsoft Windows“Hello World!” for Solaris and LinuxA Closer Look at the “Hello World!” ApplicationSource Code CommentsThe HelloWorldApp Class DefinitionThe main MethodCommon Problems (and Their Solutions)Compiler ProblemsRuntime ProblemsQuestions and Exercises: Getting gallardo.indb v11/12/14 1:48 PM

viContentsQuestionsExercisesAnswersChapter 2Chapter 3psn-gallardo.indb vi313232Object-Oriented Programming Concepts33What Is an Object?34What Is a Class?36What Is Inheritance?38What Is an Interface?39What Is a Package?40Questions and Exercises: Object-Oriented Programming Concepts 41Questions41Exercises41Answers41Language Basics43Variables44Naming45Primitive Data Types46Arrays51Summary of Variables57Questions and Exercises: Variables57Operators58Assignment, Arithmetic, and Unary Operators59Equality, Relational, and Conditional Operators62Bitwise and Bit Shift Operators65Summary of Operators66Questions and Exercises: Operators67Expressions, Statements, and Blocks68Expressions68Statements70Blocks71Questions and Exercises: Expressions, Statements, and Blocks 71Control Flow Statements72The if-then and if-then-else Statements72The switch Statement74The while and do-while Statements79The for Statement80Branching Statements82Summary of Control Flow Statements85Questions and Exercises: Control Flow Statements8611/12/14 1:48 PM

ContentsChapter 4viiClasses and ObjectsClassesDeclaring ClassesDeclaring Member VariablesDefining MethodsProviding Constructors for Your ClassesPassing Information to a Method or a ConstructorObjectsCreating ObjectsUsing ObjectsMore on ClassesReturning a Value from a MethodUsing the this KeywordControlling Access to Members of a ClassUnderstanding Class MembersInitializing FieldsSummary of Creating and Using Classes and ObjectsQuestions and Exercises: ClassesQuestions and Exercises: ObjectsNested ClassesWhy Use Nested Classes?Static Nested ClassesInner ClassesShadowingSerializationInner Class ExampleLocal and Anonymous ClassesModifiersLocal ClassesAnonymous ClassesLambda ExpressionsWhen to Use Nested Classes, Local Classes,Anonymous Classes, and Lambda ExpressionsQuestions and Exercises: Nested ClassesEnum TypesQuestions and Exercises: Enum TypesChapter 5AnnotationsAnnotations BasicsThe Format of an Annotationpsn-gallardo.indb 16316416411/12/14 1:48 PM

viiiContentsWhere Annotations Can Be UsedDeclaring an Annotation TypePredefined Annotation TypesAnnotation Types Used by the Java LanguageAnnotations That Apply to Other AnnotationsType Annotations and Pluggable Type SystemsRepeating AnnotationsStep 1: Declare a Repeatable Annotation TypeStep 2: Declare the Containing Annotation TypeRetrieving AnnotationsDesign ConsiderationsQuestions and Exercises: AnnotationsQuestionsExerciseAnswersChapter 6Interfaces and InheritanceInterfacesInterfaces in JavaInterfaces as APIsDefining an InterfaceImplementing an InterfaceUsing an Interface as a TypeEvolving InterfacesDefault MethodsSummary of InterfacesQuestions and Exercises: InterfacesInheritanceThe Java Platform Class HierarchyAn Example of InheritanceWhat You Can Do in a SubclassPrivate Members in a SuperclassCasting ObjectsMultiple Inheritance of State, Implementation, and TypeOverriding and Hiding MethodsPolymorphismHiding FieldsUsing the Keyword superObject as a SuperclassWriting Final Classes and MethodsAbstract Methods and Classespsn-gallardo.indb 19819920320620620821221211/12/14 1:48 PM

ContentsixSummary of InheritanceQuestions and Exercises: InheritanceChapter 7GenericsWhy Use Generics?Generic TypesA Simple Box ClassA Generic Version of the Box ClassType Parameter Naming ConventionsInvoking and Instantiating a Generic TypeThe DiamondMultiple Type ParametersParameterized TypesRaw TypesGeneric MethodsBounded Type ParametersMultiple BoundsGeneric Methods and Bounded Type ParametersGenerics, Inheritance, and SubtypesGeneric Classes and SubtypingType InferenceType Inference and Generic MethodsType Inference and Instantiation of Generic ClassesType Inference and Generic Constructorsof Generic and Nongeneric ClassesTarget TypesWildcardsUpper-Bounded WildcardsUnbounded WildcardsLower-Bounded WildcardsWildcards and SubtypingWildcard Capture and Helper MethodsGuidelines for Wildcard UseType ErasureErasure of Generic TypesErasure of Generic MethodsEffects of Type Erasure and Bridge MethodsNonreifiable Types and Varargs MethodsRestrictions on GenericsCannot Instantiate Generic Types with Primitive TypesCannot Create Instances of Type Parameterspsn-gallardo.indb 524624724925225225311/12/14 1:48 PM

xContentsCannot Declare Static Fields Whose Types Are Type ParametersCannot Use Casts or instanceof with Parameterized TypesCannot Create Arrays of Parameterized TypesCannot Create, Catch, or ThrowObjects of Parameterized TypesCannot Overload a Method Where the Formal ParameterTypes of Each Overload Erase to the Same Raw TypeQuestions and Exercises: GenericsAnswersChapter 8PackagesCreating and Using PackagesCreating a PackageNaming a PackageUsing Package MembersManaging Source and Class FilesSummary of Creating and Using PackagesQuestions and Exercises: Creating and Using PackagesQuestionsExercisesAnswersChapter 9Numbers and StringsNumbersThe Numbers ClassesFormatting Numeric Print OutputBeyond Basic ArithmeticAutoboxing and UnboxingSummary of NumbersQuestions and Exercises: NumbersCharactersEscape SequencesStringsCreating StringsString LengthConcatenating StringsCreating Format StringsConverting between Numbers and StringsManipulating Characters in a StringComparing Strings and Portions of StringsThe StringBuilder ClassSummary of Characters and StringsQuestions and Exercises: Characters and Stringspsn-gallardo.indb 29229530030230630711/12/14 1:48 PM

ContentsChapter 10xiExceptionsWhat Is an Exception?The Catch or Specify RequirementThe Three Kinds of ExceptionsBypassing Catch or SpecifyCatching and Handling ExceptionsThe try BlockThe catch BlocksThe finally BlockThe try-with-resources StatementPutting It All TogetherSpecifying the Exceptions Thrown by a MethodHow to Throw ExceptionsThe throw StatementThrowable Class and Its SubclassesError ClassException ClassChained ExceptionsCreating Exception ClassesUnchecked Exceptions: The ControversyAdvantages of ExceptionsAdvantage 1: Separating Error-HandlingCode from “Regular” CodeAdvantage 2: Propagating Errors Up the Call StackAdvantage 3: Grouping and Differentiating Error TypesSummaryQuestions and Exercises: ExceptionsQuestionsExercisesAnswersChapter 11Basic I/O and NIO.2I/O StreamsByte StreamsCharacter StreamsBuffered StreamsScanning and FormattingI/O from the Command LineData StreamsObject StreamsFile I/O (Featuring NIO.2)What Is a Path? (And Other File System Facts)psn-gallardo.indb 234534635235435735935911/12/14 1:48 PM

xiiContentsThe Path ClassFile OperationsChecking a File or DirectoryDeleting a File or DirectoryCopying a File or DirectoryMoving a File or DirectoryManaging Metadata (File and File Store Attributes)Reading, Writing, and Creating FilesRandom Access FilesCreating and Reading DirectoriesLinks, Symbolic or OtherwiseWalking the File TreeFinding FilesWatching a Directory for ChangesOther Useful MethodsLegacy File I/O CodeSummaryQuestions and Exercises: Basic I/OQuestionsExercisesAnswersChapter 12CollectionsIntroduction to CollectionsWhat Is a Collections Framework?Benefits of the Java Collections FrameworkInterfacesThe Collection InterfaceTraversing CollectionsCollection Interface Bulk OperationsCollection Interface Array OperationsThe Set InterfaceThe List InterfaceThe Queue InterfaceThe Deque InterfaceThe Map InterfaceObject OrderingThe SortedSet InterfaceThe SortedMap InterfaceSummary of InterfacesQuestions and Exercises: Interfacespsn-gallardo.indb 4644844945846446746947011/12/14 1:48 PM

ContentsxiiiAggregate OperationsPipelines and StreamsDifferences between Aggregate Operations and IteratorsReductionParallelismSide EffectsQuestions and Exercises: Aggregate OperationsImplementationsSet ImplementationsList ImplementationsMap ImplementationsQueue ImplementationsDeque ImplementationsWrapper ImplementationsConvenience ImplementationsSummary of ImplementationsQuestions and Exercises: ImplementationsAlgorithmsSortingShufflingRoutine Data ManipulationSearchingCompositionFinding Extreme ValuesCustom Collection ImplementationsReasons to Write an ImplementationHow to Write a Custom ImplementationInteroperabilityCompatibilityAPI DesignChapter 13ConcurrencyProcesses and ThreadsProcessesThreadsThread ObjectsDefining and Starting a ThreadPausing Execution with SleepInterruptsJoinsThe SimpleThreads Examplepsn-gallardo.indb 52052052152152252352552511/12/14 1:48 PM

xivContentsSynchronizationThread InterferenceMemory Consistency ErrorsSynchronized MethodsIntrinsic Locks and SynchronizationAtomic AccessLivenessDeadlockStarvation and LivelockGuarded BlocksImmutable ObjectsA Synchronized Class ExampleA Strategy for Defining Immutable ObjectsHigh-Level Concurrency ObjectsLock ObjectsExecutorsConcurrent CollectionsAtomic VariablesConcurrent Random NumbersQuestions and Exercises: ConcurrencyQuestionExercisesAnswersChapter 14psn-gallardo.indb 6552553554555555555556Regular Expressions557Introduction558What Are Regular Expressions?558How Are Regular Expressions Represented in This Package? 558Test Harness559String Literals560Metacharacters561Character Classes562Simple Classes562Predefined Character Classes566Quantifiers568Zero-Length Matches569Capturing Groups and Character Classes with Quantifiers572Differences among Greedy, Reluctant,and Possessive Quantifiers573Capturing Groups574Numbering574Backreferences57511/12/14 1:48 PM

ContentsxvBoundary MatchersMethods of the Pattern ClassCreating a Pattern with FlagsEmbedded Flag ExpressionsUsing the matches(String,CharSequence) MethodUsing the split(String) MethodOther Utility MethodsPattern Method Equivalents in java.lang.StringMethods of the Matcher ClassIndex MethodsStudy MethodsReplacement MethodsUsing the start and end MethodsUsing the matches and lookingAt MethodsUsing replaceFirst(String) and replaceAll(String)Using appendReplacement(StringBuffer,String)and appendTail(StringBuffer)Matcher Method Equivalents in java.lang.StringMethods of the PatternSyntaxException ClassUnicode SupportMatching a Specific Code PointUnicode Character PropertiesQuestions and Exercises: Regular ExpressionsQuestionsExerciseAnswersChapter 15The Platform EnvironmentConfiguration UtilitiesPropertiesCommand-Line ArgumentsEnvironment VariablesOther Configuration UtilitiesSystem UtilitiesCommand-Line I/O ObjectsSystem PropertiesThe Security ManagerMiscellaneous Methods in SystemPATH and CLASSPATHUpdate the PATH Environment Variable (Microsoft Windows)Update the PATH Variable (Solaris, Linux, and OS X)Checking the CLASSPATH Variable (All Platforms)psn-gallardo.indb 360460760860960961161211/12/14 1:48 PM

xviContentsQuestions and Exercises: The Platform EnvironmentQuestionExerciseAnswersChapter 16Packaging Programs in JAR FilesUsing JAR Files: The BasicsCreating a JAR FileViewing the Contents of a JAR FileExtracting the Contents of a JAR FileUpdating a JAR FileRunning JAR-Packaged SoftwareWorking with Manifest Files: The BasicsUnderstanding the Default ManifestModifying a Manifest FileSetting an Application’s Entry PointAdding Classes to the JAR File’s Class PathSetting Package Version InformationSealing Packages within a JAR FileEnhancing Security with Manifest AttributesSigning and Verifying JAR FilesUnderstanding Signing and VerificationSigning JAR FilesVerifying Signed JAR FilesUsing JAR-Related APIsAn Example: The JarRunner ApplicationThe JarClassLoader ClassThe JarRunner ClassQuestions and Exercises: Packaging Programs in JAR FilesQuestionsAnswersChapter 17Java Web StartAdditional ReferencesDeveloping a Java Web Start ApplicationCreating the Top JPanel ClassCreating the ApplicationBenefits of Separating Core Functionalityfrom the Final Deployment MechanismRetrieving ResourcesDeploying a Java Web Start ApplicationSetting Up a Web Serverpsn-gallardo.indb 5065165265265365365611/12/14 1:48 PM

ContentsxviiDisplaying a Customized Loading Progress IndicatorDeveloping a Customized Loading Progress IndicatorSpecifying a Customized Loading ProgressIndicator for a Java Web Start ApplicationRunning a Java Web Start ApplicationRunning a Java Web Start Application from a BrowserRunning a Java Web Start Applicationfrom the Java Cache ViewerRunning a Java Web Start Application from the DesktopJava Web Start and SecurityDynamic Downloading of HTTPS CertificatesCommon Java Web Start Problems“My Browser Shows the Java Network LaunchProtocol (JNLP) File for My Application as Plain Text”“When I Try to Launch My JNLP File, I Get the Following Error”Questions and Exercises: Java Web StartQuestionsExercisesAnswersChapter 18psn-gallardo.indb 64Applets665Getting Started with Applets666Defining an Applet Subclass666Methods for Milestones667Life Cycle of an Applet668Applet’s Execution Environment670Developing an Applet670Deploying an Applet673Doing More with Applets677Finding and Loading Data Files677Defining and Using Applet Parameters678Displaying Short Status Strings681Displaying Documents in the Browser682Invoking JavaScript Code from an Applet683Invoking Applet Methods from JavaScript Code686Handling Initialization Status with Event Handlers689Manipulating DOM of Applet’s Web Page691Displaying a Customized Loading Progress Indicator693Writing Diagnostics to Standard Output and Error Streams 698Developing Draggable Applets698Communicating with Other Applets70111/12/14 1:48 PM

xviiiContentsWorking with a Server-Side ApplicationWhat Applets Can and Cannot DoSolving Common Applet Problems“My Applet Does Not Display”“The Java Console Log Displaysjava.lang.ClassNotFoundException”“I Was Able to Build the Code Once, but Now the BuildFails Even Though There Are No Compilation Errors”“When I Try to Load a Web Page That Has an Applet,My Browser Redirects Me to www.java.com withoutAny Warning”“I Fixed Some Bugs and Rebuilt My Applet’sSource Code. When I Reload the Applet’s Web Page,My Fixes Are Not Showing Up”Questions and Exercises: AppletsQuestionsExercisesAnswersChapter 19Doing More with Java Rich Internet ApplicationsSetting Trusted Arguments and Secure PropertiesSystem PropertiesJNLP APIAccessing the Client Using the JNLP APICookiesTypes of CookiesCookie Support in RIAsAccessing CookiesCustomizing the Loading ExperienceSecurity in Rich Internet ApplicationsGuidelines for Securing RIAsFollow Secure Coding GuidelinesTest with the Latest Version of the JREInclude Manifest AttributesUse a Signed JNLP FileSign and Time Stamp JAR FilesUse the HTTPS ProtocolAvoid Local RIAsQuestions and Exercises: Doing More withRich Internet ApplicationsQuestionspsn-gallardo.indb 672611/12/14 1:48 PM

ContentsxixExerciseAnswersChapter 20Deployment in DepthUser Acceptance of RIAsDeployment ToolkitLocation of Deployment Toolkit ScriptDeploying an AppletDeploying a Java Web Start ApplicationChecking the Client JRE Software VersionJava Network Launch ProtocolStructure of the JNLP FileDeployment Best PracticesReducing the Download TimeAvoiding Unnecessary Update ChecksEnsuring the Presence of the JRE SoftwareQuestions and Exercises: Deployment in DepthQuestionsExerciseAnswersChapter 21Date-TimeDate-Time OverviewDate-Time Design PrinciplesClearFluentImmutableExtensibleThe Date-Time PackagesMethod Naming ConventionsStandard CalendarOverviewDayOfWeek and Month EnumsDayOfWeekMonthDate ClassesLocalDateYearMonthMonthDayYearDate and Time ClassesLocalTimepsn-gallardo.indb 6276276376376476476476411/12/14 1:48 PM

xxContentsLocalDateTimeTime Zone and Offset ClassesZoneId and ZoneOffsetThe Date-Time ClassesInstant ClassParsing and FormattingParsingFormattingThe Temporal PackageTemporal and TemporalAccessorChronoField and IsoFieldsChronoUnitTemporal AdjusterTemporal QueryPeriod and DurationDurationChronoUnitPeriodClockNon-ISO Date ConversionConverting to a Non-ISO-Based DateConverting to an ISO-Based DateLegacy Date-Time CodeInteroperability with Legacy CodeMapping java.util Date and TimeFunctionality to java.timeDate and Time FormattingSummaryQuestions and Exercises: Date-TimeQuestionsExercisesAnswersChapter 22AppendixIntroduction to JavaFXPreparation for Java Programming Language CertificationProgrammer Level I ExamSection 1: Java BasicsSection 2: Working with Java Data TypesSection 3: Using Operators and Decision ConstructsSection 4: Creating and Using ArraysSection 5: Using Loop Constructspsn-gallardo.indb 579579579679779779811/12/14 1:48 PM

ContentsxxiSection 6: Working with Methods and EncapsulationSection 7: Working with InheritanceSection 8: Handling ExceptionsSection 9: Working with Selected Classesfrom the Java APIProgrammer Level II ExamJava SE 8 Upgrade ExamSection 1: Lambda ExpressionsSection 2: Using Built-In Lambda TypesSection 3: Filtering Collections with LambdasSection 4: Collection Operations with LambdaSection 5: Parallel StreamsSection 6: Lambda CookbookSection 7: Method EnhancementsSection 8: Use Java SE 8 Date/Time APISection 9: JavaScript on Java with NashornIndexpsn-gallardo.indb 711/12/14 1:48 PM

This page intentionally left blank

PrefaceSince the acquisition of Sun Microsystems by Oracle Corporation in early 2010, ithas been an exciting time for the Java language. As evidenced by the activities ofthe Java Community Process program, the Java language continues to evolve. Thepublication of this sixth edition of The Java Tutorial reflects version 8 of the JavaPlatform Standard Edition (Java SE) and references the Application ProgrammingInterface (API) of that release.This edition introduces new features added to the platform since the publicationof the fifth edition (under release 7): Lambda expressions enable you to treat functionality as a method argumentor code as data. Lambda expressions let you express instances of singlemethod interfaces (referred to as functional interfaces) more compactly. Seethe new section in Chapter 4, “Lambda Expressions.” Type annotations can be used in conjunction with pluggable type systems forimproved type checking, and repeating annotations enable the applicationof the same annotation to a declaration or type use. See the new sections inChapter 5, “Type Annotations and Pluggable Type Systems” and “RepeatingAnnotations.” Default methods are methods in an interface that have an implementation.They enable new functionality to be added to the interfaces of libraries andensure binary compatibility with code written for older versions of thoseinterfaces. See the new section in Chapter 6, “Default Methods.”xxiiipsn-gallardo.indb xxiii11/12/14 1:48 PM

xxivPreface Aggregate operations enable you to perform functional-style operations onstreams of elements—in particular, bulk operations on collections such assequential or parallel map-reduce transformations. See the new section inChapter 12, “Aggregate Operations.” Improvements have been added that focus on limiting attackers from usingmalicious applets and rich Internet applications (RIAs). See the followingnew and updated sections: Chapter 16, “Packaging Programs in JAR Files” Chapter 19, “Security in Rich Internet Applications” and “Guidelines forSecuring Rich Internet Applications”Chapter 20, “Deployment Best Practices” Date-Time APIs enable you to represent dates and times and manipulatedate and time values. They support the International Organization for Standardization (ISO) calendar system as well as other commonly used globalcalendars. See the new Chapter 21. If you plan to take one of the Java SE 8 certification exams, this book can help.The appendix, “Preparation for Java Programming Language Certification,” liststhe three exams that are available, detailing the items covered by each exam, crossreferenced to places in the book where you can find more information about eachtopic. Note that this is one source, among others, that you will want to use to prepare for your exam. Check the online tutorial for the latest certification objectivesand cross-references to sections of the tutorial.All of the material has been thoroughly reviewed by members of Oracle Javaengineering to ensure that the information is accurate and up to date. This bookis based on the online tutorial hosted on Oracle Corporation’s web site at the following URL:http://docs.oracle.com/javase/tutorial/The information in this book, often referred to as “the core tutorial,” is required bymost beginning to intermediate programmers. Once you have mastered this material, you can explore the rest of the Java platform documentation on the web site.If you are interested in developing sophisticated RIAs, check out JavaFX, the Javagraphical user interface (GUI) toolkit, which comes with the Java SE DevelopmentKit (JDK). To learn more, see Chapter 22, “Introduction to JavaFX.”As always, our goal is to create an easy-to-read, practical programmers’ guide tohelp you learn how to use the rich environment provided by Java to build applications, applets, and components. Go forth and program!psn-gallardo.indb xxiv11/12/14 1:48 PM

PrefacexxvWho Should Read This Book?This book is geared toward both novice and experienced programmers: New programmers can benefit most from reading the book from beginning toend, including the step-by-step instructions for compiling and running yourfirst program in Chapter 1, “Getting Started.” Programmers experienced with procedural languages such as C may want tostart with the material on object-oriented concepts and features of the Javaprogramming language. Experienced programmers may want to jump feet first into the more advanced topics, such as generics, concurrency, or deployment.This book contains information to address the learning needs of programmers withvarious levels of experience.How to Use This BookThis book is designed so you can read it straight through or skip around from topicto topic. The information is presented in a logical order, and forward references areavoided wherever possible.The examples in this book are compiled against the JDK 8 release. You need todownload this release (or later) in order to compile and run most examples.Some material referenced in this book is available online—for example, the downloadable examples, the solutions to the questions and exercises, the JDK 8 guides,and the API specification.You will see footnotes like the al/java/generics/examples/BoxDemo.javaThe Java documentation home on the Oracle web site is at the following location:http://docs.oracle.com/javase/To locate the footnoted files online, prepend the URL for the Java documentation /lang/Class.htmlpsn-gallardo.indb xxv11/12/14 1:48 PM

java/generics/examples/BoxDemo.javaThe Java Tutorials are also available in two eBook formats:mobi eBook files for KindleePub eBook files for iPad, Nook, and other devices that support the ePub format Each eBook contains a single trail that is equivalent to several related chapters inthis book. You can download the eBooks via the link “In Book Form” on the homepage for the Java ndex.htmlWe welcome feedback on this edition. To contact us, please see the tutorial feedback knowledgmentsThis book would not be what it is without the Oracle Java engineering team whotirelessly reviews the technical content of our writing. For this edition of the book,we especially want to thank Alan Bateman, Alex Buckley, Stephen Colebourne,Joe Darcy, Jeff Dinkins, Mike Duigou, Brian Goetz, Andy Herrick, Stuart Marks,Thomas Ng, Roger Riggs, Leif Samuelsson, and Daniel Smith.Illustrators Jordan Douglas and Dawn Tyler created our professional graphicsquickly and efficiently.Editors Janet Blowney, Deborah Owens, and Susan Shepard provided carefuland thorough copyedits of our JDK 8 work.Thanks for the support of our team: Devika Gollapudi, Ram Goyal, and AlexeyZhebel.Last but not least, thanks for the support of our management: Sowmya Kannan,Sophia Mikulinsky, Alan Sommerer, and Barbara Ramsey.psn-gallardo.indb xxvi11/12/14 1:48 PM

About the AuthorsRaymond Gallardo is a senior technical writer at Oracle Corporation. His previous engagements include college instructor, technical writer for IBM, and bicyclecourier. He obtained his BSc in computer science and English from the Universityof Toronto and MA in creative writing from the City College of New York.Scott Hom

The Java tutorial : a short course on the basics / Raymond Gallardo, Scott Hommel, Sowmya Kannan, Joni Gordon, Sharon Biocca Zakhour.— Sixth edition. pages cm Previous edition: The Java tutorial : a short course on the basics / Sharon Zakhour, Sowmya Kannan, Raymond Gallardo. 2013, which was originally based on The Java tutorial / by Mary .