About the AuthorHerbert Schildt is a leading authority on Java, C, C++,and C#, and is a master Windows programmer. Hisprogramming books have sold more than 3.5 millioncopies worldwide and have been translated intoall major foreign languages. He is the author ofnumerous bestsellers on Java, including Java: TheComplete Reference, Java: A Beginners Guide, Swing:A Beginners Guide, and The Art of Java (co-authoredwith James Holmes). His other bestsellers include C:The Complete Reference, C++: The Complete Reference,and C#: The Complete Reference. Schildt holds bothgraduate and undergraduate degrees from theUniversity of Illinois. He can be reached at hisconsulting office at (217) 586-4683. His web site iswww.HerbSchildt.com.
Herb Schildt’s JavaProgramming Cookbook Herb Schildt New York Chicago San Francisco Lisbon London Madrid Mexico City Milan New Delhi San Juan Seoul Singapore Sydney Toronto
PrefaceF or many years, friends and readers have asked me to write a cookbook for Java, sharing some of the techniques and approaches that I use when I program. From the start I liked the idea, but was unable to make time for it in my very busy writingschedule. As many readers know, I write extensively about many facets of programming,with a special focus on Java, C/C++, and C#. Because of the rapid revision cycles of thoselanguages, I spend nearly all of my available time updating my books to cover the latestversions of those languages. Fortunately, early in 2007 a window of opportunity openedand I was finally able to devote time to writing this Java cookbook. I must admit that itquickly became one of my most enjoyable projects. Based on the format of a traditional food cookbook, this book distills the essence ofmany general-purpose techniques into a set of step-by-step recipes. Each recipe describes aset of key ingredients, such as classes, interfaces, and methods. It then shows the stepsneeded to assemble those ingredients into a code sequence that achieves the desired result.This organization makes it easy to find the technique in which you are interested and thenput that technique into action. Actually, "into action" is an important part of this book. I believe that good programmingbooks contain two elements: solid theory and practical application. In the recipes, the step-by-step instructions and discussions supply the theory. To put that theory into practice, each recipeincludes a complete code example. The examples demonstrate in a concrete, unambiguousway how the recipes can be applied. In other words, the examples eliminate the “guesswork”and save you time. Although no cookbook can include every recipe that one might desire (there is a nearlyunbounded number of possible recipes), I tried to span a wide range of topics. My criteriafor including a recipe are discussed in detail in Chapter 1, but briefly, I included recipes thatwould be useful to many programmers and that answered frequently asked questions. Evenwith these criteria, it was difficult to decide what to include and what to leave out. This wasthe most challenging part of writing this book. Ultimately, it came down to experience,judgment, and intuition. Hopefully, I have included something to satisfy everyprogrammers taste! HS xix
xx He rb Sc h i ldt ’s Java P rog ra m m i n g CookbookExample Code on the Web The source code for all of the examples in this book is available free of charge on the Web at www.osborne.com.More from Herbert Schildt Herb Schildts Java Programming Cookbook is just one of Herb’s many programming books. Here are some others that you will find of interest. To learn more about Java, we recommend Java: The Complete Reference Java: A Beginners Guide The Art of Java Swing: A Beginners Guide To learn about C++, you will find these books especially helpful. C++: The Complete Reference C++: A Beginners Guide C++ From the Ground Up STL Programming From the Ground Up The Art of C++ To learn about C#, we suggest the following Schildt books: C#: The Complete Reference C#: A Beginners Guide If you want to learn about the C language, then the following title will be of interest. C: The Complete Reference When you need solid answers, fast, turn to Herbert Schildt, the recognized authority on programming.
CHAPTER 1 Overview T his book is a collection of techniques that show how to perform various programming tasks in Java. As the title implies, it uses the well-known “cookbook” format. Each “recipe” illustrates how to accomplish a specific operation. For example, there are recipes that read bytes from a file, iterate a collection, format numeric data, construct Swing components, create a servlet, and so on. In the same way that a recipe in a food cookbook describes a set of ingredients and a sequence of instructions necessary to prepare a dish, each technique in this book describes a set of key program elements and the sequence of steps necessary to use them to accomplish a programming task. Ultimately, the goal of this book is to save you time and effort during program development. Many programming tasks consist of a set of API classes, interfaces, and methods that must be applied in a specific sequence. The trouble is that sometimes you don’t know which API classes to use or in what order to call the methods. Instead of having to wade through reams of API documentation and online tutorials to determine how to approach some task, you can look up its recipe. Each recipe shows one way to craft a solution, describing the necessary elements and the order in which they must be used. With this information, you can design a solution that fits your specific need.What’s Inside No cookbook is exhaustive. The author of a cookbook must make choices about what is and isn’t included. The same is true for this cookbook. In choosing the recipes for this book, I focused on the following categories: • String processing (including regular expressions) • File handling • Formatting data • Applets and servlets • Swing • The Collections Framework • Multithreading 1
2 He rb Sc h i ldt ’s Java P rog ra m m i n g Cookbook I chose these categories because they relate to a wide range of programmers. (I purposely avoided specialized topics that apply to only a narrow subset of cases.) Each of the categories became the basis for a chapter. In addition to the recipes related to the foregoing topics, I had several others that I wanted to include but for which an entire chapter was not feasible. I grouped those recipes into the final chapter. Of course, choosing the topics was only the beginning of the selection process. Within each category, I had to decide what to include and what not to include. In general, I included a recipe if it met the following two criteria. 1. The technique is useful to a wide range of programmers. 2. It provides an answer to a frequently asked programming question. The first criterion is largely self-explanatory and is based on my experience. I included recipes that describe how to accomplish a set of tasks that would commonly be encountered when creating Java applications. Some of the recipes illustrate a general concept that can be adapted to solve several different types of problems. For example, Chapter 2 shows a recipe that uses the Regular Expression API to search for and extract substrings from a string. This general procedure is useful in several contexts, such as finding an e-mail address or a telephone number within a sentence, or extracting a keyword from a database query. Other recipes describe more specific, yet widely used techniques. For example, Chapter 4 shows how to format the time and date by using SimpleDateFormat. The second criterion is based on my experience as the author of programming books. Over the many years that I have been writing, I have been asked hundreds and hundreds of “how to” questions by readers. These questions come from all areas of Java programming and range from the very easy to the quite difficult. I have found, however, that a central core of questions occurs again and again. Here is one example: “How do I format output?” Here is another: “How do I compress a file?” There are many others. These same types of questions also occur frequently on various programmer forums on the Web. I used these commonly asked “how to” questions to guide my selection of recipes. The recipes in this book span various skill levels. Some illustrate basic techniques, such as reading bytes from a file or creating a Swing JTable. Others are more advanced, such as creating a servlet or using reflection to instantiate an object at runtime. Thus, the level of difficulty of an individual recipe can range from relatively easy to significantly advanced. Of course, most things in programming are easy once you know how to do them, but difficult when you don’t. Therefore, don’t be surprised if some recipe seems obvious. It just means that you already know how to accomplish that task.How the Recipes Are Organized Each recipe in this book follows the same format, which has the following parts: • A description of the problem that the recipe solves. • A table of key ingredients used by the recipe. • The steps necessary to complete the recipe. • An in-depth discussion of the steps. • A code example that puts the recipe into action. • Options and alternatives that suggest other ways to craft a solution.
Chapter 1: Overview 3 A recipe begins by describing the task to accomplish. The key ingredients used by the recipe are shown in a table. These include the API classes, interfaces, and methods required to create a solution. Of course, putting a recipe into practice may imply the use of additional elements, but the key ingredients are those that are fundamental to the task at hand. Each recipe then presents step-by-step instructions that summarize the procedure. These are followed by an in-depth discussion of the steps. In many cases the summary will be sufficient, but the details are there if you need them. Next, a code example is presented that shows the recipe in action. All code examples are presented in their entirety. This avoids ambiguity and lets you clearly see precisely what is happening without having to fill in additional details yourself. Occasionally, a bonus example is included that further illustrates how a recipe can be applied. Each recipe concludes with a discussion of various options and alternatives. This section is especially important because it suggests different ways to implement a solution or other ways to think about the problem.A Few Words of Caution There are a few important points that you should keep in mind when you use this book. First, a recipe shows one way to craft a solution. Other ways may (and often do) exist. Your specific application may require an approach that is different from the one shown. The recipes in this book can serve as starting points, they can help you choose a general approach to a solution, and they can spur your imagination. However, in all cases, you must determine what is and what isn’t appropriate for your application. Second, it is important to understand that the code examples are not optimized for performance. They are optimized for clarity and ease of understanding. Their purpose is to clearly illustrate the steps of recipe. In many cases you will have little trouble writing tighter, more efficient code. Furthermore, the examples are exactly that: examples. They are simple uses that do not necessarily reflect the way that you will write code for your own application. In all circumstances, you must create your own solution that fits the needs of your application. Third, each code example contains error handling that is appropriate for that specific example, but may not be appropriate in other situations. In all cases, you must properly handle the various errors and exceptions that can result when adapting a recipe for use in your own code. Let me state this important point again: when implementing a solution, you must provide error handling appropriate to your application. You cannot simply assume that the way that errors or exceptions are handled (or not handled) by an example is sufficient or adequate for your use. Typically, additional error handling will be required in real-world applications.Java Experience Required This book is for every Java programmer, whether beginner or experienced pro. However, it does assume that you know the fundamentals of Java programming, including Java’s keywords, syntax, and basic API classes. You should also be able to create, compile, and run Java programs. None of these things are taught by this book. (As explained, this book is about applying Java to a variety of real-world programming problems. It is not about
4 He rb Sc h i ldt ’s Java P rog ra m m i n g Cookbook teaching the fundamentals of the Java language.) If you need to improve your Java skills, I recommend my books Java: The Complete Reference and Java: A Beginner’s Guide. Both are published by McGraw-Hill, Inc.What Version of Java? As most readers know, Java has been in a state of constant evolution since its creation. With each new release, features are added. In many cases a new release will also deprecate (render obsolete) several older features. As a result, not all modern Java code can be compiled by an older Java compiler. This is important because the code in this book is based on Java SE 6, which (at the time of this writing) is the current version of Java. The developer’s kit for Java SE 6 is JDK 6. This is also the JDK used to test all of the code examples. As you may know, beginning with JDK 5, several important new features were added to Java. These include generics, enumerations, and autoboxing. Some of the techniques in this book employ these features. If you are using a version of Java prior to JDK 5, then you will not be able to compile the examples that use these newer features. Therefore, it is strongly recommended that you use a modern version of Java.
CHAPTER 2 Working with Strings and Regular ExpressionsO ne of the most common programming tasks is string handling. Nearly all programs deal with strings in one form or another because they are often the conduit through which we humans interact with digital information. Because of the important partthat string handling plays, Java provides extensive support for it. As all Java programmers know, the primary string class is String. It supplies a wide arrayof string handling methods. Many of these methods provide the basic string operations withwhich most Java programmers are quite familiar. These include methods that compare twostrings, search one string for an occurrence of another, and so on. However, String alsocontains a number of less well-known methods that offer a substantial increase in powerbecause they operate on regular expressions. A regular expression defines a general pattern, nota specific character sequence. This pattern can then be used to search a string for substringsthat match the pattern. This is a powerful concept that is revolutionizing the way that Javaprogrammers think about string handling. Java began providing support for regular expressions in version 1.4. Regular expressionsare supported by the regular expression API, which is packaged in java.util.regex. As justexplained, regular expressions are also supported by several methods in String. With theaddition of regular expressions, several otherwise difficult string handling chores aremade easy. This chapter contains recipes that illustrate various string handling techniques that gobeyond the basic search, compare, and replace operations found in String. Several alsomake use of regular expressions. In some cases, the regular expression capabilities of Stringare employed. Others use the regular expression API itself. Here are the recipes contained in this chapter: • Sort an Array of Strings in Reverse Order • Ignore Case Differences When Sorting an Array of Strings • Ignore Case Differences When Searching for or Replacing Substrings • Split a String into Pieces by Using split( ) • Retrieve Key/Value Pairs from a String 5
6 He rb Sc h i ldt ’s Java P rog ra m m i n g Cookbook • Match and Extract Substrings Using the Regular Expression API • Tokenize a String Using the Regular Expression APIAn Overview of Java’s String Classes A string is a sequence of characters. Unlike some other programming languages, Java does not implement strings as arrays of characters. Rather, it implements strings as objects. This enables Java to define a rich assortment of methods that act on strings. Although strings are familiar territory to most Java programmers, it is still useful to review their key attributes and capabilities. Most strings that you will use in a program are objects of type String. String is part of java.lang. Therefore, it is automatically available to all Java programs. One of the most interesting aspects of String is that it creates immutable strings. This means that once a String is created, its contents cannot be altered. While this may seem like a serious restriction, it is not. If you need to change a string, you simply create a new one that contains the modification. The original string remains unchanged. If the original string is no longer needed, discard it. The unused string will be recycled the next time the garbage collector runs. By using immutable strings, String can be implemented more efficiently than it could be if it used modifiable ones. Strings can be created in a variety of ways. You can explicitly construct a string by using one of String’s constructors. For example, there are constructors that create a String instance from a character array, a byte array, or another string. However, the easiest way to make a string is to use a string literal, which is a quoted string. All string literals are automatically objects of type String. Thus, a string literal can be assigned to a String reference, as shown here: String str = "Test"; This line creates a String object that contains the word "Test" and then assigns to str a reference to that object. String supports only one operator: +. It concatenates two strings. For example, String strA = "Hello"; String strB = " There"; String strC = strA + strB; This sequence results in strC containing the sequence "Hello There". String defines several methods that operate on strings. Since most readers have at least passing familiarity with String, there is no need for a detailed description of all its methods. Furthermore, the recipes in this chapter fully describe the String methods that they employ. However, it is helpful to review String’s core string-handling capabilities by grouping them into categories. String defines the following methods that search the contents of one string for another: contains Returns true if one string contains another. endsWith Returns true if a string ends with a specified string. indexOf Returns the index within a string at which the first occurrence of another string is found. Returns –1 if the string is not found. lastIndexOf Returns the index within the invoking string at which the last occurrence of the specified string is found. Returns –1 if the string is not found. startsWith Returns true if a string starts with a specified string.