You are previewing Just Java™ 2, Fifth Edition.
O'Reilly logo
Just Java™ 2, Fifth Edition

Book Description

  • Java programming language and basic packages

  • Server-side libraries and enterprise development

  • Networking, Beans, and collections

  • GUI components and more

  • Covers Java 2 platform (JDK 1.4 release) and enterprise/server-side development.

    An international bestseller for over 5 years, Just Java 2 is the most comprehensive and accessible tutorial for programmers at all levels. Completely updated and revised, the 5th edition is not only a readable and engaging overview of the Java 2 platform (JDK 1.4 release) and its libraries, it is also a practical introduction to today's best enterprise and server-side programming techniques.

    Writing for real programmers, author Peter van der Linden delivers expert advice, clear explanations and challenging examples, along with his popular "light relief" sidebars and wry commentary on the computer industry.

    Just Java 2 covers:

  • The core language: advantages, syntax, object-oriented features, and key techniques-including interfaces, threads, assert statements, and much more

  • Key Java libraries: Input/output, from the basics to cutting-edge pattern matching, file locking, and mapped I/O techniques-plus a full chapter data structures and collections

  • Server-side Java technology: Powerful techniques for building Web-based transaction systems and Web services: servlets, Java Server Pages(tm), RMI, object serialization, and more

  • Client-side Java technology: Up-to-the-minute coverage of JFC(tm)/Swing GUI development, applet techniques, games code, containers, layouts, and graphics programming

  • Enterprise Java technology: J2EE(tm) platform-capabilities, benefits, and techniques! Including a database introduction, JDBC(tm) API tutorial, basics of EJB(tm) architecture, Java platform security, and a brand-new chapter on XML

  • CD-ROM INCLUDES

  • Browse the CD with your Web browser to run the applets and to get easy access to the contents

  • Tons of great software, including Perl, GNU C/C++, Python, games, and more

  • Extensive code examples from top programmers around the world

  • The complete programmer's FAQ

  • Table of Contents

    1. Copyright
      1. Dedication
    2. Acknowledgments
    3. Using the Just Java CD-ROM
      1. About the CD-ROM
        1. Running the Java Tools
    4. I. Language
      1. 1. What Is Java?
        1. Compiling and Executing a Sample Program
        2. The Biggest Java Benefit: Future-Proofing
          1. Why Software Portability Matters
          2. J2EE, J2ME, J2SE Editions
        3. Java Virtual Machine
        4. The “Java Platform”
        5. The Java Language
        6. Java Libraries
          1. How New Libraries are Developed
        7. Three Execution Environments
          1. Applets
          2. Server-Side Java
        8. Some Light Relief—A Java Desktop Application
      2. 2. The Story of O: Object-Oriented Programming
        1. Abstraction
        2. Encapsulation
        3. Comparing Primitive Types to Class Types
          1. Defining a Type
          2. Declaring Variables
          3. Newsflash: Object vs. Reference to an Object!
          4. Operations on Primitive Types/Methods on Objects
        4. The One-Minute Object Manager
        5. Creating New Objects: Constructors
          1. A First Glimpse at Inheritance
          2. How Constructors Are Invoked
          3. No Destructors
          4. Methods
          5. You Always Get to an Object with a “Reference Variable”
          6. The “null” Reference
          7. Dynamic Data Structures
        6. Per-Instance and Per-Class Members
          1. Static Data
          2. Static Methods
          3. Static Blocks
          4. Static Classes
        7. The “final” Modifier
          1. The “Blank Final Variable”
        8. Access Modifiers
        9. Exercises
        10. Some Light Relief—It’s Not Your Father’s IBM
      3. 3. Explanation of a Sample Program
        1. Explanation of the Example Program
          1. Applications vs. Applets vs. Servlets
        2. Where an Application Starts
        3. Runtime Internals: Stack and Heap
        4. The Class “Object”
        5. Reading the Java API
        6. Some Light Relief—Napster and LimeWire
      4. 4. Identifiers, Keywords, and Types
        1. Java and Unicode
        2. Scanning
        3. Identifiers
        4. Comments
        5. Keywords
          1. Used for built-in types:
          2. Used for objects:
          3. Used in statements:
          4. Used to modify declarations (visibility, sharing, etc.):
          5. Used for other method or class-related purposes:
          6. Used for larger-than-a-single-class building blocks:
          7. Reserved for possible future use:
        6. The Primitive Types
          1. boolean
          2. int
          3. long
          4. byte
          5. short
          6. double
          7. float
          8. char
          9. String
        7. String Concatenation
        8. String Comparison and intern()
        9. Some Light Relief—Hatless Atlas
      5. 5. Names, Arrays, Operators, and Accuracy
        1. Names
          1. When Can an Identifier Be Forward-Referenced?
        2. Expressions
        3. Arrays
          1. Creating an Array
          2. Initializing an Array
          3. Arrays of Arrays of …
          4. Have Array Brackets, Will Travel
        4. Operators
          1. Java Operators
          2. The ++ and -Operators
          3. The % and / Operators
          4. The << >> and >>> Operators
          5. The instanceof Operator
          6. The & | and ^ Operators
          7. The && and || Operators
          8. The ? ... : Operator
          9. The Assignment Operators
          10. The Comma Operator Is Gone
        5. Associativity
        6. How Accurate Are Calculations?
          1. Floating-Point Extension
        7. Widening and Narrowing Conversions
        8. What Happens on Overflow?
          1. Integer Overflow
          2. Floating Point Overflow
          3. Arithmetic That Cannot Overflow
        9. The Math Package
        10. Further Reading
        11. Some Light Relief—Too Much Bread
      6. 6. More OOP—Extending Classes
        1. Inheritance
          1. A Java Example of Inheritance
          2. What Happens When Names Collide?
          3. Compatibility of Superclass and Subclass
          4. Casting
        2. Polymorphism
          1. Overloading
          2. Overriding
          3. Inheriting from Object
          4. Forcing Overriding off: Final
          5. Forcing Overriding: Abstract
        3. The Class Whose Name Is Class
        4. Exercises
        5. Some Light Relief—The Nerd Detection System
      7. 7. Java Statements
        1. “Organizing” Statements
        2. Expression Statements
        3. Selection Statements
          1. Statement Notes
          2. Statement Notes
        4. Iteration Statements
          1. Statement Notes
          2. Statement Notes
          3. Statement Notes
        5. Transfer of Control Statements
          1. Statement Notes
        6. Exceptions
          1. The Purpose of Exceptions
          2. How to Cause an Exception (Implicitly and Explicitly)
          3. Triggering an Exception
          4. How to Handle (“Catch”) an Exception Within the Method Where It Was Thrown
          5. Handling Groups of Related Exceptions
          6. How the Exception Propagates If Not Handled in the Method Where It Was Thrown
          7. How and Why Methods Declare the Exceptions That Can Propagate Out of Them
          8. Fancy Exception Stuff
          9. Summary of Exceptions
        7. The Assert Statement
        8. Further Reading
        9. Exercises
        10. Some Light Relief—MiniScribe: The Hard Luck Hard Disk
      8. 8. Interfaces
        1. What Problem Does an Interface Solve?
        2. Comparable
          1. Interfaces vs. Abstract Classes
          2. Granting Permission Through an Interface—Cloneable
        3. What Protected Really Means
          1. Interfaces in the Java Runtimes
        4. Call Backs
          1. Using Inter faces for Named Constants
          2. The Class Double
        5. Exercises
        6. Some Light Relief—The Odyssey of Naming Hal
      9. 9. Packages and Visibility
        1. What Are Packages For?
          1. How to Choose a Package Name
        2. How the JVM Finds Classes
          1. Putting the Jar File Where Java Will Find It
          2. Telling Java Where to Look for the Jar File or Package Roots
        3. Packages and Access Modifiers
          1. Access Between Two Classes in the Same Package
          2. Access Between Two Unrelated Classes in Different Packages
          3. Access Between a Parent and Child Class in Different Packages
          4. How Many Packages in a Directory?
        4. Compilation Units
          1. Import
        5. Nested Classes
          1. Nested Static Classes
          2. Member Classes
          3. Local Classes
          4. Anonymous Classes
          5. How Inner Classes Are Compiled
        6. The Class Character
          1. Java Coding Style
        7. Exercises
        8. Some Light Relief—The Domestic Obfuscated Java Code Non-Competition
      10. 10. Doing Several Things at Once: Threads
        1. What Are Threads?
        2. Two Ways to Obtain a New Thread
          1. A Few Words on Runnable
        3. The Lifecycle of a Thread
          1. Priorities
        4. Thread Groups
        5. Four Kinds of Threads Programming
          1. Unrelated Threads
          2. Related but Unsynchronized Threads
        6. Some Light Relief—The Motion Sensor Solution
      11. 11. Advanced Thread Topics
        1. More Thread Programming
          1. Mutually-Exclusive Threads
          2. Communicating Mutually-Exclusive Threads
          3. Interrupting a Thread
        2. Piped I/O for Threads
          1. Thread Local Storage
        3. Garbage Collection
          1. Why Do We Need Garbage Collection?
          2. Garbage Collection Algorithms
          3. Finalizers
          4. Weak References
        4. Design Patterns
        5. Further Reading
        6. Exercises
        7. Some Light Relief—Are You Certifiable?
          1. Sun Certified Java Programmer
      12. 12. Practical Example Explained
        1. Case Study Java Program: Fritter Engine Shunt
        2. Exercises
        3. Some Light Relief—Apple Armchair Advice
    5. II. Key Libraries
      1. 13. Simple Input Output
        1. Design Philosophy
        2. File and FileDescriptor Classes
          1. Public members of java.io.File
          2. FileDescriptor
          3. Portability of I/O
        3. Output
        4. Outputting Double-byte Characters
          1. Wrapping a Writer
          2. Methods of java.io.PrintWriter
        5. Other Writer Wrappers
          1. A Filter to Replace Chars
          2. A Class that Uses a Filter
          3. Summary of Writers
        6. Outputting ASCII Characters and Binary Values
          1. Basic OutputStream Methods
          2. java.io.DataOutputStream for Binary Output
          3. java.io.PrintStream for Printable Output
          4. System.in, out, and err
          5. Writing a Binary File
          6. Output Stream Wrappers
          7. Example of Outputting a Zip File
          8. Writing a Zip Archive
          9. Summary of Output Streams
        7. Input
          1. Inputting Double Byte Characters
          2. Basic Reader Methods
          3. An Input Problem Rears Its Ugly Head
        8. Reader Wrappers
          1. Classes That Wrap Readers
        9. Inputting ASCII Characters and Binary Values
          1. Basic InputStream Methods
          2. Methods of java.io.DataInputStream
          3. A Word About IOExceptions
          4. Example
        10. Input Stream Wrappers
          1. GZIP Files and Streams
          2. Suggested Use of Input Streams
        11. Further Reading
        12. Exercises
        13. Some Light Relief—The Illegal Prime Number!
          1. Converting a Number to Binary and Writing to a File
      2. 14. Advanced Input Output
        1. Random Access File
          1. class java.io.RandomAccessFile
        2. Reading from the Keyboard
        3. Running Commands and Getting Output from Them
          1. Executing the Attrib Command from Java
          2. Limitations on Running Processes
        4. Formatted String Output
          1. How Many Digits Are Output?
          2. You Can Also Format Dates
        5. Writing Objects to Disk
          1. Serializing and Security
          2. XML Support Class
        6. New I/O Package
          1. Multiplexed Non-blocking Server I/O
          2. Recovering from Blocked Server I/O
          3. Getting and Using a File Channel
          4. Buffers
          5. Read a File Using a Channel and a Buffer
          6. Other Buffer Methods
          7. View Buffers
          8. A Bulk Transfer from a Buffer to an int Array
        7. Memory Mapped I/O
          1. Mapped I/O Example import java.io.*;
        8. File Locking
        9. Charsets and Endian-ness
          1. Big-endian Storage
          2. Little-endian storage
          3. Supported Encodings
          4. Using a Specific Character Set
          5. Byte-Swapping Binary Data
          6. Summary of Charsets
        10. Exercises
        11. Some Light Relief—The Illegal T-Shirt!
      3. 15. Regular Expressions , Collections , Utilities
        1. Regular Expressions and Pattern Matching
          1. Matching a Pattern
          2. Forming Patterns
          3. Range
          4. Single-Character Metacharacters
          5. Quantifiers
          6. Capturing Groups and Back References
          7. Anchors
          8. Alternation
          9. Word Negation
          10. Metawords
          11. Java Grep Program
        2. Collections API
          1. Adding to a Collection
          2. public interface Iterator
          3. List, LinkedList, and ArrayList
          4. Comparable and Comparator
          5. The Collections Helper Class
          6. Set, HashSet, and SortedSet
            1. Summary of Collections.
          7. Map, HashMap, and TreeMap
          8. HashMap Implements Map
        3. Other Utility Classes
          1. Stack
        4. The java.math API
        5. Calendar Utilities
          1. Calendar and GregorianCalendar
        6. Other Utilities
          1. Random
          2. StringTokenizer
          3. Observer and Observable
          4. Properties
          5. java.util.Properties
          6. Note on the Java Native Interface
        7. Further Reading
        8. Exercises
        9. Some Light Relief—Exchanging Apples and Crays
    6. III. Server-side Java
      1. 16. Servlets and JSP
        1. Why Use Servlets?
        2. Releases and Versions
        3. Installing the Tomcat Software
        4. Running the Example Servlets
        5. Ports and Protocols
        6. The HTML to Invoke a Servlet
        7. A Servlet and Its Request/response
        8. Servlet Request
        9. Response to a Servlet Request
        10. Writing Your Own Servlet
          1. Keeping Track of Content Length
        11. Servlet Operating Cycle and Threading
        12. Java Server Pages
          1. Second Example of JSP
        13. Java Beans in Servlets and JSP
        14. Further Reading
        15. Exercises
        16. Some Light Relief—The Java-Powered Toaster
      2. 17. Networking in Java
        1. Everything You Need To Know about TCP/IP but Failed to Learn in Kindergarten
          1. What’s in the Networking Library?
          2. TCP/IP Client/Server Model
        2. A Client Socket in Java
        3. Sending Email by Java
        4. A Server Socket in Java
          1. Socket Protocols
          2. Running the HTTP Server Program
          3. Debugging Sockets
          4. Getting the HTTP Command
        5. HTTP and Web Browsing: Retrieving HTTP Pages
          1. How to Find the IP Address Given to a Machine Name
          2. Some Notes on Protocol and Content Handlers
        6. How to Make an Applet Write a File on the Server
          1. The Linlyn Class for File Transfer
        7. A Multithreaded HTTP Server
        8. A Mapped I/O HTTP Server
        9. Further Reading
        10. Exercises
        11. Some Light Relief—Using Java to Stuff an Online Poll
          1. The Java Votebot
      3. 18. Remote Method Invocation
        1. Object Serialization
          1. Class Versioning
        2. Remote Method Invocation
          1. The Client Side of RMI
          2. The Server Side of RMI
          3. Creating the Server Stub and Skeleton
          4. Running the RMI Example
          5. Adding the Client Security Manager
          6. Jini Software
        3. Object Communication Middleware
          1. CORBA
          2. IDL
        4. Exercises
        5. Some Light Relief—The Origami Kamikaze Water Bomber
    7. IV. Client Java
      1. 19. GUI Basics and Event-Handling
        1. All About Event-Handling
          1. Java Event Model
          2. The JFrame Example
        2. Tips for Slimming Down Handler Code
          1. Making a Top-Level Class into a Listener
          2. Using a Listener Adapter Class
        3. Summary of Event-Handling
        4. Exercises
        5. Some Light Relief—The Mouse That Roared
      2. 20. All About Applets
        1. Differences Between Applets and Applications and How to Convert Between Them
        2. Embedding a Java Program in a Web Page
          1. The HTML to Invoke an Applet
        3. Starting Applet Execution
          1. Screen Appearance of an Applet
          2. Browser Summary
          3. Passing Parameters to Applets
          4. Build in Debugging Help
        4. Zip Files and Jar Files
          1. Keep Your Software in a Jar
          2. Removing the Contents from a Jar
        5. Java Web Start
        6. HTML Applet Tags
        7. Exercises
        8. Some Light Relief—Three Fine Applets
      3. 21. JFC and the Swing Package
        1. Java Foundation Classes
          1. Some Terminology
          2. Overview of JComponent
        2. All About Controls (JComponents)
          1. How to Display Components
        3. Swing Threads—A Caution!
        4. Swing Components
          1. JLabel
          2. JButton
          3. JToolTip
          4. JTextField
          5. JCheckBox
          6. JPanel
          7. JRadioButton and ButtonGroup
          8. JOptionPane
          9. JScrollPane
          10. JTabbedPane
          11. JEditorPane
        5. More about Swing Components
        6. Further Reading
        7. Exercises
        8. Some Light Relief—The Bible Code
      4. 22. Containers, Layouts, and AWT Loose Ends
        1. Pluggable Look and Feel
        2. All About Containers
          1. The Container Class Hierarchy
          2. What’s in a Swing Container?
          3. JFrame
          4. JPanel
          5. Applet and JApplet
          6. Window and JWindow
        3. Layout in a Container
          1. FlowLayout
          2. Grid Layout
          3. BorderLayout
          4. BoxLayout
          5. Combining Layouts
          6. Other Layout Managers
        4. Tying up the Loose Ends
          1. JDK 1.4 Image I/O
          2. The Toolkit
          3. Printing the Screen
          4. Changing Cursor Appearance
          5. How to Simulate Multibutton Mice
        5. Exercises
        6. Some Light Relief—Sky View Cafe: A High Quality Applet
    8. V. Enterprise Java
      1. 23. Java Beans in Theory
        1. What Is Component Software?
        2. What Is a Java Bean?
        3. Properties and Events
        4. Coding Time, Design Time, Runtime
        5. Refresher on Events
        6. Bean Conventions
        7. Install the Beanbox
        8. Run a Demo Bean
          1. Loading a Bean into the Beanbox
        9. Customizing Bean Properties
        10. Connecting a Button to a Method in Another Bean
        11. Activation Framework and Infobus
          1. Java Activation Framework
          2. Infobus
        12. Limitations of Beans
        13. Enterprise Java Beans (EJB)
        14. Using EJB in an Application Server
        15. EJB Summary
        16. Further Reading
        17. Exercises
        18. Some Light Relief—Furby’s Brain Transplant
      2. 24. Java Beans in Practice
        1. The Specification for Two Beans
        2. The Code for the ConverterField Bean
          1. Properties of the ConverterField Bean
          2. Summary of ConverterField Bean
        3. The Code for DoItButton Bean
          1. Properties of the DoItButton Bean
        4. Compile, Jar, and Load Classes into Beanbox
          1. Beans are Best Carried Around in Jars
        5. Bean Icons
        6. The Bean Info Class
          1. How to Write BeanInfo
        7. Descriptor Classes
        8. Properties
          1. Describing the Properties in a BeanInfo Class
          2. Weird Exception Handling
          3. Back to Descriptors
        9. Bound Properties
          1. Practical Example of a Bound Property: validNum
        10. Property Change Support for Non-Visual Beans
        11. Summary: Telling Another Bean About a Change in One of Your Values
        12. Connecting a Swing Event to a Method in Another Bean
          1. EventSet Descriptor Code
        13. Hidden State
        14. The Completed, Integrated Rate Calculator
        15. Customizing More Complicated Properties
        16. Constrained Properties
        17. Calling a Method in Another Bean—Don’t Do It!
        18. Exercises
        19. Some Light Relief—Java’s Duke Mascot
        20. Complete Code Listings
          1. DoItButton.java
          2. DoItButtonBeanInfo.java
          3. ConverterField.java
          4. ConverterFieldBeanInfo.java
      3. 25. Java Security
        1. The Sandbox
        2. Code Signing
        3. The Security Manager
        4. Applying the Security Policy
        5. Signing a Java Program
          1. Step 1: Setup for Applet Signing (One-Time)
          2. Step 2: Put All the Files That Make up the Applet into a Jar File
          3. Step 3: Create a Signed Jar File
          4. Step 4: Change the Applet Tag
          5. Step 5: The Person Who Runs the Applet Must Import My Certificate
          6. Step 6: Set up a Security Policy for the User, Allowing Signed Code
          7. Step 7: Run the Code Using the Policy File
        6. Some Light Relief—Software About Nothing
        7. Further References
      4. 26. Relational Databases and SQL
        1. Introduction to Relational Databases
        2. Primary and Foreign Keys
        3. 1-Many, Many-Many Relationships
        4. Normal Forms
        5. Relational Database Glossary
        6. Basic SQL Primer
        7. Creating and Populating Tables
        8. Querying and Retrieving Data
        9. Subquery Selections
        10. Result Set of a SELECT Query
          1. SELECT Pitfalls
        11. Updating Values
        12. Deleting Records and Tables
        13. SQL Prepared Statements and Stored Procedures
        14. Further Reading
        15. Exercises
        16. Some Light Relief—Reading the Docs
      5. 27. JDBC
        1. Downloading and Installing the Software
        2. Running the Example Code
          1. Output from Running SimpleApplicationDemo
        3. Connecting to the Database
        4. Executing SQL Statements
          1. Threads and Database Programming
        5. Result Sets
          1. Cursor Support
        6. Batching SQL Statements and Transactions
        7. Transactions
        8. Prepared Statements and Stored Procedures
        9. Complete Example
        10. Database and Result Set Metadata
        11. Further Reading
        12. Exercises
        13. Light Relief—Hear Java Speak! See Java on a PDA!
      6. 28. XML and Java
        1. Some Rules of XML
        2. The Document Type Definition (DTD)
        3. What Is XML Used For?
        4. XML Versions and Glossary
        5. JAXP Library Contents
        6. Reading XML with DOM Parsers
        7. A Program That Uses a DOM Parser
        8. Reading an XML File—SAX Parsers
        9. A Program That Uses a SAX Parser
        10. The Factory Design Pattern
        11. Design Pattern Summary
        12. Other Java XML Notes
        13. Download and Install the Java XML Software (JAXP)
        14. Running the Example Code
        15. Further Reading
        16. Exercises
        17. Some Light Relief—“View Source” on Kevin’s Life
    9. A. Graphics Programming
      1. Colors
      2. Fonts and Font Metrics
      3. The Graphics Context
      4. Drawing Text, Lines, and Shapes
      5. Loading and Drawing Images
        1. Loading an Image File in an Application
        2. Loading an Image File in an Applet
        3. Drawing an Image Onto a Graphics Object
        4. The ImageObserver Argument
        5. Image Update
        6. The Media Tracker
        7. Image Processing
        8. Double Buffering
        9. Clipping Rectangles
        10. Taking Images Apart: java.awt.image
        11. Transparent Backgrounds
        12. Animation
      6. Sounds
      7. Some Light Relief—Satan: Oscillate My Metallic Sonatas
    10. B. Obsolete Components of the Abstract Window Toolkit
      1. How the Java Abstract Window Toolkit Works
      2. Controls, Containers, Events
        1. Overview of Controls
      3. All About AWT Controls (Components)
        1. Button
        2. Canvas
        3. Adapter Classes
        4. Checkbox
        5. CheckboxGroup
        6. Choice
        7. Label
        8. List
        9. Scrollbar
        10. TextField
        11. TextArea
        12. Menus: Design
        13. Menu : Class
        14. CheckboxMenuItem
        15. Pop-up Menus
      4. All About Containers
        1. ScrollPane
        2. Window
        3. Frame
        4. Panel
        5. Applet
        6. Dialog
        7. FileDialog
    11. C. Powers of 2 and ISO 8859