ebook img

Java Examples in a Nutshell: A Tutorial Companion to Java in a Nutshell PDF

584 Pages·2000·2.55 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Java Examples in a Nutshell: A Tutorial Companion to Java in a Nutshell

™ EXAMPLES IN A NUTSHELL A Tutorial Companion to Java in a Nutshell Learning Java Java Threads Java Network Programming Java Virtual Machine Java AWT Reference Java Language Reference Java Fundamental Classes Reference Database Programming with JDBC and Java Java Distributed Computing Developing Java Beans Java Security Java Cryptography Java Swing Java Servlet Programming Java I/O Java 2D Graphics Enterprise JavaBeans Creating Effective JavaHelp Java and XML Java Performance Tuning Also from O’Reilly Java in a Nutshell Java Examples in a Nutshell Java Enterprise in a Nutshell Java Foundation Classes in a Nutshell Java Power Reference: A Complete Searchable Resource on CD-ROM ™ EXAMPLES IN A NUTSHELL A Tutorial Companion to Java in a Nutshell Second Edition David Flanagan Beijing •Cambridge •Farnham •Köln •Paris •Sebastopol •Taipei •Tokyo Java™Examples in a Nutshell, Second Edition by David Flanagan Copyright © 2000, 1997 O’Reilly & Associates, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly & Associates, Inc., 101 Morris Street, Sebastopol, CA 95472. Editor: Paula Ferguson Production Editor: Mary Anne Weeks Mayo Cover Designer: Edie Freedman Printing History: September 1997: First Edition. September 2000: Second Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks and The Java Series is a trademark of O’Reilly & Associates, Inc.TheassociationoftheimageofanalligatorandthetopicofJavaexamplesisa trademarkofO’Reilly&Associates,Inc.JavaandallJava-basedtrademarksandlogos are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries. O’Reilly & Associates, Inc. is independent of Sun Microsystems. Many of the designations used by manufacturers and sellers to distinguish their productsareclaimedastrademarks. Wherethosedesignationsappearinthisbook, and O’Reilly & Associates, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. Whileeveryprecautionhasbeentakeninthepreparationofthisbook,thepublisher assumesnoresponsibilityforerrorsoromissions,orfordamagesresultingfromthe use of the information contained herein. Library of Congress Cataloging-in-Publication Data Flanagan, David. Java examples in a nutshell / David Flanagan.--2nd ed. p.cm.-- (A Nutshell handbook) (The Java series) Includes index. ISBN 1-596-00039-1 1.Java (Computer program language) I.Title. II.Series. III.Java series (O’Reilly & Associates) QA76.73.J38 F5518 2000 005.13'3--dc21 00-045274 ISBN: 0-596-00039-1 [M] About the Author David Flanagan is a computer programmer who spends most of his time writing about Java. His other books with O’Reilly & Associates include the bestselling Java inaNutshell, JavaFoundationClassesinaNutshell, JavaEnterpriseinaNutshell, JavaPowerReference,JavaScript:TheDefinitiveGuide,andJavaScriptPocketRefer- ence. David has a degree in computer science and engineering from the MassachusettsInstituteofTechnology.HeliveswithhispartnerChristieintheU.S. Pacific Northwest between the cities of Seattle, Washington and Vancouver, British Columbia. Colophon Ourlookistheresultofreadercomments,ourownexperimentation,andfeedback fromdistributionchannels.Distinctivecoverscomplementourdistinctiveapproach to technical topics, breathing personality and life into potentially dry subjects. TheanimalfeaturedonthecoverofJavaExamplesinaNutshell,SecondEdition,is analligator.Thereareonlytwospeciesofalligator:theAmericanalligator(Alligator mississippiensis), found in the southeastern coastal plain of the United States, and the smaller Chinese alligator (Alligator sinensis), found in the lower valley of the Yangtze River. Both alligators are related to the more widely distributed crocodile. The alligator is a much-studied animal, and so a great deal is known about its life cycle. Female alligators lay 30 to 80 eggs at a time. The mother allows the sun to incubate the eggs, but stays nearby. After about 60 days the eggs hatch, and the youngcalloutfortheirmother.Themotherthencarriesorleadsthemtothewater, where they live with her for a year. Alligators eat a varied diet of insects, fish, shellfish, frogs, water birds, and small mammals.Alligatorattacksonhumansarerare.Althoughnormallyslow-movingani- mals,alligatorscanchargequicklyforshortdistanceswhentheyortheiryoungare in danger. Alligators have been hunted extensively for their skin. The American alligator was placedontheendangeredspecieslistin1969,thendeclaredtobeoutofdangerin 1987. The Chinese alligator remains on the endangered list. MaryAnneWeeksMayowasthecopyeditorandproductioneditorforJavaExamples in a Nutshell, Second Edition. Emily Quill, Madeleine Newell, and Jane Ellin pro- vided quality control. Ann Schirmer and Linley Dolby provided production assistance. Ellen Troutman-Zaig wrote the index. EdieFreedmandesignedthecoverofthisbookusinga19th-centuryengravingfrom the Dover Pictorial Archive. Emma Colby produced the cover layout with Quark- XPress 4.1 using Adobe’s ITC Garamond font. AliciaCechandDavidFutatodesignedtheinteriorlayoutbasedonaseriesdesignby NancyPriest.TheprintversionofthisbookwascreatedbytranslatingtheDocBook SGMLmarkupofitssourcefilesintoasetofgtroffmacrosusingafilterdevelopedat O’Reilly&AssociatesbyNormanWalsh.SteveTalbottdesignedandwrotetheunder- lying macro set on the basis of the GNU troff -gs macros; Lenny Muellner adapted themtoSGMLandimplementedthebookdesign.TheGNUgrofftextformatterver- sion 1.11.1 generated PostScript output. The text and heading fonts are ITC GaramondandLetterGothic.Theillustrationsthatappearinthebookwereproduced byRobertRomanousingMacromediaFreeHand8andAdobePhotoshop5.Thiscol- ophon was written by Clairemarie Fisher O’Leary. Wheneverpossible,ourbooksuseadurableandflexiblelay-flatbinding.Ifthepage count exceeds this binding’s limit, perfect binding is used. Ta ble of Contents Preface .................................................................................................................... xiii Part I: Core Java APIs Chapter 1—Java Basics .................................................................................. 3 Hello World ............................................................................................. 3 FizzBuzz .................................................................................................. 7 The Fibonacci Series ............................................................................. 10 Using Command-Line Arguments ........................................................ 10 Echo in Reverse .................................................................................... 11 FizzBuzz Switched ................................................................................ 12 Computing Factorials ............................................................................ 13 Recursive Factorials .............................................................................. 14 Caching Factorials ................................................................................. 15 Computing Big Factorials ..................................................................... 16 Handling Exceptions ............................................................................. 17 Interactive Input .................................................................................... 18 Using a StringBuffer .............................................................................. 19 Sorting Numbers ................................................................................... 21 Computing Primes ................................................................................ 22 Exercises ................................................................................................ 23 v 13 September 2000 10:02 Chapter 2—Objects, Classes, and Interfaces ................................. 24 A Rectangle Class .................................................................................. 25 Testing the Rect Class ........................................................................... 26 A Rect Subclass ..................................................................................... 27 Another Subclass ................................................................................... 27 Complex Numbers ................................................................................ 28 Computing Pseudo-Random Numbers ................................................ 30 Computing Statistics .............................................................................. 32 A Linked List Class ................................................................................ 33 Advanced Sorting .................................................................................. 36 Exercises ................................................................................................ 42 Chapter 3—Input/Output ......................................................................... 44 Files and Streams .................................................................................. 44 Working with Files ................................................................................ 48 Copying File Contents .......................................................................... 49 Reading and Displaying Text Files ...................................................... 52 Listing Directory and File Information ................................................. 55 Compr essing Files and Directories ...................................................... 60 Filtering Character Streams ................................................................... 62 Filtering Lines of Text ........................................................................... 64 A Custom HTML Output Stream .......................................................... 65 Exercises ................................................................................................ 68 Chapter 4—Threads ....................................................................................... 70 Thr ead Basics ........................................................................................ 71 Thr eads and Thread Groups ................................................................ 72 Deadlock ............................................................................................... 75 Timers .................................................................................................... 77 Exercises ................................................................................................ 82 Chapter 5—Networking .............................................................................. 84 Downloading the Contents of a URL ................................................... 84 Using a URLConnection ........................................................................ 86 Sending Email Through a URLConnection .......................................... 87 Connecting to a Web Server ................................................................. 89 A Simple Web Server ............................................................................ 91 A Proxy Server ...................................................................................... 93 Networking with Applets ..................................................................... 96 A Generic Client .................................................................................... 99 vi 13 September 2000 10:02 A Generic Multithreaded Server ......................................................... 101 A Multithr eaded Pr oxy Server ............................................................ 113 Sending Datagrams ............................................................................. 116 Receiving Datagrams .......................................................................... 117 Exercises .............................................................................................. 119 Chapter 6—Secur ity and Cryptog raphy ....................................... 121 Running Untrusted Code .................................................................... 122 Loading Untrusted Code ..................................................................... 123 Message Digests and Digital Signatures ............................................ 128 Cryptography ...................................................................................... 136 Exercises .............................................................................................. 139 Chapter 7—Inter nationalization ..................................................... 141 A Word About Locales ........................................................................ 141 Unicode ............................................................................................... 142 Character Encodings ........................................................................... 146 Handling Local Customs ..................................................................... 148 Localizing User-Visible Messages ....................................................... 151 For matted Messages ............................................................................ 156 Exercises .............................................................................................. 159 Chapter 8—Reflection ............................................................................... 161 Obtaining Class and Member Information ........................................ 161 Invoking a Named Method ................................................................ 164 Exercises .............................................................................................. 168 Chapter 9—Object Serialization ........................................................ 169 Simple Serialization ............................................................................. 169 Custom Serialization ........................................................................... 172 Exter nalizable Classes ......................................................................... 174 Serialization and Class Versioning ...................................................... 176 Serialized Applets ................................................................................ 177 Exercises .............................................................................................. 178 vii 13 September 2000 10:02 Part II: Graphics and GUIs Chapter 10—Graphical User Interfaces ....................................... 181 Components ........................................................................................ 183 Containers ........................................................................................... 189 Layout Management ............................................................................ 190 Event Handling ................................................................................... 203 A Complete GUI ................................................................................. 217 Actions and Reflection ........................................................................ 221 Custom Dialogs ................................................................................... 222 Displaying Tables ................................................................................ 227 Displaying Trees ................................................................................. 230 A Simple Web Browser ....................................................................... 234 Describing GUIs with Properties ....................................................... 242 Themes and the Metal Look-and-Feel ............................................... 253 Custom Components .......................................................................... 257 Exercises .............................................................................................. 263 Chapter 11—Graphics .............................................................................. 266 Graphics Before Java 1.2 .................................................................... 267 The Java 2D API .................................................................................. 276 Drawing and Filling Shapes ............................................................... 277 Transfor ms ........................................................................................... 279 Line Styles with BasicStroke ............................................................... 281 Str oking Lines ...................................................................................... 283 Filling Shapes with Paint .................................................................... 284 Antialiasing .......................................................................................... 287 Combining Colors with AlphaComposite .......................................... 289 Image Processing ................................................................................ 292 A Custom Shape .................................................................................. 295 Custom Strokes ................................................................................... 299 Custom Paint ....................................................................................... 303 Advanced Animation .......................................................................... 305 Displaying Graphics Examples .......................................................... 308 Exercises .............................................................................................. 312 viii 13 September 2000 10:02

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.