`
`'"" r':w‘兔e・、‘
`
`Jav Progranimin
`轰巍样篡幼 age
`Th元rd Ed树on
`
`f』卜‘“卜肠‘尸人、眨七““『仁‘"'“仁“乡么
`
`胜民“卜」‘
`
` 井立”.洲沪浦九.过叭甘.及确厂吐议.,”招“睡.艘盖均抽目,妇俘・幼氏赵”%端蟹翔感抽足训祖叭洲良资映“闲如拍萝护留“‘抓卜}摊侧“蕊访蹄自’片‘""'“朴“”科“典口‘西住‘门口为”
`
`JAVA
`
`Fall Line Patents, LLC Ex. 2001
`U.S. Patent No. 9,454,748
`
`
`
`The Java"
`Programming Language
`Third Edition
`
`Page - 02 of 11
`
`
`The Javar"
`Programming Language
`Third Edition
`
`Ken Arnold
`James Gosling
`David Holmes
`
`4
`
`Iry
`A DDISON-WESLEY
`'Boston • San FranQisco • New siork • inrwito•Nion4441
`Madt
`London. Munich• Pat
`ftican• Sidney Tokyo • Singapore • Me yiivsn Cu)
`
`Page - 03 of 11
`
`
`The JavaIM Series
`Lisa Friendly, Series Editor
`Tim Lindholm, Technical Editor
`Kern.Arnold, Technical Editor of The lid' Technology Series
`Jim Inner% Technical Editor of The Java Series, Enterprise Edition
`Tim Lindhohn and Prank Yellin
`Ken Arnold, James Gosling, David Holmes
`The javarm Virtual Machine Specification, Second Edition
`The ./aveinf Programming Language, Third Edition
`Viada IvIatena and 'Beth Stearns
`Joshua Bloch
`Applying Enterprise JavaBeansTM:
`EffectiveJavaThl Progranuning Language Guide
`Component-Based Development for the J2EEN Platform
`Greg Bellella, James Coaling, Ben Bresgot, Peter Dibble,
`Roger Riggs, Anrero Taivalsaati, Mark VandenBrink
`Steve Purr, David Hardin, Mark Turnbull
`Programming Wireless Deviees.with the Javarm 2
`The Beal-Time Specification for Juveirm
`Platform, Micro Edition
`Mary Campione, Kathy Wairath, Alison Huml
`Ruhul Sharma, Beth Stearns, Torty.Ng
`The Javan' Tutorial, Third Edition:
`12EK" Ctittneetor AtrhitectUre and Enter
`A Short Coarse on the Basics
`Integration
`Mary Campione, Kathy Wairath, Alison Hund,Tutorial Teara
` Kevin Rushfotth, and Michael Deering
`Henry Scv
`The Javan' Tutorial Continued:
`The Java 3Div API Specification, SecondEdition
`The Rest of the IDKIm
`Kathy Walrath, Mary Campion.
`Patrick Chan
`ThellirSwing Tutorial:
`The J0y0TM Developers Almanat.2000
`A Guide to Constructing GCiIs
`Patrick Chan, Rosanna Lee
`Seth White. Maydene fisher, Rick .Cattell, Graham Hamilton,
`The Javrerm Clan Libraries, Second .Edition, ''blame
`Mark Hardier
`java.applet, java.awt, java.beans
`JDBCtm API Tutorial and Reference, Second Edition:
`Patrick Chan, Rosanna Lee
`Wiwi-sal Data Access for the Javan' 2 Platform
`The Java) f Class Libraries Poster; Sixth Edition,.Purt
`Steve Wilson, Jett' Kesselmun
`Patrick Chan, Rosanna Lee
`Java TM PlutfOrnt. Performance:
`The Javdtm Class Libraries Poster; Sixth Edition, Part 2
`Strategies and Tactics
`Patriek Chan, Rosanna Lee, Doug Kramer
`The JavalM Class Libraries, Second Edition, RAMC I:
`jaw*. javahme, javarnath, javana, java.text. java.tali
`Patrick Chan. Rosanna Lee, Doug Kramer
`The Java- Class Libraries. Second Edition, Volume I:
`Supplethent for the Jtwam 2 Platform,
`Standtorl Edition, vl .2
`Kirk Chen, Li Gong
`Programming Open Service Gateways with JavaTsi
`Embedded Server
`Zhiqun Chen
`Java Canirm Technology for Smart Curds:
`Architecture and Programmer's Guide
`Li Gong
`Inside 'avant 2 Platform Security:.
`Architecture, API Design, and Implementation
`James Gosling, Bill Joy, Guy Steele, Gilod Bracha
`The Javam Language Specification, Second Edition
`Jonni Kanerva
`The itiva'rm. TAQ
`Doug Lea
`Concurrent Programming in .lavaTM, Second Edition:
`Design Principles and Pamirs
`.Rosatma Lee, Scott Seligman
`JNDJ API littorial and Refire/toe:
`Building Directory-Enabled 'ovum Applications
`Sheng Liang
`The Javam Native Interface:
`Programmer 's Guide and Specification
`
`The Javtirm Series, Enterprise Edition
`Rick Cattell, Jim Timor& Enterprise Partners
`J2EEN Technology in .Prectice:
`Building Business Applications with the Jetsam 2 Pitafpnit
`Enterprise Edition
`Patrick Chan, Rosanna Lee
`The JovaTm Class Libraries Poster,Enterprise Edition;::
`version 1.2
`Nicholas Kassem, Enterprise Team
`Designing Enterprise APplications with the Javan'
`Platform, Enterprise Edition
`Bill Shannon, Mark Raper, Vlada Matenadarries, .
`Davidson, EdUardo Pelegri-Llopart, Larry Cable;
`Enterprise Team
`Jawing 2 PladOrm, Enterprise Edition:
`Platform and Component Specifications
`
`http://ww ntjuvaseries.com
`
` Application
`
`The ihdim Technology Series
`
`Eric Freeman, Susanne Hupfer, l(en.Arnotd
`JavaSpaceem Principles, Patterns, andrractice
`Jim Waldatinini Technology Team
`The Jinirm Specifications, Second Edition,
`edited by Ken Arnold
`
`Page - 04 of 11
`
`
`.1`
`
`Copyright U2000 by Sun Microsystems, Inc., 901 San Antonio Road, Palo Alto, CA 94303, USA.
`All rights reserved.
`
`Duke logo TM designed by Joe Palrang.
`Sun Ivlicrosystems, Inc. has intellectual property rights Mating to implernentations of the technol-
`ogy described in this publication. In particular, and without limitation, these intellectual property
`rights may include one or more U.S, patents, foreign patents, or pending applications. Sun, Sun
`Microsystems, the Sun logo, and id Sun, Java, Jini, and SOlaris based trademarks and logos are
`trademarks or registered trademarks of Sun Microsystems, itIC„in the United States and other coun-
`tries. UNIX is a registered trademark in the United States and other countries, exclusively licensed
`through X/Open Company, Lid.
`THIS PUBLICATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
`EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMftbD TO, THE IMPLIED WAR-
`RANTIES OP MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE, OR NON-
`INFRINGEMENT.
`THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHI-
`CAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN;
`THESE CHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THE PUBLICATION.
`SUN MICROSYSTEMS, INC. MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE
`PRODUCT(S) AND/OR THE PROG.RAM(S) DESCRIBED IN THIS PUBLICATION AT ANY
`TIME.
`The publisher offers discounts on this book when ordered in quantity for special sales. For more
`information, please contact:
`Pearson Education Corporate Sales Division
`201 W. 103rd Street
`Indianapolis, IN 46290
`(800) 428-5331
`corpsales@pearsoned.com
`
`Text printed on recycled and acid-free paper.
`ISBN 0201704331
`4 5 6 7 8 9 CRS 04 03 02 01
`4th Printing Octob►r 2001
`
`Page - 05 of 11
`
`
`CLASSES AND OBJEcrs
`
`63
`
`2.10 Native Methods
`if you need to write a program that will use some existing code that isn't written
`in the Java programming language, or if you need to manipulate some hardware
`directly, you can write native methods. A native method lets you implement a
`method .that can be invoked from the Java programming language but is written in
`a "native" language. usually C or C++. Native methods are declared using the
`native modifier. Because the method is implemented in another language, the
`method body is specified as a semicolon. For example, here is a declaration of a
`native method that queries the operating system for the CPU identifier of the host
`machine..
`public native int getCPUID ;
`Other than being implemented in native code, native methods are like all other
`methods: they can be overloaded. overridden, final, stati c, synchroni zed,
`public, protected or private. A native method cannot. however, be declared
`abstract. nor strlctfp.
`If you use a native method, all portability and safety of the code are lost. You
`cannot, for instance, use a native method in almost any code you expect to down-
`load and run from across a network connection tan applet, for example). The
`downloading system may or may not be of the same architecture. and even if it is,
`it might not trust your system well enough to run arbitrary native code.
`Native methods are implemented using an API provided by the people who
`wrote the virtual machine on which the code executes. The standard one for C
`programmers is called iNI—Java Native interface. Others are being defined for
`other native languages. A description of these A-PIS is beyond the scope of this
`book.
`
`The sign:flaw Problems we face minor he .solved
`by the same level of thinking-that rivaled them.
`—Albert Einstein
`
`Page - 06 of 11
`
`
`488
`
`SHUTDOWN
`
`The environment variables of the current runtime process can be retrieved using
`the System „geteriv method, which takes a stringargument representing the name
`of the environment variable and returns a string representing its value. This
`method is deprecated because system properties (see page 481) are the preferred
`way to communicate between different virtual machine runtimes. However, this
`remains the only means of querying and subsequently modifying the environment
`when executing a non-Java program.
`There remain two further forms of exec that allow the initial working dired-
`tory of the child process to be specified:
`public Process exec(Stringri cmdAr ray , Sting[] env, File dir)
`throws 1.0Excepti on
`public Process exec(String command, String] env, File dir)
`throws I0Excepti on
`The child process is given an initial working directory as specified by the path
`of di r. if di r is null, the child process inherits the current working directory of
`the parent—as specified by the system property user..di r. The one- and two-
`argument forms of exec -are equivalent IP passing null for di r.
`
`•
`
`18.2.3 Portability
`Any program that uses exec is not portable aetoss all systems, Not all environ-
`ments have processes,. and those. that have them can have widely varying com-
`mands and syntax for invoking those commands. Also, because running arbitrary
`commands raises serious security issues, the system may not allow all programs to
`use exec. Be very cautious in choosing to use exec because it has a strong nega-
`tive impact on your ability to tun your program everywhere.
`Exercise 18.2; Write a program that runs exec on its-command-line arguments and
`prints the output from the command, preceding each line of output by its line num-
`ber.
`E ereise 18.3: Write a program that runs exec on command-line arguments and
`prints the output from the command, killing the command when a particular string
`appears in the output,
`
`,
`
`18.3 Shutdown
`Normallyan execution of a virtual machine terminates when the last user thread
`terminates. A Runtime can also be shut down explicitly by invoking its exit
`
`higtallMINOMONI
`
`AtitiEt
`
`Page - 07 of 11
`
`
`40
`
`s1 71;M PROGRAMMING
`method. passing an integer status code that can be communicated to the environ-
`ment executing the virtual machine—zero to indicate successful completion of a
`task and non-zero to indicate failure. This method abruptly terminates all threads
`in the runtime system, no matter what their state. They are not interrupted, or even
`stopped..they simply cease to exist as the virtual machine itself stops running—no
`fi nal ly clauses are executed.
`In either case, when exi t is invoked, or the last user thread terminates, the
`shutdown sequence is initiated. The virtual machine can also be shut down exter-
`nally, such as by a user :interrupting the virtual machine from a keyboard (on many
`systems by typing control-C) or when .the user Digs out or the computer is shut
`down.
`AU of the methods related to shutting down the runtime system are security
`checked and throw a SecurityExcepti on if you do not have permission to per-
`form them. •
`
`18.3.1. Shutdown Hooks
`An application can register a shutdown hook with the runtime system. These are
`threads that represent actions that should be taken before the virtual machine
`exits. Hooks typically clean up external resources such as files and -network .con-
`nections.
`public void addShutdownHook(Thread hqpk)
`Registers a: new virtual machine shutdown hook. If hook has already been
`registered or has already been started an Il legal ArgumentException is
`thrown.
`public boot can rentoveShutdownItook(Thread hook)
`De-registers a previously registered virtual machine shutdown hook..
`Returns true if hook was registered and...has been de-registered. Returns
`false if hook was not previously registered.
`You cannot add or remove shutdown hooks after shutdown has commenced; you
`will get Il 1 egal StateExcepti on if you try.
`When shutdown is initiated, the virtual Machine will invoke the start
`method on all shutdown hook Thread objects. You cannot rely on any ordering—
`shutdown hook threads may be executed before, after, or at the same time as any
`other shutdown hook thread depending on thread scheduling.
`You must be. careful about this lack of ordering. Suppose, for example, you
`were writing a class that stored state in a database. You might register a shutdOWn
`hook that closed the database. However a program using your class might want to
`register its own shutdown hook that writes some final state information through
`your class to the database. If your shutdown hook is run first (closing the data-
`
`Page - 08 of 11
`
`
`532
`
`20.2 Java.appi et —Applets
`
`,AVA, APPI.ET+APPLETS
`
`Applets are a way to run code inside another application—Commonly a Web
`browser. Applets are the first exposure many.. people have- to tile Java virtual
`machine and its uses. An.applet is defined prinwily by the protocol that governs
`its lifetime and the methods by which it can query and manipulate its runtime
`environment. The types in Java .-appl et—primarily the Appl et superclass
`itself—define this environment.
`When an APPLET tag is found in a Web page's HTML,, the browser downloads
`the -code for the named class from a URI., creates an object of that Class, creates a
`region on the. Web page. for that Object to contra and then invokes the object's
`lnit method—Often. creating a ThreadCroup and Thread just for this 'applet. AS •
`the applet. rues, it can download other classes from the server as needed:: Applets
`are usually run in a tightly secured "sandbox" in which potentially dangerous
`operations (such as file access, network access. and running local programs) are
`restricted by the security policy,
`The method i ni t Is one of four lifecycle methods. defined for the applet in the
`Appi et class. After i hi tis called, start is called, which tellS the applet that it is
`active and should perform its functien, lithe browser decides that the applet is no
`longer of interest to the user, for example the user leaves. the page the applet was
`on, the applet's stop method is invoked to tell it to stop what it was doing. If the
`user returns to the applet's page the browser may invoke start again to tell the
`applet to recommence----so the applet can cycle through a stop-start sequence as
`the user presses the "8ack'' and "Forward" buttons (or their equivalents) to visit
`'and leave the page:When the browser decides -that the applet has been: finished
`with (perhaps because the user has moved a-number. of pages away) the, applet's
`destroy method is 'invoked to free up any resources used by the applet. If the. app-
` revisited the lifecycle will recommence with 1 ni t being called
`let's page is
`again. The browser ultimately defines the lifecycle of an applet and may choose to
`invoke destroy immediately after stop when the user leaves the page. Whether
`.or not an applet class is unloaded and reloaded between visits to the applet is
`again a feature of the browser.
`These lifecycle methods .are typically overridden by appletclasses. Forexam-
`ple, if an applet uses a thread to do its wok i ni t would typically create the
`thread; start would invoke the thread's start method the first time andask it to
`continue execution on subsequent invocations; stop could ask the thread to pause
`to prevent it from consuming resources.While the page is. not visible; and destroy
`could interrupt the thread because the thread would no longer be needed.
`An applet can. get parameters from the APPLET tag to customize its behavior.
`It might get colors, rents, or the URL of an image to display.
`
`Page - 09 of 11
`
`
`533
`
`STANDARD PACKAGES
`Applets usually run in a highly constrained security environment to protect
`your computer and network from unwelcome inspection or invasion by a hostile
`applet. This means .that certain conveniences, such as a local scratch disk, may not
`be available by default. Permission to perform particular actions can be granted to
`individual applets by specifying an appropriate security policy.
`The applet model is a good example of how the Java platform provides power.
`The fact that the same code runs on all systems in the same way allows a single
`piece of code (an applet} to run in a variety of browsers on a .variety of windowing
`systems running on.a larger variety of Operating systems; The portability of Java
`.bytecodes allows you to execute part of your application on. the server and another
`part on the client system via downloaded code, whichever is appropriate. it is the
`L same platforin on both sides: the Java virtual machine, The ability to move code
`from one place to another and execute it in a secure environment enables new
`rays of thinking.about where to execute what part of your design.
`
`20.3 Java beans Components
`JavaBeansT' is a componeat architecture that helps independent vendors write
`classes that can be -treated as components of larger systems assembled by users.
`The java, beans package provides necessary and useful classes for writing such
`beans. A bean exports properties, generates events, and implements methods. By
`following certain design patterns or by implementing methods that provide a
`description of these facets of behavior, you can compose beans using interactive
`tools to build a system the user needs.
`Much of a bean's behavior is simplified if you follow expected design pat-.
`terns; For example, if your bean class is called Ernest and you provide a class
`named ErnestSeanlnfo that implements the Beaninfe interface, the JavaBefins
`tools will use it as a source of information about the behavior of the bean: the
`-events it supports, the icons it uses, and so on.
`Providing a Bean Info object is itself optional—the javaBearts system will
`use reflection to infer events and properties: For example, if a class Ernest has
`methods named oet impor ranee and setimportance, the JavaBeans systernwill
`assume that. you have an iimportance property that can be set,. either directly or
`via another bean. Bulkier tools are expected to present the properties and events to
`users, who can use them to connect beans as components to build custom .applica-
`tions.
`AWT components are beans, and the event model described earlier for AWT
`components is also the JavaBeans event model.
`
`Page - 10 of 11
`
`
`ti
`
`Diced from the creators of the Java" programming language, this Third Edition of7.
`The Java' Programming Language is a valuable resource for both novice and
`advanced programmers. More lhan MOO developers who programmed with
`C, C++, Smalltalk, or other high-level languages have used this book to get a con,
`vise, intelligent, and deep understanding of the Java programming language. •
`- This book is what you .need to understand the basic design goals of the
`language and the application of the language in real-world developinent.• tt
`provides unique insights into why and how the language was designed •and •
`intended to be used....
`The authors deS6-ibe the latest.versinn of the language, as.delined in the
`Jame Language Sperifiration,..Serond Edition and implemented in version.1.5
`of the Java 2 SDK,. Standard E,dition. This third edition has been struchired to
`give More intdepth trealntent titter newer language•features, as well as infor-
`mative examples on using soine of thenew APIs.
`New and/or revised in this edition:
`•
`;.;
`,
`•
`• . • •
`• more details on language features, including an expanderi3Oction
`on nested
`•
`. • more comprehensive treatment of'garbage collection and related
`.
`•
`programming issues
`* cOVeragellfneW APfs, such as collections and internationalization
`,Thoitughlyrevised from Mart to finish, this editionitilly covers the features of
`the current release of the Java programming language and class libraries. The
`book serves aS a tutorial introduction to the language and essential libraries as
`as a reference.
`Experienced programmers will find this new edition to be a valuable refer-
`ehce,•and will gain new insights.intp the subtleties of the language. Novice and
`intermediate programmer;; will benefit froM the valuable examples and clear
`explanations of tangnage•and library features. Make sore you upderstapd the
`contents'of this book before you begin any serious developmeht for the JaVa
`platform.
`Ken Arnold, a Senior Staff Engineer at Sun Microsystems laboratories, is
`a leading expert in object-oriented design and implementation, one of the orig-
`inal architects of the Jini" technology, and the lead engineer or Sun's
`JavaSpaces' technology:Ha has written extensively on C and C-1-4- topics for
`LIM Wien', and is a leading expert in object-oriented design; Jaya, and C4-4-. •
`dimes Gosling. is .a fellow and.Vice President at Sun Microsystems, the
`creator oftheJava programming language, and one of the''iztriputei indushys
`most noted programmers. He is the 1996 recipient of Software Development's
`"Programming Excellence Award!' He. previously developed NeWS'',..Surt's net-
`work-extensible window system, anti was a principal. in tha Andrew project at
`Carnegie-Mellon University, from which he holds a PhD In Computer Science.
`David Holmes is a Senior Research Scientist al the Cooperative Research
`Centre for Enterprise Distributed Systems. Technology (DSTC Ply Ltd), located
`in Brisba;le, Australia. His work with Java technology haS foctised on concur-
`,
`ratty and synchronization support in the language and.viytuat machine. He has
`presented tutorials on cone urgency and design at numerous international
`object-oriented programming conferences, He completed his PhD at Macquarie
`University, Sydney, in 1999.
`http://javasuricom/books/Series/
`
`JOyar See s. is. Su
`and 'alAtha
`rs of the ,.iavit• nolog
`. 4 ,
`iCarOSVSkInSt ices. It is
`it .place to. go for.,.064ppietefi
`and, definitie
`e>
`on,Javatecluvlow.:,
`provide the ila~idi info r ;
`tip
`friatibri-you need to bUild*edive,
`anci pottat*i vplic.ations
`and, app g‘: The' $&ries,is:an ndts
`pensabte reisoure`fdtany
`gretirsk(theltval
`
`ai4 c
`
`e t
`
`14.4,4*
`
`Su 4.
`
`1 nicannte—
`Covei de:iiga by Sitnone it. Payment
`Cover art by Sara Connell
`*Text printed on recycled paper
`•Ar Addison-Wesley
`Pearson Education
`
`Ifill9M9191
`
`11111111 II
`9 780201 704334
`ISB N 0-201-70433 it
`$39.99 US
`CANADA .
`$59.95
`
`• 1•.
`
`Page - 11 of 11
`