Java Cookbook: Solutions and Examples for Java Developers

Java Cookbook: Solutions and Examples for Java Developers

by Ian F. Darwin

Paperback(Third Edition)

$59.99 View All Available Formats & Editions
Eligible for FREE SHIPPING
  • Get it by Wednesday, March 21 , Order now and choose Expedited Delivery during checkout.
    Same Day delivery in Manhattan. 


Java Cookbook: Solutions and Examples for Java Developers by Ian F. Darwin

From lambda expressions and JavaFX 8 to new support for network programming and mobile development, Java 8 brings a wealth of changes. This cookbook helps you get up to speed right away with hundreds of hands-on recipes across a broad range of Java topics. You’ll learn useful techniques for everything from debugging and data structures to GUI development and functional programming.

Each recipe includes self-contained code solutions that you can freely use, along with a discussion of how and why they work. If you are familiar with Java basics, this cookbook will bolster your knowledge of the language in general and Java 8’s main APIs in particular.

Recipes include:

  • Methods for compiling, running, and debugging
  • Manipulating, comparing, and rearranging text
  • Regular expressions for string- and pattern-matching
  • Handling numbers, dates, and times
  • Structuring data with collections, arrays, and other types
  • Object-oriented and functional programming techniques
  • Directory and filesystem operations
  • Working with graphics, audio, and video
  • GUI development, including JavaFX and handlers
  • Network programming on both client and server
  • Database access, using JPA, Hibernate, and JDBC
  • Processing JSON and XML for data storage
  • Multithreading and concurrency

Product Details

ISBN-13: 9781449337049
Publisher: O'Reilly Media, Incorporated
Publication date: 07/18/2014
Edition description: Third Edition
Pages: 898
Sales rank: 689,361
Product dimensions: 9.10(w) x 7.00(h) x 1.90(d)

About the Author

Ian F. Darwin has worked in the computer industry for three decades. He wrote the freeware file(1) command used on Linux and BSD and is the author of Checking C Programs with Lint, Java Cookbook, and over seventy articles and courses on C and Unix. In addition to programming and consulting, Ian teaches Unix, C, and Java for Learning Tree International, one of the world's largest technical training companies.

Read an Excerpt

Chapter 18: Web Server Java: Servlets and JSP


This chapter covers Web Server Java, but you won't find anything about writing CGI programs in Java here. Although it would be entirely possible to do so, it would not be efficient. The whole notion of CGI programs is pretty much passe. Every time a CGI program is invoked, the web server has to create a new heavyweight process in which to run it; this is inefficient. If it's interpreted in Java, the program has to be translated into machine code each time; this is even more inefficient.

Today's trend is toward building functionality into the web server: Microsoft ASP, PHP3, Java servlets, and JavaServer Pages? (JSP1) are examples of this. None of these normally requires a separate process to be created for each request; the Java-based solutions run in a thread (see Chapter 24) inside the web server, and the Java bytecode need only be translated into machine code once in a long while, assuming a just-in-time (JIT) runtime system. Naturally, this book concentrates on the Java solutions.

We'll use two examples in this chapter. Consider the task of displaying a web page with five randomly chosen integer numbers (lottery players love this sort of thing). The Java code you need is simple:

// Part of file netweb/servlets_jsp/ 
Random r = new Random(  ); 
for (int i=0; i<5; i++) 
	System.out.println(r.nextInt(  )); 

But of course you can't just run that and save its output into an HTML file because you want each person seeing the page to get a different set of numbers. If you wanted to mix that into a web page, you'd have to write code to println( ) a bit of HTML. This would be a Java servlet.

The servlet code could get messy, however, since you'd have to escape double quotes inside strings. Worse, if the webmaster wanted to change the HTML, he'd have to approach the programmer's sanctified source code and plead to have it changed. Imagine if you could give the webmaster a page containing a bit of HTML and the Java code you need, and have it magically compiled into Java whenever the HTML was changed. Imagine no longer, says the marketer, for that capability is here now, with JavaServer Pages.

The second example is a dictionary (list of terms); I'll present this both as a servlet and as a JSP.

I won't talk about how you get your servlet engine installed, nor exactly how you install your servlet. If you don't already have a servlet engine, though, I'd recommend downloading Tomcat from Tomcat is the official reference implementation--so designated by Sun--for the servlet and JSP standard. It is also (as you can infer from the URL) the official servlet engine for the ever-popular Apache web server.

First Servlet: Generating an HTML Page


You want a servlet to present some information to the user.


Override the HttpServlet method service( ), or doGet( )/doPost( ).


The abstract class javax.servlet.Servlet is designed for those who wish to structure an entire web server around the servlet notion. For example, in Sun's Java Web Server, there is a servlet subclass for handling plain HTML pages, another for processing CGI programs, and so on. Unless you are writing your own web server, you will probably not extend from this class, but rather its subclass HttpServlet, in the package javax.servlet.http. This class has a method:

public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException; 

The service method is passed two arguments, request and response. The request contains all the information about the request from the browser, including its input stream should you need to read data. The response argument contains information to get the response back to the browser, including the output stream to write your response back to the user.

But the web has several HTTP methods for passing data into a web page. Unimportant for plain HTML pages, this distinction becomes of interest when processing forms, i.e., web pages with fill-in-the-blank or choice items. Briefly, the GET method of HTTP is used to pass all the form data appended to the URL. GET URLs look like this, for example: 

They have the advantage that the user can bookmark them, avoiding having to fill in the form multiple times. But there is a limit of about 1KB on the overall length of the URL. Since this must be a single string, there is an encoding that allows spaces, tabs, colons, and other characters to be presented as two hexadecimal digits: %20 is the character hexadecimal 20, or the ASCII space character. The POST method, by contrast, passes any parameters as input on the socket connection, after the HTTP headers.

The default implementation of the service( ) method in the HttpServlet class figures out which method was used to invoke the servlet. It dispatches to the correct method: doGet( ) if a GET request, doPost( ) if a POST request, etc., passing along the request and response arguments. So while you can, in theory, override the service( ) method, it's more common (and officially recommended) to override either doGet( ), doPost( ), or both.

The simplest HttpServlet is something like Example 18-1....

Table of Contents

1: Getting Started: Compiling, Running, and Debugging
Compiling and Running Java: JDK
Editing and Compiling with a Color-Highlighting Editor
Compiling, Running, and Testing with an IDE
Using Classes from This Book
Automating Compilation with jr
Automating Compilation with make
Automating Compilation with Ant
Running Applets
Dealing with Deprecation Warnings
Conditional Debugging without #ifdef
Debugging Printouts
Using a Debugger
Unit Testing: Avoid the Need for Debuggers
Decompiling Java Class Files
Preventing Others from Decompiling Your Java Files
Getting Readable Tracebacks
Finding More Java Source Code
Program: Debug

2: Interacting with the Environment
Getting Environment Variables
System Properties
Writing JDK Release-Dependent Code
Writing Operating System-Dependent Code
Using CLASSPATH Effectively
Using Extensions or Other Packaged APIs
Parsing Command-Line Arguments

3: Strings and Things
Taking Strings Apart with Substrings
Taking Strings Apart with StringTokenizer
Putting Strings Together with + and StringBuffer
Processing a String One Character at a Time
Aligning Strings
Converting Between Unicode Characters and Strings
Reversing a String by Word or Character
Expanding and Compressing Tabs
Controlling Case
Indenting Text Documents
Entering Non-Printable Characters
Trimming Blanks from the End of a String
Parsing Comma-Separated Data
Program: A Simple Text Formatter
Program: Soundex Name Comparisons

4: Pattern Matching with Regular Expressions
Regular Expression Syntax
How REs Work in Practice
Using Regular Expressions in Java
Testing REs Interactively
Finding the Matching Text
Replacing the Matching Text
Printing All Occurrences of a Pattern
Printing Lines Containing a Pattern
Controlling Case in match( ) and subst( )
Precompiling the RE
Matching Newlines in Text
Program: Data Mining
Program: Full Grep

5: Numbers
Checking Whether a String Is a Valid Number
Storing a Larger Number in a Smaller
Taking a Fraction of an Integer Without Using Floating Point
Ensuring the Accuracy of Floating-Point Numbers
Comparing Floating-Point Numbers
Rounding Floating-Point Numbers
Formatting Numbers
Converting Between Binary, Octal, Decimal, and Hexadecimal
Operating on a Series of Integers
Working with Roman Numerals
Formatting with Correct Plurals
Generating Random Numbers
Generating Better Random Numbers
Calculating Trigonometric Functions
Taking Logarithms
Multiplying Matrixes
Using Complex Numbers
Handling Very Large Numbers
Program: TempConverter
Program: Number Palindromes

6: Dates and Times
Finding Today's Date
Printing Date/Time in a Specified Format
Representing Dates in Other Epochs
Converting YMDHMS to a Calendar or Epoch Seconds
Parsing Strings into Dates
Converting Epoch Seconds to DMYHMS
Adding to or Subtracting from a Date or Calendar
Difference Between Two Dates
Comparing Dates
Day of Week/Month/Year or Week Number
Calendar Page
High-Resolution Timers
Sleeping for a While
Program: Reminder Service

7: Structuring Data with Java
Data Structuring Using Arrays
Resizing an Array
Like an Array, but More Dynamic
Data-Independent Access with Iterators
Structuring Data in a Linked List
Mapping with Hashtable and HashMap
Storing Strings in Properties and Preferences
Sorting a Collection
Sorting in Java 1.1
Avoiding the Urge to Sort
Finding an Object in a Collection
Converting a Collection to an Array
Rolling Your Own Iterator
Multidimensional Structures
Finally, Collections
Program: Timing Comparisons

8: Object-Oriented Techniques
Printing Objects: Formatting with toString( )
Overriding the Equals Method
Overriding the Hashcode Method
The Clone Method
The Finalize Method
Using Inner Classes
Providing Callbacks via Interfaces
Polymorphism/Abstract Methods
Passing Values
Roll Your Own Exceptions
Program: Plotter

9: Input and Output
Reading Standard Input
Writing Standard Output
Opening a File by Name
Copying a File
Reading a File into a String
Reassigning the Standard Streams
Duplicating a Stream as It Is Written
Reading/Writing a Different Character Set
Those Pesky End-of-Line Characters
Beware Platform-Dependent File Code
Reading "Continued" Lines
Scanning a File
Binary Data
Writing Data Streams from C
Saving and Restoring Serialized Objects
Preventing ClassCastExceptions with SerialVersionUID
Reading and Writing JAR or Zip Archives
Reading and Writing Compressed Files
Program: Text to PostScript
Program: TarList (File Converter)

10: Directory and Filesystem Operations
Getting File Information
Creating a File
Renaming a File
Deleting a File
Creating a Transient File
Changing File Attributes
Listing a Directory
Getting the Directory Roots
Making New Directories
Program: Find

11: Programming Serial and Parallel Ports
Choosing a Port
Opening a Serial Port
Opening a Parallel Port
Resolving Port Conflicts
Reading and Writing: Lock Step
Reading and Writing: Event-Driven
Reading and Writing: Threads
Program: Penman Plotter

12: Graphics and Sound
Painting with a Graphics Object
Testing Graphical Components
Drawing Text
Drawing Centered Text in a Component
Drawing a Drop Shadow
Drawing an Image
Playing a Sound File
Displaying a Moving Image with Video
Drawing Text with 2D
Printing: JDK 1.1 Printing: Java 2
Program: PlotterAWT
Program: Grapher

13: Graphical User Interfaces
Displaying GUI Components
Designing a Window Layout
A Tabbed View of Life
Action Handling: Making Buttons Work
Action Handling Using Anonymous Inner Classes
Terminating a Program with "Window Close"
Dialogs: When Later Just Won't Do
Getting Program Output into a Window
Choosing a File with JFileChooser
Choosing a Color
Centering a Main Window
Changing a Swing Program's Look and Feel
Program: Custom Font Chooser
Program: Custom Layout Manager

14: Internationalization and Localization
Creating a Button with I18N Resources
Listing Available Locales
Creating a Menu with I18N Resources
Writing Internationalization Convenience Routines
Creating a Dialog with I18N Resources
Creating a Resource Bundle
JILTing Your Code
Using a Particular Locale
Setting the Default Locale
Formatting Messages
Program: MenuIntl
Program: BusCard

15: Network Clients
Contacting a Server
Finding and Reporting Network Addresses
Handling Network Errors
Reading and Writing Textual Data
Reading and Writing Binary Data
Reading and Writing Serialized Data
UDP Datagrams
Program: TFTP UDP Client
Program: Telnet Client
Program: Chat Client

16: Server-Side Java: Sockets
Opening a Server for Business
Returning a Response (String or Binary)
Returning Object Information
Handling Multiple Clients
Network Logging
Program: A Java Chat Server

17: Network Clients II: Applets and Web Clients
Embedding Java in a Web Page
Applet Techniques
Contacting a Server on the Applet Host
Making an Applet Show a Document
Making an Applet Run a CGI Script
Reading the Contents of a URL
Extracting HTML from a URL
Extracting URLs from a File
Converting a Filename to a URL
Program: MkIndex
Program: LinkChecker

18: Web Server Java: Servlets and JSP
First Servlet: Generating anHTML Page
Servlets: Processing Form Parameters
Session Tracking
Generating PDF from a Servlet
HTML Meets Java: JSP
JSP Include/Forward
JavaServer Pages Using a Servlet
Simplifying Your JSP with a JavaBean
JSP Syntax Summary
Program: CookieCutter
Program: JabaDot Web News Portal

19: Java and Electronic Mail
Sending Email: Browser Version
Sending Email: For Real
Mail-Enabling a Server Program
Sending MIME Mail
Providing Mail Settings
Sending Mail Without Using JavaMail
Reading Email
Program: MailReaderBean
Program: MailClient

20: Database Access
Text-File Databases
DBM Databases
JDBC Setup and Connection
Connecting to a JDBC Database
Sending a JDBC Query and Getting Results
Using JDBC Parameterized Statements
Using Stored Procedures with JDBC
Changing Data Using a ResultSet
Changing Data Using SQL
Finding JDBC Metadata
Program: JDAdmin

21: XML
Transforming XML with XSLT
Parsing XML with SAX
Parsing XML with DOM
Verifying Structure with a DTD
Generating Your Own XML with DOM
Program: xml2mif

22: Distributed Java: RMI
Defining the RMI Contract
RMI Client
RMI Server
Deploying RMI Across a Network
Program: RMI Callbacks
Program: RMIWatch

23: Packages and Packaging
Creating a Package
Documenting Classes with Javadoc
Archiving with jar
Running an Applet from a JAR
Running an Applet with a JDK
Running a Program from a JAR
Preparing a Class as a JavaBean
Pickling Your Bean into a JAR
Packaging a Servlet into a WAR File
"Write Once, Install Anywhere"
Java Web Start
Signing Your JAR File

24: Threaded Java
Running Code in a Different Thread
Displaying a Moving Image with Animation
Stopping a Thread
Rendezvous and Timeouts
Thread Communication: Synchronized Code
Thread Communication: wait( ) and notifyAll( )
Background Saving in an Editor
Threaded Network Server

25: Introspection, or "A Class Named Class"
Getting a Class Descriptor
Finding and Using Methods and Fields
Loading and Instantiating a Class Dynamically
Constructing a Class from Scratch
Performance Timing
Printing Class Information
Program: CrossRef
Program: AppletViewer

26: Using Java with Other Languages
Running a Program
Running a Program and Capturing Its Output
Mixing Java and Scripts with BSF
Blending in Native Code (C/C++)
Calling Java from Native Code
Program: DBM


Customer Reviews

Most Helpful Customer Reviews

See All Customer Reviews