www.it-ebooks.info www.it-ebooks.info Java ™ Cookbook ™ www.it-ebooks.info Other Java ™ resources from O’Reilly Related titles Java ™ in a Nutshell Head First Java ™ Head First EJB ™ Programming Jakarta Struts Tomcat: The Definitive Guide Learning Java ™ Better, Faster, Lighter Java ™ Java ™ Servlet and JSP ™ Cookbook ™ Hardcore Java ™ JavaServer ™ Pages Java Books Resource Center java.oreilly.com is a complete catalog of O’Reilly’s books on Java and related technologies, including sample chapters and code examples. OnJava.com is a one-stop resource for enterprise Java develop- ers, featuring news, code recipes, interviews, weblogs, and more. Conferences O’Reilly brings diverse innovators together to nurture the ideas that spark revolutionary industries. We specialize in document- ing the latest tools and systems, translating the innovator’s knowledge into useful skills for those in the trenches. Visit con- ferences.oreilly.com for our upcoming events. Safari Bookshelf (safari.oreilly.com) is the premier online refer- ence library for programmers and IT professionals. Conduct searches across more than 1,000 books. Subscribers can zero in on answers to time-critical questions in a matter of seconds. Read the books on your Bookshelf from cover to cover or sim- ply flip to the page you need. Try it today with a free trial. www.it-ebooks.info Java ™ Cookbook ™ SECOND EDITION Ian F. Darwin Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo www.it-ebooks.info Java ™ Cookbook ™ , Second Edition by Ian F. Darwin Copyright © 2004, 2001 O’Reilly Media, Inc. 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. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Editors: Mike Loukides and Debra Cameron Production Editor: Marlowe Shaeffer Cover Designer: Hanna Dyer Interior Designer: David Futato Printing History: June 2001: First Edition. June 2004: Second Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. The Cookbook series designations, Java Cookbook, the image of a domestic chicken, and related trade dress are trademarks of O’Reilly Media, Inc. Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries. O’Reilly Media, Inc. is independent of Sun Microsystems, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed 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 initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. This book uses RepKover ™ , a durable and flexible lay-flat binding. ISBN: 0-596-00701-9 ISBN13: 978-0-596-00701-0 [M] [1/07] www.it-ebooks.info v Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv 1. Getting Started: Compiling, Running, and Debugging . . . . . . . . . . . . . . . . . . . 1 1.1 Compiling and Running Java: JDK 1 1.2 Editing and Compiling with a Color-Highlighting Editor 3 1.3 Compiling, Running, and Testing with an IDE 4 1.4 Using CLASSPATH Effectively 11 1.5 Using the com.darwinsys API Classes from This Book 14 1.6 Compiling the Source Code Examples from This Book 15 1.7 Automating Compilation with Ant 16 1.8 Running Applets 17 1.9 Dealing with Deprecation Warnings 20 1.10 Conditional Debugging Without #ifdef 22 1.11 Debugging Printouts 24 1.12 Maintaining Program Correctness with Assertions 25 1.13 Debugging with JDB 26 1.14 Unit Testing: Avoid the Need for Debuggers 28 1.15 Getting Readable Tracebacks 30 1.16 Finding More Java Source Code 32 1.17 Program: Debug 33 2. Interacting with the Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 2.1 Getting Environment Variables 35 2.2 System Properties 37 2.3 Writing JDK Release-Dependent Code 39 2.4 Writing Operating System-Dependent Code 40 2.5 Using Extensions or Other Packaged APIs 42 2.6 Parsing Command-Line Arguments 43 www.it-ebooks.info vi | Table of Contents 3. Strings and Things . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 3.1 Taking Strings Apart with Substrings 52 3.2 Taking Strings Apart with StringTokenizer 53 3.3 Putting Strings Together with +, StringBuilder (JDK 1.5), and StringBuffer 56 3.4 Processing a String One Character at a Time 59 3.5 Aligning Strings 60 3.6 Converting Between Unicode Characters and Strings 63 3.7 Reversing a String by Word or by Character 64 3.8 Expanding and Compressing Tabs 65 3.9 Controlling Case 70 3.10 Indenting Text Documents 71 3.11 Entering Nonprintable Characters 73 3.12 Trimming Blanks from the End of a String 74 3.13 Parsing Comma-Separated Data 75 3.14 Program: A Simple Text Formatter 80 3.15 Program: Soundex Name Comparisons 82 4. Pattern Matching with Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 4.1 Regular Expression Syntax 87 4.2 Using regexes in Java: Test for a Pattern 94 4.3 Finding the Matching Text 97 4.4 Replacing the Matched Text 99 4.5 Printing All Occurrences of a Pattern 100 4.6 Printing Lines Containing a Pattern 103 4.7 Controlling Case in Regular Expressions 104 4.8 Matching “Accented” or Composite Characters 105 4.9 Matching Newlines in Text 106 4.10 Program: Apache Logfile Parsing 108 4.11 Program: Data Mining 110 4.12 Program: Full Grep 112 5. Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 5.1 Checking Whether a String Is a Valid Number 119 5.2 Storing a Larger Number in a Smaller Number 120 5.3 Converting Numbers to Objects and Vice Versa 121 5.4 Taking a Fraction of an Integer Without Using Floating Point 122 5.5 Ensuring the Accuracy of Floating-Point Numbers 123 5.6 Comparing Floating-Point Numbers 125 www.it-ebooks.info Table of Contents | vii 5.7 Rounding Floating-Point Numbers 127 5.8 Formatting Numbers 128 5.9 Converting Between Binary, Octal, Decimal, and Hexadecimal 130 5.10 Operating on a Series of Integers 131 5.11 Working with Roman Numerals 132 5.12 Formatting with Correct Plurals 136 5.13 Generating Random Numbers 138 5.14 Generating Better Random Numbers 139 5.15 Calculating Trigonometric Functions 140 5.16 Taking Logarithms 141 5.17 Multiplying Matrices 141 5.18 Using Complex Numbers 143 5.19 Handling Very Large Numbers 145 5.20 Program: TempConverter 147 5.21 Program: Number Palindromes 151 6. Dates and Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154 6.1 Finding Today’s Date 155 6.2 Printing Date/Time in a Given Format 156 6.3 Representing Dates in Other Epochs 159 6.4 Converting YMDHMS to a Calendar or Epoch Seconds 160 6.5 Parsing Strings into Dates 161 6.6 Converting Epoch Seconds to DMYHMS 162 6.7 Adding to or Subtracting from a Date or Calendar 163 6.8 Difference Between Two Dates 165 6.9 Comparing Dates 165 6.10 Day of Week/Month/Year or Week Number 167 6.11 Creating a Calendar Page 168 6.12 Measuring Elapsed Time 171 6.13 Sleeping for a While 173 6.14 Program: Reminder Service 173 7. Structuring Data with Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 7.1 Using Arrays for Data Structuring 177 7.2 Resizing an Array 178 7.3 Like an Array, but More Dynamic 180 7.4 Using Iterators for Data-Independent Access 181 7.5 Structuring Data in a Linked List 183 7.6 Mapping with Hashtable and HashMap 185 www.it-ebooks.info viii | Table of Contents 7.7 Storing Strings in Properties and Preferences 186 7.8 Sorting a Collection 190 7.9 Avoiding the Urge to Sort 193 7.10 Eschewing Duplication 195 7.11 Finding an Object in a Collection 196 7.12 Converting a Collection to an Array 198 7.13 Rolling Your Own Iterator 199 7.14 Stack 201 7.15 Multidimensional Structures 202 7.16 Finally, Collections 204 7.17 Program: Timing Comparisons 206 8. Data Structuring with Generics, foreach, and Enumerations (JDK 1.5) . . . 208 8.1 Using Generic Collections 209 8.2 Using “foreach” Loops 210 8.3 Avoid Casting by Using Generics 211 8.4 Let Java Convert with AutoBoxing and AutoUnboxing 214 8.5 Using Typesafe Enumerations 215 8.6 Program: MediaInvoicer 219 9. Object-Oriented Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 9.1 Printing Objects: Formatting with toString( ) 224 9.2 Overriding the Equals Method 225 9.3 Overriding the hashCode Method 228 9.4 The Clone Method 229 9.5 The Finalize Method 231 9.6 Using Inner Classes 233 9.7 Providing Callbacks via Interfaces 234 9.8 Polymorphism/Abstract Methods 238 9.9 Passing Values 239 9.10 Enforcing the Singleton Pattern 242 9.11 Roll Your Own Exceptions 243 9.12 Program: Plotter 244 10. Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 10.1 Reading Standard Input 248 10.2 Writing Standard Output 252 10.3 Printing with the 1.5 Formatter 253 10.4 Scanning a File with StreamTokenizer 257 10.5 Scanning Input with the 1.5 Scanner Class 262 www.it-ebooks.info [...]... but not necessarily optimal for speed of development Nonetheless, using Sun’s JDK, the commands are javac to compile and java to run your program (and, on Windows only, javaw to run a program without a console window) For example: C:\javasrc>javac HelloWorld .java C:\javasrc >java HelloWorld Hello, World C:\javasrc> As you can see from the compiler’s (lack of) output, this compiler works on the Unix “no... reserved Preface to the First Edition If you know a little Java, great If you know more Java, even better! This book is ideal for anyone who knows some Java and wants to learn more If you don’t know any Java yet, you should start with one of the more introductory books from O’Reilly, such as Head First Java or Learning Java if you’re new to this family of languages, or Java in a Nutshell if you’re an... standardized Java 2 Micro Edition is concerned with small devices such as handhelds (PalmOS and others), cell phones, fax machines, and the like Within J2ME are various “profiles” for different classes of devices At the high end, the Java 2 Enterprise Edition (J2EE) is concerned with building large, scalable, distributed applications Servlets, JavaServer Pages, JavaServer Faces, CORBA, RMI, JavaMail,... release to Java 2, and the implementation is known as Java 2 SDK 1.2 The current version as of the writing of the first edition of this book was Java 2 SDK 1.3 (JDK 1.3), which was released in 2000 Preface This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright © 2007 O’Reilly & Associates, Inc All rights reserved | xxi As the first edition of this book went to press, Java 2 Version... Running Java: JDK Problem You need to compile and run your Java program Solution This is one of the few areas where your computer’s operating system impinges on Java s portability, so let’s get it out of the way first * There is humor in the phrase “old Java code,” which should be apparent when you realize that Java had been in circulation for under five years at the time of this book’s first edition. .. in Recipe 1.4, that controls where Java looks for classes CLASSPATH, if set, is used by both javac and java In older versions of Java you had to set your CLASSPATH to include “.”, even to run a simple program from the current directory; this is no longer true on Sun’s current Java implementations It may be true on some of the clones Command-line alternatives Sun’s javac compiler is the official reference... around the time of the book’s completion so I could mention it only briefly The second edition of this book looks to have better timing; Java 2 Version 1.5 is in beta as I am updating the book This book is aimed at the fifth version, Java 2 Standard Edition, Version 1.5 By the time of publication, I expect that all Java projects in development will be using JDK 1.4, with a very few wedded to earlier... and/or if any for FTP? Check out http:/ /java. sun.com (oak got renamed to java and webrunner got renamed to hotjava to keep the lawyers happy) I downloaded HotJava and began to play with it At first I wasn’t sure about this newfangled language, which looked like a mangled C/C++ I wrote test and demo programs, sticking them a few at a time into a directory that I called javasrc to keep it separate from my... Enterprise JavaBeans™ (EJBs), Transactions, and other APIs are part of the J2EE J2ME and J2EE packages normally begin with “javax” as they are not core J2SE packages This book does not * Note that not all packages named javax are extensions: javax.swing and its subpackages—the Swing GUI packages—used to be extensions, but are now core xxii | Preface This is the Title of the Book, eMatter Edition www.it-ebooks.info... at: http://www.oreilly.com/catalog/javacook2/ I also have a personal web site for the book: http://javacook.darwinsys.com/ xxvi | Preface This is the Title of the Book, eMatter Edition www.it-ebooks.info Copyright © 2007 O’Reilly & Associates, Inc All rights reserved Both sites list errata and plans for future editions You’ll also find the source code for all the Java code examples to download; please . Definitive Guide Learning Java ™ Better, Faster, Lighter Java ™ Java ™ Servlet and JSP ™ Cookbook ™ Hardcore Java ™ JavaServer ™ Pages Java Books Resource Center java. oreilly.com is a complete. trial. www.it-ebooks.info Java ™ Cookbook ™ SECOND EDITION Ian F. Darwin Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo www.it-ebooks.info Java ™ Cookbook ™ , Second Edition by. www.it-ebooks.info www.it-ebooks.info Java ™ Cookbook ™ www.it-ebooks.info Other Java ™ resources from O’Reilly Related titles Java ™ in a Nutshell Head First Java ™ Head First EJB ™ Programming