Java In A Nutshell, 6th Edition (covers Java 8) - R-5

Transcription

6th Understand basic techniques used inobject-oriented design Examine concurrency and memory, andhow they’re intertwined Work with Java collections and handlecommon data formats Delve into Java’s latest I/O APIs, includingasynchronous channels Use Nashorn to execute JavaScript on theJava Virtual Machine Become familiar with development tools inOpenJDKDavid Flanagan, senior stafffrontend software engineer atMozilla, has written several booksfor O’Reilly, including JavaScript:The Definitive Guide, jQuery PocketReference, The Ruby ProgrammingLanguage, and previous editions ofJava in a Nutshell.Twitter: @oreillymediafacebook.com/oreillyPROGR AMMING/JAVAUS 59.99Benjamin J. Evans is thecofounder and TechnologyFellow of jClarity, a startup thatdelivers performance tools to helpdevelopment & ops teams. He is aJava Champion; JavaOne Rockstar;coauthor of The Well-GroundedJava Developer (Manning); anda regular public speaker on theJava platform, performance,concurrency, and related topics.on 8Explore generics, enumerations,annotations, and lambda expressionsva —Kevlin Henneyconsultant, author, speaker,editor of 97 Things EveryProgrammer Should KnowJavaJavain a NutshellA DESKTOP QUICK REFERENCECAN 62.99ISBN: 978-1-449-37082-4itiLearn object-oriented programming, usingbasic Java syntax”Ja rsGet up to speed on language details,including Java 8 changesreferences, this latestedition is still thesimplest and mostdefinitive way to cutthrough to the answersyou need.Evans &Flanagan veThe second section is a reference to core conceptsand APIs that shows you how to perform realprogramming work in the Java environment.In a world of blogged“opinionsand javadoc’dSIXTHEDITIONJava in a NutshellThe latest edition of Java in a Nutshell is designed tohelp experienced Java programmers get the most outof Java 7 and 8, but it’s also a learning path for newdevelopers. Chock full of examples that demonstratehow to take complete advantage of modern Java APIsand development best practices, the first section ofthis thoroughly updated book provides a fast-paced,no-fluff introduction to the Java programming languageand the core runtime aspects of the Java platform.EdCoJava in a NutshellBenjamin J. Evans & David Flanagan

6th Understand basic techniques used inobject-oriented design Examine concurrency and memory, andhow they’re intertwined Work with Java collections and handlecommon data formats Delve into Java’s latest I/O APIs, includingasynchronous channels Use Nashorn to execute JavaScript on theJava Virtual Machine Become familiar with development tools inOpenJDKDavid Flanagan, senior stafffrontend software engineer atMozilla, has written several booksfor O’Reilly, including JavaScript:The Definitive Guide, jQuery PocketReference, The Ruby ProgrammingLanguage, and previous editions ofJava in a Nutshell.Twitter: @oreillymediafacebook.com/oreillyPROGR AMMING/JAVAUS 59.99Benjamin J. Evans is thecofounder and TechnologyFellow of jClarity, a startup thatdelivers performance tools to helpdevelopment & ops teams. He is aJava Champion; JavaOne Rockstar;coauthor of The Well-GroundedJava Developer (Manning); anda regular public speaker on theJava platform, performance,concurrency, and related topics.on 8Explore generics, enumerations,annotations, and lambda expressionsva —Kevlin Henneyconsultant, author, speaker,editor of 97 Things EveryProgrammer Should KnowJavaJavain a NutshellA DESKTOP QUICK REFERENCECAN 62.99ISBN: 978-1-449-37082-4itiLearn object-oriented programming, usingbasic Java syntax”Ja rsGet up to speed on language details,including Java 8 changesreferences, this latestedition is still thesimplest and mostdefinitive way to cutthrough to the answersyou need.Evans &Flanagan veThe second section is a reference to core conceptsand APIs that shows you how to perform realprogramming work in the Java environment.In a world of blogged“opinionsand javadoc’dSIXTHEDITIONJava in a NutshellThe latest edition of Java in a Nutshell is designed tohelp experienced Java programmers get the most outof Java 7 and 8, but it’s also a learning path for newdevelopers. Chock full of examples that demonstratehow to take complete advantage of modern Java APIsand development best practices, the first section ofthis thoroughly updated book provides a fast-paced,no-fluff introduction to the Java programming languageand the core runtime aspects of the Java platform.EdCoJava in a NutshellBenjamin J. Evans & David Flanagan

JAVAIN A NUTSHELLSixth EditionBenjamin J. Evans and David Flanagan

Java in a Nutshellby Benjamin J. Evans and David FlanaganCopyright 2015 Benjamin J. Evans and David Flanagan. All rights reserved.Printed in the United States of America.Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.O’Reilly books may be purchased for educational, business, or sales promotional use. Onlineeditions are also available for most titles (http://www.safaribooksonline.com). For more infor‐mation, contact our corporate/institutional sales department: 800-998-9938 or corpo‐rate@oreilly.com.Editors: Mike Loukides andMeghan BlanchetteProduction Editor: Matthew HackerCopyeditor: Charles RoumeliotisProofreader: Jasmine KwitynIndexer: Ellen Troutman ZaigInterior Designer: David FutatoCover Designer: Ellie VolckhausenIllustrator: Rebecca DemarestFebruary 1996: First EditionMay 1997: Second EditionNovember 1999: Third EditionMarch 2002: Fourth EditionMarch 2005: Fifth EditionOctober 2014: Sixth EditionRevision History for the Sixth Edition2014-10-10:First ReleaseSee http://oreilly.com/catalog/errata.csp?isbn 9781449370824 for release details.Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trade‐marks of O’Reilly Media, Inc. Java in a Nutshell, the cover image of a Javan tiger, and relatedtrade dress are trademarks of O’Reilly Media, Inc.Many of the designations used by manufacturers and sellers to distinguish their products areclaimed as trademarks. Where those designations appear in this book, and O’Reilly Media,Inc., was aware of a trademark claim, the designations have been printed in caps or initialcaps.While the publisher and the authors have used good faith efforts to ensure that the informa‐tion and instructions contained in this work are accurate, the publisher and the authors dis‐claim all responsibility for errors or omissions, including without limitation responsibility fordamages resulting from the use of or reliance on this work. Use of the information andinstructions contained in this work is at your own risk. If any code samples or other technol‐ogy this work contains or describes is subject to open source licenses or the intellectual prop‐erty rights of others, it is your responsibility to ensure that your use thereof complies withsuch licenses and/or rights.978-1-449-37082-4[LSI]

Table of ContentsForeword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiPreface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiiiPart I.Introducing Java1. Introduction to the Java Environment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3The Language, the JVM, and the EcosystemA Brief History of Java and the JVMThe Lifecycle of a Java ProgramJava SecurityComparing Java to Other LanguagesAnswering Some Criticisms of Java3791111132. Java Syntax from the Ground Up. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Java Programs from the Top DownLexical StructurePrimitive Data TypesExpressions and OperatorsStatementsMethodsIntroduction to Classes and ObjectsArraysReference TypesPackages and the Java NamespaceJava File StructureDefining and Running Java ProgramsSummary18182230466672778488939495vii

3. Object-Oriented Programming in Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97Overview of ClassesFields and MethodsCreating and Initializing ObjectsSubclasses and InheritanceData Hiding and EncapsulationAbstract Classes and MethodsModifier Summary971001061101211281324. The Java Type System. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135InterfacesJava GenericsEnums and AnnotationsNested TypesLambda ExpressionsConclusion1361421511551711745. Introduction to Object-Oriented Design in Java. . . . . . . . . . . . . . . . . . . . . . . 177Java ValuesImportant Methods of java.lang.ObjectAspects of Object-Oriented DesignExceptions and Exception HandlingSafe Java Programming1771781831931956. Java’s Approach to Memory and Concurrency. . . . . . . . . . . . . . . . . . . . . . . . . 197Basic Concepts of Java Memory ManagementHow the JVM Optimizes Garbage CollectionThe HotSpot HeapFinalizationJava’s Support for ConcurrencyWorking with ThreadsSummaryPart II.197201203206208218219Working with the Java Platform7. Programming and Documentation Conventions. . . . . . . . . . . . . . . . . . . . . . . 223Naming and Capitalization ConventionsPractical NamingJava Documentation CommentsConventions for Portable Programsviii Table of Contents223225226235

8. Working with Java Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239Introduction to Collections APILambda Expressions in the Java CollectionsConclusion2392582669. Handling Common Data Formats. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267TextNumbers and MathJava 8 Date and TimeConclusion26727528028710. File Handling and I/O. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289Classic Java I/OModern Java I/ONIO Channels and BuffersAsync I/ONetworking28929529830130411. Classloading, Reflection, and Method Handles. . . . . . . . . . . . . . . . . . . . . . . . 311Class Files, Class Objects, and MetadataPhases of ClassloadingSecure Programming and ClassloadingApplied ClassloadingReflectionDynamic ProxiesMethod Handles31131331531732032532612. Nashorn. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331Introduction to NashornExecuting JavaScript with NashornNashorn and javax.scriptAdvanced NashornConclusion33133234034234713. Platform Tools and Profiles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349Command-Line ToolsVisualVMJava 8 ProfilesConclusion349362367372Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373Table of Contents ix

ForewordIn the winter of 2013–14, the United Kingdom was battered by an extended series ofexceptionally violent winter storms. These storms uncovered shipwrecks and someamazing archaeology, especially in my home county of Cornwall. One of the moststriking discoveries was a petrified forest, dating back to the end of the last Ice Age,now covered by the sea and sand. Before the sea claimed it again, I was luckyenough to visit it at very low tide and spend some hours exploring it.Among the remaining roots and tree stumps and beds of organic matter on theirway to becoming peat, I could still make out pieces of trunk branch and bark. As Iwandered along the shore with the tide coming in, I came across a single hemi‐sphere from a nut—from a tree that no longer grows in these latitudes. Despitebeing embedded in the organic layer, the shape of the nutshell and its ability to sur‐vive over long periods of time was still unmistakable.In working on this new edition of David’s classic text, I hope to have embodied thespirit of that prehistoric tree. If I have preserved the tenacious form and, crucially,the feel of Java in a Nutshell, while bringing it to the attention of a new generation ofdevelopers, with the important parts emphasized, then I shall be well satisfied.—Ben Evans, 2014xi

PrefaceThis book is a desktop Java reference, designed to sit faithfully by your keyboardwhile you program. Part I of the book is a fast-paced, “no-fluff ” introduction to theJava programming language and the core runtime aspects of the Java platform.Part II is a reference section that blends elucidation of core concepts with examplesof important core APIs. The book covers Java 8, but we recognize that some shopsmay not have adopted it yet—so where possible we call out if a feature was intro‐duced in Java 8 (and sometimes Java 7). We use Java 8 syntax throughout, includingusing lambda expressions in code that would previously have used a trivial anony‐mous nested class.Changes in the Sixth EditionThe fifth edition of this book covers Java 5, whereas this edition covers Java 8. Thelanguage, and the working environment of the programmer, have both changedconsiderably since the last edition was published nearly a decade ago. This new edi‐tion has, accordingly, changed a vast amount as well. One very important aspect isthat this book does not attempt to be as complete a description of the core platformAPIs as was possible in earlier editions.For one thing, the sheer size of the core APIs render this utterly impractical for aprinted book. A more compelling reason is the continued rise of fast, always-onInternet. The amount of Java programmers who regularly work without Internetaccess is now vanishingly small. The proper place for detailed reference API docs isonline, not printed out.Accordingly, the reference section, which occupied two-thirds of the fifth edition, isgone. In the space we’ve recovered, we have tried to update the concept of what itmeans to be a “Nutshell” guide. The modern Java developer needs to know morethan just syntax and APIs. As the Java environment has matured, such topics asconcurrency, object-oriented design, memory, and the Java type system have allgained in importance—even among mainstream developers.xiii

In this edition, we have tried to reflect this changed world, and have largely aban‐doned the historical approach of earlier editions. In particular, the exhaustiveattempt to detail exactly which version of Java particular features arrived with hasmostly been abandoned—only the most recent versions of Java are likely to be ofinterest to the majority of Java developers.Contents of This BookThe first six chapters of this book document the Java language and the Java platform—they should all be considered essential reading. The book is biased toward theOracle/OpenJDK (Open Java Development Kit) implementation of Java, but notgreatly so—developers working with other Java environments will still find plenty tooccupy them. Part I includes:Chapter 1, IntroductionThis chapter is an overview of the Java language and the Java platform. Itexplains the important features and benefits of Java, including the lifecycle of aJava program. We also touch on Java security and answer some criticisms ofJava.Chapter 2, Java Syntax from the Ground UpThis chapter explains the details of the Java programming language, includingthe Java 8 language changes. It is a long and detailed chapter that does notassume substantial programming experience. Experienced Java programmerscan use it as a language reference. Programmers with substantial experiencewith languages such as C and C should be able to pick up Java syntaxquickly by reading this chapter; beginning programmers with only a modestamount of experience should be able to learn Java programming by studyingthis chapter carefully, although it is best read in conjunction with a second text(such as O’Reilly’s Head First Java by Bert Bates and Kathy Sierra).Chapter 3, Object-Oriented Programming in JavaThis chapter describes how the basic Java syntax documented in Chapter 2 isused to write simple object-oriented programs using classes and objects in Java.The chapter assumes no prior experience with OO programming. It can beused as a tutorial by new programmers or as a reference by experienced Javaprogrammers.Chapter 4, The Java Type SystemThis chapter builds on the basic description of object-oriented programming inJava, and introduces the other aspects of Java’s type system, such as generictypes, enumerated types, and annotations. With this more complete picture, wecan discuss the biggest change in Java 8—the arrival of lambda expressions.Chapter 5, Introduction to Object-Oriented Design in JavaThis chapter is an overview of some basic techniques used in the design ofsound object-oriented programs, and briefly touches on the topic of design pat‐terns and their use in software engineering.xiv Preface

Chapter 6, Java’s Approach to Memory and ConcurrencyThis chapter explains how the Java Virtual Machine manages memory onbehalf of the programmer, and how memory and visibility is intimatelyentwined with Java’s support for concurrent programming and threads.These first six chapters teach you the Java language and get you up and runningwith the most important concepts of the Java platform. The second part of the bookis all about how to get real programming work done in the Java environment. Itcontains plenty of examples and is designed to complement the cookbook approachfound in some other texts. Part II includes:Chapter 7, Programming and Documentation ConventionsThis chapter documents important and widely adopted Java programming con‐ventions. It also explains how you can make your Java code self-documentingby including specially formatted documentation comments.Chapter 8, Working with Java Collections and ArraysThis chapter introduces Java’s standard collections libraries. These contain datastructures that are vital to the functioning of virtually every Java program—such as List, Map, and Set. The new Stream abstraction and the relationshipbetween lambda expressions and the collections is explained in detail.Chapter 9, Handling Common Data FormatsThis chapter discusses how to use Java to work effectively with very commondata formats, such as text, numbers, and temporal (date and time) information.Chapter 10, File Handling and I/OThis chapter covers several different approaches to file access—from the moreclassic approach found in older versions of Java, through to more modern andeven asynchronous styles. The chapter concludes with a short introduction tonetworking with the core Java platform APIs.Chapter 11, Classloading, Reflection, and Method HandlesThis chapter introduces the subtle art of metaprogramming in Java—first intro‐ducing the concept of metadata about Java types, then turning to the subject ofclassloading and how Java’s security model is linked to the dynamic loading oftypes. The chapter concludes with some applications of classloading and therelatively new feature of method handles.Chapter 12, NashornThis chapter describes Nashorn, an implementation of JavaScript running atopthe Java Virtual Machine. Nashorn ships with Java 8, and provides an alterna‐tive to other JavaScript implementations. Toward the end of the chapter, wediscuss Avatar.js—a server-side technology compatible with Node.Chapter 13, Platform Tools and ProfilesOracle’s JDK (as well as OpenJDK) includes a number of useful Javadevelopment tools, most notably the Java interpreter and the Java compiler.This chapter documents those tools. The second part of the chapter coversPreface xv

Compact Profiles—a new feature in Java 8 allowing cut-down Java RuntimeEnvironments (JREs) with a significantly reduced footprint.Related BooksO’Reilly publishes an entire series of books on Java programming, including severalcompanion books to this one. The companion books are:Learning Java by Pat Niemeyer and Daniel LeuckThis book is a comprehensive tutorial introduction to Java, and includes topicssuch as XML and client-side Java programming.Java 8 Lambdas by Richard WarburtonThis book documents the new Java 8 feature of lambda expressions in detail,and introduces concepts of functional programming that may be unfamiliar toJava developers coming from earlier versions.Head First Java by Bert Bates and Kathy SierraThis book uses a unique approach to teaching Java. Developers who think visu‐ally often find it a great accompaniment to a traditional Java book.You can find a complete list of Java books from O’Reilly at http://java.oreilly.com/.Examples OnlineThe examples in this book are available online and can be downloaded from thehome page for the book at http://www.oreilly.com/catalog/javanut6. You may alsowant to visit this site for any important notes or errata that have been publishedthere.Conventions Used in This BookWe use the following formatting conventions in this book:ItalicUsed for emphasis and to signify the first use of a term. Italic is also used forcommands, email addresses, websites, FTP sites, and file and directory names.Constant WidthUsed for all Java code as well as for anything that you would type literally whenprogramming, including keywords, data types, constants, method names, vari‐ables, class names, and interface names.Constant Width ItalicUsed for the names of function arguments and generally as a placeholder toindicate an item that should be replaced with an actual value in your program.Sometimes used to refer to a conceptual section or line of code as instatement.xvi Preface

This element signifies a tip or suggestion.This element signifies a general note.This element indicates a warning or caution.Request for CommentsYou can send comments, fixes and suggestions directly to the authors by using theemail address javanut6@gmail.com.Please address comments and questions concerning this book to the publisher:O’Reilly Media, Inc.1005 Gravenstein Highway NorthSebastopol, CA 95472800-998-9938 (in the United States or Canada)707-829-0515 (international or local)707-829-0104 (fax)We have a web page for this book, where we list errata, examples, and any additionalinformation. You can access this page at http://bit.ly/java nutshell 6e.To comment or ask technical questions about this book, send email to bookques‐tions@oreilly.com.For more information about our books, courses, conferences, and news, see ourwebsite at http://www.oreilly.com.Find us on Facebook: http://facebook.com/oreillyFollow us on Twitter: http://twitter.com/oreillymediaWatch us on YouTube: http://www.youtube.com/oreillymediaPreface xvii

Safari Books OnlineSafari Books Online is an on-demand digitallibrary that delivers expert content in both bookand video form from the world’s leading authorsin technology and business.Technology professionals, software developers, web designers, and business andcreative professionals use Safari Books Online as their primary resource forresearch, problem solving, learning, and certification training.Safari Books Online offers a range of plans and pricing for enterprise, government,education, and individuals.Members have access to thousands of books, training videos, and prepublicationmanuscripts in one fully searchable database from publishers like O’Reilly Media,Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams,Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, MorganKaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, NewRiders, McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. Formore information about Safari Books Online, please visit us online.AcknowledgmentsMeghan Blanchette was the editor of the sixth edition—her attention to detail andcheerful, grounded approach helped provide extra momentum at very usefulmoments throughout the book’s development.Special thanks are due to Jim Gough, Richard Warburton, John Oliver, Trisha Gee,and Stephen Colebourne.As always, Martijn Verburg has been a good friend, business partner, soundingboard, and font of useful advice.Ben, in particular, would like to thank everyone who has given him feedback andhelped him improve as a writer. Caroline Kvitka, Victor Grazi, Tori Weildt, andSimon Ritter deserve special mention for their helpful suggestions. If he’s failed totake all of their excellent advice in this text the blame is, of course, his.xviii Preface

IIntroducing JavaPart I is an introduction to the Java language and the Java platform. These chaptersprovide enough information for you to get started using Java right away:Chapter 1, IntroductionChapter 2, Java Syntax from the Ground UpChapter 3, Object-Oriented Programming in JavaChapter 4, The Java Type SystemChapter 5, Introduction to Object-Oriented Design in JavaChapter 6, Java’s Approach to Memory and Concurrency

Introduction to the JavaEnvironmentWelcome to Java 8. We may be welcoming you back. You may be coming to this eco‐system from another language, or maybe this is your first programming language.Whatever road you may have traveled to get here: welcome. We’re glad you’vearrived.Java is a powerful, general-purpose programming environment. It is one of the mostwidely used programming languages in the world, and has been exceptionally suc‐cessful in business and enterprise computing.In this chapter, we’ll set the scene by describing the Java language (which program‐mers write their applications in), the Java Virtual Machine (which executes thoseapplications), and the Java ecosystem (which provides a lot of the value of the pro‐gramming environment to development teams).We’ll briefly cover the history of the Java language and virtual machine, before mov‐ing on to discuss the lifecycle of a Java program and clear up some common ques‐tions about the differences between Java and other environments.At the end of the chapter, we’ll introduce Java security, and discuss some of theaspects of Java which relate to secure coding.The Language, the JVM, and the EcosystemThe Java programming environment has been around since the late 1990s. It com‐prises the Java language, and the supporting runtime, otherwise known as the JavaVirtual Machine (JVM).At the time that Java was initially developed, this split was considered novel, butrecent trends in software development have made it more commonplace. Notably,3Introduction1

Microsoft’s .NET environment, announced a few years after Java, adopted a verysimilar approach to platform architecture.One important difference between Microsoft’s .NET platform and Java is that Javawas always conceived as a relatively open ecosystem of multiple vendors. Through‐out Java’s history, these vendors both cooperated and competed on aspects of Javatechnology.One of the main reasons for the success of Java is that this ecosystem is a standar‐dized environment. This means there are specifications for the technologies thatcomprise the environment. These standards give the developer and consumer confi‐dence that the technology will be compatible with other components, even if theycome from a different technology vendor.The current steward of Java is Oracle Corporation (who acquired SunMicrosystems, the originator of Java). Other corporations, such as Red Hat, IBM,Hewlett-Packard, SAP, Apple, and Fujitsu are also heavily involved in producingimplementations of standardized Java technologies.There is also an open source version of Java, called OpenJDK, which many of thesecompanies collaborate on.Java actually comprises several different, but related environments and specifica‐tions—Java Mobile Edition (Java ME), Java Standard Edition (Java SE), and JavaEnterprise Edition (Java EE). In this book, we’ll only cover Java SE, version 8.We will have more to say about standardization later, so let’s move on to discuss theJava language and JVM as separate, but related concepts.What Is the Java Language?Java programs are written as source code in the Java language. This is a humanreadable programming language, which is class based and object oriented. It isconsidered to be relatively easy to read and write (if occasionally a bit verbose).Java is intended to be easy to learn and to teach. It builds on industry experiencewith languages like C and tries to remove complex features as well as preserving“what works” from previous programming languages.Overall, Java is intended to provide a stable, solid base for companies to developbusiness-critical applications.As a programming language, it has a relatively conservative design and a slow rateof change. These properties are a conscious attempt to serve the goal of protectingthe investment that businesses have made in Java technology.The language has undergone gradual revision (but no complete rewrites) since itsinception in 1996. This does mean that some of Java’s original design choices, whichwere expedient in the late 1990s, are still affecting the language today—see Chapters2 and 3 for more details.4 Chapter 1: Introduction to the Java Environment

The Java language is governed by the Java Language Specification (JLS), whichdefines how a conforming implementation must behave.What Is the JVM?The JVM is a program that provides the runtime environment necessary for Javaprograms to execute. Java programs cannot run unless there is a JVM available forthe appropriate hardware and OS platform we wish to execute on.Fortunately, the JVM has been ported to run on a large number of environments—anything from a set-top box or Blu-ray player to a huge mainframe will probablyhave a JVM available for it.Java programs are typically started by a command line, such as:java arguments program name This brings up the JVM as an operating system process that provides the Java run‐time environment, and then executes our program in the context of the freshlystarted (and empty) virtual machine.It is important to understand that when the JVM takes in a Java program for execu‐tion, the program is not provided as Java language source code. Instead, the Javalanguage source must have been converted (or compiled) into a form known as Javabytecode. Java bytecode must be supplied to the JVM in a format called class files—which always have a .class extension.The JVM is an interpreter for the bytecode form of the program—it steps throughone bytecode instruct

Mozilla, has written several books for O'Reilly, including JavaScript: The Definitive Guide, jQuery Pocket Reference, The Ruby Programming Language, and previous editions of Java in a Nutshell. av J a in a Nutshell Benjamin J. Evans & David Flanagan av J a A DESKTOP QUICK REFERENCE n a 8 Java in a Nutshell Evans & Flanagan SIXTH EDITION