You are previewing Java Cookbook, 3rd Edition.
O'Reilly logo
Java Cookbook, 3rd Edition

Book Description

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.

Table of Contents

  1. Preface
    1. Preface to the Third Edition
    2. Preface to Previous Editions
    3. Who This Book Is For
    4. What’s in This Book?
    5. Platform Notes
    6. Java Books
    7. Conventions Used in This Book
    8. Comments and Questions
    9. Acknowledgments
  2. 1. Getting Started: Compiling, Running, and Debugging
    1. Introduction
    2. Compiling and Running Java: JDK
    3. Editing and Compiling with a Syntax-Highlighting Editor
    4. Compiling, Running, and Testing with an IDE
    5. Using CLASSPATH Effectively
    6. Downloading and Using the Code Examples
    7. Automating Compilation with Apache Ant
    8. Automating Dependencies, Compilation, Testing and Deployment with Apache Maven
    9. Automating Dependencies, Compilation, Testing and Deployment with Gradle
    10. Dealing with Deprecation Warnings
    11. Conditional Debugging Without #ifdef
    12. Maintaining Program Correctness with Assertions
    13. Debugging with JDB
    14. Unit Testing: Avoid the Need for Debuggers
    15. Maintaining Your Code with Continuous Integration
    16. Getting Readable Tracebacks
    17. Finding More Java Source Code: Programs, Frameworks, Libraries.
  3. 2. Interacting with the Environment
    1. Introduction
    2. Getting Environment Variables
    3. System Properties
    4. Learning about the current JDK Release
    5. Dealing with Operating-System-Dependent Variations
    6. Using Extensions or Other Packaged APIs
    7. Parsing Command-Line Arguments
  4. 3. Strings and Things
    1. Introduction
    2. Taking Strings Apart with Substrings
    3. Breaking Strings Into Words
    4. Putting Strings Together with <code xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="" class="literal">StringBuilder</code>
    5. Processing a String One Character at a Time
    6. Aligning Strings
    7. Converting Between Unicode Characters and Strings
    8. Reversing a String by Word or by Character
    9. Expanding and Compressing Tabs
    10. Controlling Case
    11. Indenting Text Documents
    12. Entering Nonprintable Characters
    13. Trimming Blanks from the End of a String
    14. Parsing Comma-Separated Data
    15. Program: A Simple Text Formatter
    16. Program: Soundex Name Comparisons
  5. 4. Pattern Matching with Regular Expressions
    1. Introduction
    2. Regular Expression Syntax
    3. Using regexes in Java: Test for a Pattern
    4. Finding the Matching Text
    5. Replacing the Matched Text
    6. Printing All Occurrences of a Pattern
    7. Printing Lines Containing a Pattern
    8. Controlling Case in Regular Expressions
    9. Matching “Accented” or Composite Characters
    10. Matching Newlines in Text
    11. Program: Apache Logfile Parsing
    12. Program: Data Mining
    13. Program: Full Grep
  6. 5. Numbers
    1. Introduction
    2. Checking Whether a String Is a Valid Number
    3. Storing a Larger Number in a Smaller Number
    4. Converting Numbers to Objects and Vice Versa
    5. Taking a Fraction of an Integer Without Using Floating Point
    6. Ensuring the Accuracy of Floating-Point Numbers
    7. Comparing Floating-Point Numbers
    8. Rounding Floating-Point Numbers
    9. Formatting Numbers
    10. Converting Between Binary, Octal, Decimal, and Hexadecimal
    11. Operating on a Series of Integers
    12. Working with Roman Numerals
    13. Formatting with Correct Plurals
    14. Generating Random Numbers
    15. Calculating Trigonometric Functions
    16. Taking Logarithms
    17. Multiplying Matrices
    18. Using Complex Numbers
    19. Handling Very Large Numbers
    20. Program: TempConverter
    21. Program: Number Palindromes
  7. 6. Dates and Times - New API
    1. Introduction
    2. Finding Today’s Date
    3. Formatting Dates and Times
    4. Converting among Dates/Times, YMDHMS, Epoch Seconds
    5. Parsing Strings into Dates
    6. Difference Between Two Dates
    7. Adding to or Subtracting from a Date or Calendar
    8. Interfacing with Legacy <code xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="" class="literal">Date</code> and and <code xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="" class="literal">Calendar</code> Classes Classes
  8. 7. Structuring Data with Java
    1. Introduction
    2. Using Arrays for Data Structuring
    3. Resizing an Array
    4. The Collections Framework
    5. Like an Array, but More Dynamic
    6. Using Generic Collections
    7. Avoid Casting by Using Generics
    8. How Shall I Iterate Thee? Let Me Enumerate The Ways
    9. Eschewing Duplicates with a Set
    10. Using Iterators or Enumerations for Data-Independent Access
    11. Structuring Data in a Linked List
    12. Mapping with Hashtable and HashMap
    13. Storing Strings in Properties and Preferences
    14. Sorting a Collection
    15. Avoiding the Urge to Sort
    16. Finding an Object in a Collection
    17. Converting a Collection to an Array
    18. Rolling Your Own Iterator
    19. Stack
    20. Multidimensional Structures
    21. Program: Timing Comparisons
  9. 8. Object-Oriented Techniques
    1. Introduction
    2. Formatting Objects for Printing with toString( )
    3. Overriding the equals() and hashCode() Methods
    4. Using ShutdownHooks for Application Cleanup
    5. Using Inner Classes
    6. Providing Callbacks via Interfaces
    7. Polymorphism/Abstract Methods
    8. Passing Values
    9. Using Typesafe Enumerations
    10. Enforcing the Singleton Pattern
    11. Roll Your Own Exceptions
    12. Using Dependency Injection
    13. Program: Plotter
  10. 9. Functional Programming Techniques: Functional Interfaces, Streams, Spliterators, Parallel Collections
    1. Introduction
    2. Using Lambdas/Closures Instead of Inner Classes
    3. Using Lambda Pre-defined Interfaces Instead of Your Own
    4. Simplifying Processing with Streams
    5. Improving Throughput with Parallel Streams and Collections
    6. Creating Your Own Functional Interfaces
    7. Using Existing Code as Functional with Method References
    8. Java Mixins - Mixing In Methods
  11. 10. Input and Output
    1. Introduction
    2. Reading Standard Input
    3. Reading from the Console or Controlling Terminal; Reading Passwords Without Echoing
    4. Writing Standard Output or Standard Error
    5. Printing with <code xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="" class="literal">Formatter</code> and and <code xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="" class="literal">printf</code>
    6. Scanning Input with StreamTokenizer
    7. Scanning Input with the Scanner Class
    8. Scanning Input with Grammatical Structure
    9. Opening a File by Name
    10. Copying a File
    11. Reading a File into a String
    12. Reassigning the Standard Streams
    13. Duplicating a Stream as It Is Written
    14. Reading/Writing a Different Character Set
    15. Those Pesky End-of-Line Characters
    16. Beware Platform-Dependent File Code
    17. Reading “Continued” Lines
    18. Reading/Writing Binary Data
    19. Seeking
    20. Writing Data Streams from C
    21. Saving and Restoring Java Objects
    22. Preventing ClassCastExceptions with SerialVersionUID
    23. Reading and Writing JAR or Zip Archives
    24. Finding files in a Filesystem-Neutral Way with <code xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="" class="literal">getResource()</code> and and <code xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="" class="literal">getResourceAsStream()</code>
    25. Reading and Writing Compressed Files
    26. Learning about the Communications API for Serial and Parallel Ports
    27. Save User Data to Disk
    28. Program: Text to PostScript
  12. 11. Directory and Filesystem Operations
    1. Introduction
    2. Getting File Information
    3. Creating a File
    4. Renaming a File
    5. Deleting a File
    6. Creating a Transient File
    7. Changing File Attributes
    8. Listing a Directory
    9. Getting the Directory Roots
    10. Creating New Directories
    11. Using <code xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="" class="literal">Path</code> instead of instead of <code xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="" class="literal">File</code>
    12. Using the FileWatcher Service to get notified about File Changes
    13. Program: Find
  13. 12. Media: Graphics, Audio, Video
    1. Introduction
    2. Painting with a Graphics Object
    3. Showing Graphical Components Without Writing Main
    4. Drawing Text
    5. Drawing Centered Text in a Component
    6. Drawing a Drop Shadow
    7. Drawing Text with 2D
    8. Drawing Text with an Application Font
    9. Drawing an Image
    10. Reading and Writing Images with javax.imageio
    11. Playing an Audio/Sound File
    12. Playing a Video File
    13. Printing in Java
    14. Program: PlotterAWT
    15. Program: Grapher
  14. 13. Graphical User Interfaces
    1. Introduction
    2. Displaying GUI Components
    3. Run your GUI on the Event Dispatching Thread
    4. Designing a Window Layout
    5. A Tabbed View of Life
    6. Action Handling: Making Buttons Work
    7. Action Handling Using Anonymous Inner Classes
    8. Action Handling Using Lambdas
    9. Terminating a Program with “Window Close”
    10. Dialogs: When Later Just Won’t Do
    11. Catching and Formatting GUI Exceptions
    12. Getting Program Output into a Window
    13. Choosing a Value with JSpinner
    14. Choosing a File with JFileChooser
    15. Choosing a Color
    16. Formatting JComponents with HTML
    17. Centering a Main Window
    18. Changing a Swing Program’s Look and Feel
    19. Enhancing Your Swing GUI for Mac OS X
    20. Program: Custom Font Chooser
    21. Building your GUI Application with JavaFX
    22. Program: Custom AWT/Swing Layout Manager
  15. 14. Internationalization and Localization
    1. Introduction
    2. Creating a Button with I18N Resources
    3. Listing Available Locales
    4. Creating a Menu with I18N Resources
    5. Writing Internationalization Convenience Routines
    6. Creating a Dialog with I18N Resources
    7. Creating a Resource Bundle
    8. Extracting Strings from Your Code
    9. Using a Particular Locale
    10. Setting the Default Locale
    11. Formatting Messages with <code xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="" class="literal">MessageFormat</code>
    12. Program: MenuIntl
    13. Program: BusCard
  16. 15. Network Clients
    1. Introduction
    2. Contacting a Server
    3. Finding and Reporting Network Addresses
    4. Handling Network Errors
    5. Reading and Writing Textual Data
    6. Reading and Writing Binary Data
    7. Reading and Writing Serialized Data
    8. UDP Datagrams
    9. Program: TFTP UDP Client
    10. URI, URL, or URN?
    11. REST Web Service Client
    12. SOAP Web Service Client
    13. Program: Telnet Client
    14. Program: Chat Client
    15. Program: Simple HTTP Link Checker
  17. 16. Server-Side Java
    1. Introduction
    2. Opening a Server Socket for Business
    3. Returning a Response (String or Binary)
    4. Returning Object Information Across a Network Connection
    5. Handling Multiple Clients
    6. Serving the HTTP Protocol
    7. Securing a Web Server with SSL and JSSE
    8. Network Logging
    9. Network Logging with SLF4J
    10. Network Logging with log4j
    11. Network Logging with <code xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="" class="literal">java.util.logging</code>
    12. Finding Network Interfaces
    13. Program: A Java Chat Server
  18. 17. Java and Electronic Mail
    1. Introduction
    2. Sending Email: Browser Version
    3. Sending Email: For Real
    4. Mail-Enabling a Server Program
    5. Sending MIME Mail
    6. Providing Mail Settings
    7. Reading Email
    8. Program: MailReaderBean
    9. Program: MailClient
  19. 18. Database Access
    1. Introduction
    2. Easy Database Access with JPA and/or Hibernate
    3. JDBC Setup and Connection
    4. Connecting to a JDBC Database
    5. Sending a JDBC Query and Getting Results
    6. Using JDBC Prepared Statements
    7. Using Stored Procedures with JDBC
    8. Changing Data Using a ResultSet
    9. Storing Results in a RowSet
    10. Changing Data Using SQL
    11. Finding JDBC Metadata
    12. Program: SQLRunner
  20. 19. Processing JSON Data
    1. Introduction
    2. Generating JSON directly
    3. Parsing and Writing JSON with Jackson
    4. Parsing and Writing JSON with org.json
  21. 20. Processing XML
    1. Introduction
    2. Converting between Objects and XML with JAXB
    3. Converting between Objects and XML with Serializers
    4. Transforming XML with XSLT
    5. Parsing XML with SAX
    6. Parsing XML with DOM
    7. Finding XML Elements with XPath
    8. Verifying Structure with Schema or DTD
    9. Generating Your Own XML with DOM and the XML Tranformer
    10. Program: xml2mif
  22. 21. Packages and Packaging
    1. Introduction
    2. Creating a Package
    3. Documenting Classes with Javadoc
    4. Beyond Javadoc: Annotations/Metadata
    5. Archiving with jar
    6. Running a Program from a JAR
    7. Preparing a Class as a JavaBean
    8. Pickling Your Bean into a JAR
    9. Packaging a Servlet into a WAR File
    10. “Write Once, Install Anywhere”
    11. “Write Once, Install on Mac OS X”
    12. Java Web Start
    13. Signing Your JAR File
  23. 22. Threaded Java
    1. Introduction
    2. Running Code in a Different Thread
    3. Displaying a Moving Image with Animation
    4. Stopping a Thread
    5. Rendezvous and Timeouts
    6. Synchronizing Threads with the synchronized Keyword
    7. Simplifying Synchronization with Locks
    8. Synchronizing Threads with wait( ) and notifyAll( )
    9. Simplifying Producer-Consumer with the Queue Interface
    10. Optimizing Parallel Processing with Fork/Join
    11. Background Saving in an Editor
    12. Program: Threaded Network Server
    13. Simplifying Servers Using the Concurrency Utilities
  24. 23. Reflection, or “A Class Named Class”
    1. Introduction
    2. Getting a Class Descriptor
    3. Finding and Using Methods and Fields
    4. Accessing Private Methods and Fields via Reflection
    5. Loading and Instantiating a Class Dynamically
    6. Constructing a Class from Scratch With A ClassLoader
    7. Performance Timing
    8. Printing Class Information
    9. Listing Classes in a Package
    10. Using and Defining Annotations
    11. Finding Plugin-like Classes via Annotations
    12. Program: CrossRef
    13. Program: AppletViewer
  25. 24. Using Java with Other Languages
    1. Introduction
    2. Running an External Program From Java
    3. Running a Program and Capturing Its Output
    4. Calling Other Languages via <code xmlns="" xmlns:epub="" xmlns:m="" xmlns:pls="" xmlns:ssml="" xmlns:svg="" class="literal">javax.script</code>
    5. Roll Your Own Scripting Engine
    6. Marrying Java and Perl
    7. Calling Other Languages via Native Code
    8. Calling Java from Native Code
  26. Afterword
  27. A. Java Then and Now
    1. Introduction: Always In Motion The Java Is
    2. Java Preview: HotJava
    3. Java Arrives: 1.0
    4. What Was New In Java 1.1
    5. What Was New In Java 2 (Java SDK 1.2)
    6. What Was New In Java 1.3
    7. What Was New In Java 1.4
    8. What Was New In Java 5
    9. What Was New In Java 6
    10. What Was New In Java 7
    11. What Is New In Java 8
    12. Look Away Beyond the Blue Horizon…
  28. About the Author
  29. Copyright