Teach Yourself
Java in 21 Days
Professional Reference Edition
by Laura Lemay, Charles L. Perkins and Michael Morrison
C O N T E N T S
Introduction
Day 1 An Introduction to Java Programming
- What Is Java?
- Java's Past, Present, and Future
- Why Learn Java?
- Getting Started Programming in Java
- Troubleshooting
- Summary
-
Q&A
Day 2 Object-Oriented Programming and Java
- Thinking in Objects: An Analogy
- Objects and Classes
- Behavior and Attributes
- Inheritance, Interfaces, and Packages
- Summary
-
Q&A
Day 3 Java Basics
- Statements and Expressions
- Variables and Data Types
- Comments
- Literals
- Expressions and Operators
- String Arithmetic
- Summary
-
Q&A
Day 4 Working with Objects
- Creating New Objects
- Accessing and Setting Class and Instance Variables
- Calling Methods
- References to Objects
- Casting and Converting Objects and Primitive Types
- Odds and Ends
- Class and Object Reflection (Java 1.1)
- The Java Class Library
- Summary
-
Q&A
Day 5 Arrays, Conditionals, and Loops
- Arrays
- Block Statements
- if Conditionals
- switch Conditionals
- for Loops
- while and do Loops
- Breaking Out of Loops
- Summary
-
Q&A
Day 6 Creating Classes and Applications in Java
- Defining Classes
- Creating Instance and Class Variables
- Creating Methods
- Creating Java Applications
- Java Applications and Command-Line Arguments
- Summary
-
Q&A
Day 7 More About Methods
- Creating Methods with the Same Name, Different Arguments
- Constructor Methods
- Overriding Methods
- Finalizer Methods
- Summary
-
Q&A
Day 8 Java Applet Basics
- How Applets and Applications Are Different
- Creating Applets
- Including an Applet on a Web Page
- More About the <APPLET> Tag
- Java Archives
- Passing Parameters to Applets
- Summary
-
Q&A
Day 9 Graphics, Fonts, and Color
Day 10 Simple Animation and Threads
- Creating Animation in Java
- Threads: What They Are and Why You Need Them
- Reducing Animation Flicker
- Summary
-
Q&A
Day 11 More Animation, Images, and Sound
- Retrieving and Using Images
- Creating Animation Using Images
- Retrieving and Using Sounds
- Using Animation Packages
- More About Flicker: Double-Buffering
- Summary
-
Q&A
Day 12 Managing Simple Events and Interactivity
Day 13 Creating User Interfaces with the awt
- An awt Overview
- The Basic User Interface Components
- Panels and Layout
- Handling UI Actions and Events
- Nesting Panels and Components
- More UI Components
- More UI Events
- Fun with Components
- A Complete Example: RGB-to-HSB Converter
- Up and Coming in Java 1.1
- Summary
-
Q&A
Day 14 Windows, Networking, and Other Tidbits
Day 15 Modifiers, Access Control, and Class Design
- Modifiers
- Controlling Access to Methods and Variables
- Class Variables and Methods
- Finalizing Classes, Methods, and Variables
- Abstract Classes and Methods
- Summary
-
Q&A
Day 16 Packages and Interfaces
- Programming in the Large and Programming in the Small
- What Are Packages?
- Using Packages
- Creating Your Own Packages
- What Are Interfaces?
- Implementing and Using Interfaces
- Creating and Extending Interfaces
- Summary
-
Q&A
Day 17 Exceptions
- Exceptions, the Old and Confusing Way
- Java Exceptions
- Managing Exceptions
- Declaring Methods That Might Throw Exceptions
- Creating and Throwing Your Own Exceptions
- When and When Not to Use Exceptions
- Summary
-
Q&A
Day 18 Multithreading
- Thread Fundamentals
- The Problem with Parallelism
- Thinking Multithreaded
- Creating and Using Threads
- Knowing When a Thread Has Stopped
- Thread Scheduling
- Summary
-
Q&A
Day 19 Streams and I/O
- What Are Streams?
- The java.io Package
- Input Streams
- Output Streams
- Related Classes
- Object Serialization (Java 1.1)
- Summary
-
Q&A
Day 20 Using Native Methods and Libraries
- Why Use Native Methods?
- Disadvantages of Native Methods
- The Illusion of Required Efficiency
- Writing Native Methods
- Tools and Techniques for Writing Native Implementations
- Summary
-
Q&A
Day 21 Under the Hood
- -The Big Picture
- The Java Virtual Machine
- The Bytecode Interpreter
- Just-in-Time Compilers
- The Class File Format
- Method Signatures
- The Garbage Collector
- The Security Story
- Summary
-
Q&A
Day 22 Java Programming Tools
- Overview of the Standard JDK Tools
- The Runtime Interpreter
- The Compiler
- The Applet Viewer
- The Debugger
- The Class File Disassembler
- The Header and Stub File Generator
- The Documentation Generator
- Visual Development Tools
- Summary
- Q&A
Day 23 Working with Data Structures in Java
- Data Structure Fundamentals
- The Standard Java Data Structures
- Building Your Own Data Structures
- Summary
-
Q&A
Day 24 Advanced Animation and Media
- What Is Animation?
- Types of Animation
- Tracking Images
- The MediaTracker Class
- Implementing Sprite Animation
- Sample Applet: Sharks
- Summary
-
Q&A
Day 25 Fun with Image Filters
- The Basics of Color
- Color Images in Java
- Color Models
- The Color Model Classes
- Image Filters
- The Image Filter Classes
- Writing Your Own Image Filters
- Using Image Filters
- Summary
-
Q&A
Day 26 Client/Server Networking in Java
- Internet Network Basics
- The Client/Server Paradigm
- Sockets
- Fortune: A Datagram Client and Server
- Trivia: A Stream Client and Server
- Summary
-
Q&A
Day 27 The Standard Extension APIs
- Java API Overview
- The Enterprise API
- The Commerce API
- The Management API
- The Server API
- The Media API
- The Security API
- The Java Beans API
- The Embedded API
- Summary
-
Q&A
Day 28 Emerging Technologies
appendix A Language Summary
- Reserved Words
- Comments
-
Literals
-
Variable Declaration
-
Variable Assignment
-
Operators
-
Objects
-
Arrays
-
Loops and Conditionals
-
Class Definitions
- Method and Constructor Definitions
- Packages, Interfaces, and Importing
-
Exceptions and Guarding
appendix B Class Hierarchy Diagrams
appendix C The Java Class Library
appendix D Bytecodes Reference
appendix E java.applet Package Reference
appendix F java.awt Package Reference
- LayoutManager
- MenuContainer
- BorderLayout
- Button
- Canvas
- CardLayout
- Checkbox
- CheckboxGroup
- CheckboxMenuItem
- Choice
- Color
- Component
- Container
- Dialog
- Dimension
- Event
- FileDialog
- FlowLayout
- Font
- FontMetrics
- Frame
- Graphics
- GridBagConstraints
- GridBagLayout
- GridLayout
- Image
- Insets
- Label
- List
- MediaTracker
- Menu
- MenuBar
- MenuComponent
- MenuItem
- Panel
- Point
- Polygon
- Rectangle
- Scrollbar
- TextArea
- TextComponent
- TextField
- Toolkit
- Window
- awtError
appendix G java.awt.image Package Reference
- ImageConsumer
- ImageObserver
- ImageProducer
- ColorModel
- CropImageFilter
- DirectColorModel
- FilteredImageSource
- ImageFilter
- IndexColorModel
- MemoryImageSource
- PixelGrabber
- RGBImageFilter
appendix H java.awt.peer Package Reference
- ButtonPeer
- CanvasPeer
- CheckboxMenuItemPeer
- CheckboxPeer
- ChoicePeer
- ComponentPeer
- ContainerPeer
- DialogPeer
- FileDialogPeer
- FramePeer
- LabelPeer
- ListPeer
- addItem
- MenuBarPeer
- MenuComponentPeer
- MenuItemPeer
- MenuPeer
- PanelPeer
- ScrollbarPeer
- TextAreaPeer
- TextComponentPeer
- TextFieldPeer
- WindowPeer
appendix I java.io Package Reference
- DataInput
- DataOutput
- FilenameFilter
- BufferedInputstream
- BufferedOutputStream
- ByteArrayInputStream
- ByteArrayOutputStream
- DataInputStream
- DataOutputStream
- File
- FileDescriptor
- FileInputStream
- FileOutputStream
- FilterInputStream
- FilterOutputStream
- InputStream
- LineNumberInputStream
- OutputStream
- PipedInputStream
- PipedOutputStream
- PrintStream
- PushbackInputStream
- RandomAccessFile
- SequenceInputStream
- StreamTokenizer
- StringBufferInputStream
- EOFException
- FileNotFoundException
- IOException
- InterruptedIOException
- UTFDataFormatException
appendix J java.lang Package Reference
- Cloneable
- Runnable
- Boolean
- Character
- Class
- ClassLoader
- Compiler
- Double
- Float
- Integer
- Long
- Math
- Number
- Object
- Process
- Runtime
- SecurityManager
- String
- StringBuffer
- System
- Thread
- ThreadGroup
- Throwable
- RuntimeException
- ClassNotFoundException
- CloneNotSupportedException
- Exception
- IllegalAccessException
- IllegalArgumentException
- IllegalMonitorStateException
- IllegalThreadStateException
- IndexOutOfBoundsException
- InstantiationException
- InterruptedException
- NegativeArraySizeException
- NullPointerException
- NumberFormatException
- RuntimeException
- SecurityException
- StringIndexOutOfBoundsException
- AbstractMethodError
- ClassFormatError
- Error
- IllegalAccessError
- IncompatibleClassChangeError
- InstantiationError
- InternalError
- LinkageError
- NoClassDefFoundError
- NoSuchFieldError
- NoSuchMethodError
- OutOfMemoryError
- StackOverflowError
- ThreadDeath
- UnknownError
- UnsatisfiedLinkError
- VerifyError
- VirtualMachineError
appendix K java.net Package Reference
- ContentHandlerFactory
- SocketImplFactory
- URLStreamHandlerFactory
- ContentHandler
- DatagramPacket
- DatagramSocket
- InetAddress
- ServerSocket
- Socket
- SocketImpl
- URL
- URLConnection
- URLEncoder
- MalformedURLException
- ProtocolException
- SocketException
- UnknownHostException
- UnknownServiceException
appendix L java.util Package Reference
- Enumeration
- Observer
- BitSet
- Date
- Dictionary
- Hashtable
- Observable
- Properties
- Random
- Stack
- StringTokenizer
- Vector
- EmptyStackException
- NoSuchElementException
Credits
Copyright © 1996 by Sams.net Publishing
All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of the information contained herein. For information, address Sams.net Publishing, 201 W. 103rd St., Indianapolis, IN 46290.
International Standard Book Number: 1-57521-183-1
HTML conversion by :
M/s. LeafWriters (India) Pvt. Ltd.
Website : http://leaf.stpn.soft.net
e-mail :
leafwriters@leaf.stpn.soft.net
Credits
| President, Sams Publishing | Richard K. Swadley |
| Publishing Manager | Mark Taber |
| Managing Editor | Cindy Morrow |
| Director of Marketing | John Pierce |
| Assistant Marketing Managers | Kristina Perry, Rachel Wolfe |
| Acquisitions Editor | Mark Taber | Development Editor | Fran Hatton |
| Software Development Specialist | Bob Correll | Senior Editor | Kitty Wilson |
| Copy Editors | Kimberly K. Hannel, Colleen Williams | Indexer | Johnna VanHoose |
| Technical Reviewers | Brad Birnbaum, Pratip Banerji, Jeff Bankston, Jeff Shockley, | Editorial Coordinator | Bill Whitmer |
| Technical Edit Coordinator | Lorraine Schaffer | Editorial Assistants | Carol Ackerman, Andi Richter, Rhonda Tinch-Mize |
| Cover Designer | Tim Amrhein | Book Designer | Gary Adair |
| Copy Writer | Peter Fuller | Production Team Supervisor | Brad Chinn |
| Production | Cynthia Davis, Elizabeth Deeter, Sonja Hart, Lousia Klucznik, Polly Lavrick, Paula Lowell, Andrew Stone | ||
Preface to the Professional Reference Edition
I first saw Java running in May of 1995, and was immediately struck by what it offered to the Web. What I saw seems almost quaint in this day and age of multimedia Web pages-a small animation of a character doing cartwheels across the screen-but at the time it was a revolution. My friend Jim Graham, a programmer on the Java team, showed me various aspects of the Java language and the HotJava browser, and I sat with my mouth agape, unable to say much of anything except for "that is so cool." At the time, I was just finishing up a book about HTML and looking for something else to do. I immediately knew that this had to be it. I had to write a book on Java.
It took somewhat longer to actually produce the book, between needing to finish a number of other projects, having to wait for a new version of Java itself, and coming down with a number of bad cases of the flu, but the book was written and shipped in early 1996. That book was the original Teach Yourself Java in 21 Days.
While not the first book available on the Java language, it was widely regarded as the first good book and the first one that wasn't either too vague or that assumed too much knowledge of programming. Written for an intermediate programmer, Teach Yourself Java continues to be one of the few books available that offers a basic tutorial in Java, enough to get you started and enough to move beyond the basics. Teach Yourself Java continues to be popular and continues to be recommended as one of the best books on getting started in Java.
Which brings us to this hefty tome that you're holding in your hands. Since early 1996 Java itself has not changed overly much. The current 1.0.2 release has added few features since 1.0; for the new features we'll have to wait for 1.1 (due out in late 1996). But given the explosion of tools for building Java applications and the wide variety of things that people are doing with Java out there for the Web and for general-purpose applications, there is no shortage of things to talk about when it comes to Java.
This book, therefore, is an extension of the original Teach Yourself Java. It has been greatly expanded and enhanced, with all the original content updated, the weak parts fixed, and more examples added. This book also contains a bonus week that adds further depth and detail about existing topics such as images, animation, and networking; it includes information about tools, debugging, and advanced data structures; and it goes into great detail about upcoming features in Java 1.1 and the extension APIs. With more than 250 pages of reference material, there's little you won't be able to discover using this book.
If you haven't yet worked with Java, this is the book to start with. If you have worked with Java but are looking for more information, this is the book to continue with. And even if you've read the original Teach Yourself Java, you'll find enough new in this edition to merit putting aside the original and adding this one to the stack of programming books on your desk.
Good luck and enjoy!
August 1996
Acknowledgments
From Laura Lemay:
To Sun's Java team, for all their hard work on Java, the language, and on the browser, and particularly to Jim Graham, who demonstrated Java and HotJava to me on very short notice in May and planted the idea for this book.To everyone who bought my previous books and liked them: Buy this one, too.
From Charles L. Perkins:
To Patrick Naughton, who first showed me the power and the promise of Oak (Java) in early 1993.To Mark Taber, who shepherded this lost sheep through his first book.
From Mike Morrison:
Thanks to Mark Taber for giving me the opportunity to contribute to such a cool project, and to Fran Hatton for being so enormously positive and helpful.
About the Authors
Laura Lemay
Laura Lemay is a technical writer and a nerd. After spending six years writing software documentation for various computer companies in Silicon Valley, she decided that writing books would be much more fun (but has still not yet made up her mind). In her spare time she collects computers, e-mail addresses, interesting hair colors, and nonrunning motorcycles. She is also the perpetrator of Teach Yourself Web Publishing with HTML in 14 Days.
You can visit her home page at http://www.lne.com/lemay/.
Charles L. Perkins
Charles L. Perkins is the founder of Virtual Rendezvous, a company building a Java-based service that will foster socially focused, computer-mediated, real-time filtered interactions between people's personas in the virtual environments of the near future. In previous lives, he has evangelized NeXTSTEP, SmallTalk, and UNIX, and has degrees in both physics and computer science. Before attempting this book, he was an amateur columnist and author. He's done research in speech recognition, neural nets, gestural user interfaces, computer graphics, and language theory, but had the most fun working at Thinking Machines and Xerox PARC's SmallTalk group. In his spare time, he reads textbooks for fun.
You can reach him via e-mail at virtual@rendezvous.com, or visit his Java page at http://rendezvous.com/java.
Michael Morrison
Michael Morrison is the author of Teach Yourself Internet Game Programming with Java in 21 Days, and a contributing author to Tricks of the Java Programming Gurus, Java Unleashed, and Game Developer magazine. Michael lives in Scottsdale, Arizona, with his (now legally recognized) female cohort, Mahsheed. In his spare time, Michael enjoys testing his threshold for pain on skateboard ramps. You can reach Michael via e-mail at mmorrison@thetribe.com, or check out his Web site at http://www.thetribe.com.
Tell Us What You Think!
As a reader, you are the most important critic and commentator of our books. We value your opinion and want to know what we're doing right, what we could do better, what areas you'd like to see us publish in, and any other words of wisdom you're willing to pass our way. You can help us make strong books that meet your needs and give you the computer guidance you require.
Do you have access to CompuServe or the World Wide Web? Then check
out our CompuServe forum by typing GO
SAMS at any prompt. If you prefer the World
Wide Web, check out our site at http://www.mcp.com.
| Note |
If you have a technical question about this book, call the technical support line at 800-571-5840, ext. 3668. |
As the team leader of the group that created this book, I welcome
your comments. You can fax, e-mail, or write me directly to let
me know what you did or didn't like about this book-as well as
what we can do to make our books stronger. Here's the information:
| FAX: | 317-581-4669 |
| E-mail: | newtech_mgr@sams.mcp.com |
| Mail: | Mark Taber
Publishing Manager Sams.net Publishing 201 W. 103rd Street Indianapolis, IN 46290 |
Introduction
The World Wide Web, for much of its existence, has been a method for distributing passive information to a widely distributed number of people. The Web has, indeed, been exceptionally good for that purpose. With the addition of forms and image maps, Web pages began to become interactive-but the interaction was often simply a new way to get at the same information. The limitations of Web distribution were all too apparent once designers began to try to stretch the boundaries of what the Web can do. Even other innovations, such as Netscape's server push to create dynamic animations, were merely clever tricks layered on top of a framework that wasn't built to support much other than static documents with images and text.
Enter Java, and the capability for Web pages to contain Java applets. Applets are small programs that create animations, multimedia presentations, real-time (video) games, multiuser networked games, and real interactivity-in fact, most anything a small program can do, Java applets can. Downloaded over the Net and executed inside a Web page by a browser that supports Java, applets are an enormous step beyond standard Web design.
The disadvantage of Java is that to create Java applets right now, you need to write them in the Java language. Java is a programming language, and therefore, creating Java applets is more difficult than creating a Web page or a form using HTML. Soon there will be tools and programs that will make creating Java applets easier-they may be available by the time you read this. For now, however, the only way to delve into Java is to learn the language and start playing with the raw Java code. Even when the tools come out, you may want to do more with Java than the tools can provide, and you're back to learning the language.
That's whereTeach Yourself Java in 21 Days comes in. This book teaches you all about the Java language and how to use it to create not only applets, but also applications, which are more general Java programs that don't need to run inside a Web browser. By the time you get through with this book, you'll know enough about Java to do just about anything, inside an applet or out.
How This Book Is Organized
Teach Yourself Java in 21 Days covers the Java language and its class libraries in 21 days, organized as three separate weeks. In addition, this edition contains a bonus week that's chock full of new and advanced information. Each week covers a different broad area of developing Java applets and applications.
In the first week you'll learn about the Java language itself:
- Day 1 is the basic introduction: what Java is, why it's cool, and how to get the software. You'll also create your first Java applications and applets.
- On Day 2 you'll explore basic object-oriented programming concepts as they apply to Java.
- On Day 3 you'll start getting down to details with the basic Java building blocks: data types, variables, and expressions, such as arithmetic and comparisons.
- Day 4 goes into detail about how to deal with objects in Java: how to create them, how to access their variables and call their methods, and how to compare and copy them. You'll also get your first glance at the Java class libraries.
- On Day 5 you'll learn more about Java, with arrays, conditional statements, and loops.
- Day 6 is the best one yet. You'll learn how to create classes, the basic building blocks of any Java program, and how to put together a Java application (a Java program that can run on its own without a Web browser).
- Day 7 builds on what you learned on Day 6. You'll learn more about how to create and use methods, including overriding and overloading methods and creating constructors.
Week 2 is dedicated to applets and the Java class libraries:
- Day 8 provides the basics of applets-how they're different from applications, how to create them, and about the most important parts of an applet's life cycle. You'll also learn how to create HTML pages that contain Java applets.
- On Day 9 you'll learn about the Java classes for drawing shapes and characters to the screen-in black, white, or any other color.
- On Day 10 you'll start animating those shapes you learned about on Day 9, including learning about threads and their uses.
- Day 11 covers more detail about animation, adding bitmap images and audio to the soup.
- Day 12 delves into interactivity-handling mouse and keyboard clicks from the user in your Java applets.
- Day 13 is ambitious; you'll learn about using Java's Abstract Windowing Toolkit to create a user interface in your applet, including menus, buttons, check boxes, and other elements.
- On Day 14 you'll explore the last of the main Java class libraries for creating applets: windows and dialogs, networking, and a few other tidbits.
Week 3 includes advanced topics for when you start doing larger and more complex Java programs or when you want to learn more:
- On Day 15 you'll learn more about the Java language's modifiers-for abstract and final methods and classes as well as for protecting a class's private information from the prying eyes of other classes.
- Day 16 covers interfaces and packages, useful for abstracting protocols of methods to aid reuse and for the grouping and categorization of classes.
- Day 17 covers exceptions: errors and warnings and other abnormal conditions, generated either by the system or by you in your programs.
- Day 18 builds on the thread basics you learned on Day 10 to give a broad overview of multithreading and how to use it to allow different parts of your Java programs to run in parallel.
- On Day 19 you'll learn all about the input and output streams in Java's I/O library.
- Day 20 teaches you about native code-how to link C code into your Java programs to provide missing functionality or to gain performance.
- On Day 21 you'll get an overview of some of the behind-the-scenes technical details of how Java works: the bytecode compiler and interpreter, the techniques Java uses to ensure the integrity and security of your programs, and the Java garbage collector.
This Professional Reference Edition also includes a bonus week that contains more depth about some of the topics previously mentioned in the book, lots more sample programs, and coverage of the various tools and utilities currently available for writing with Java. It also gives you a preview of the features coming up in Java 1.1:
- Day 22 describes tools and utilities for programming in Java, including debugging techniques, Java development environments such as Symantec Café and Visual J++, the javadoc documentation system, and other tips and tricks.
- On Day 23 you'll learn about creating structures for modeling various forms of data, both with the classes in the java.util package and by creating new classes.
- Day 24 goes into even more detail about animation in Java, building on the simple techniques covered in Week 2. On this day you'll learn about creating sprite-based animation and coordinating image and media loading with your programs.
- Sun's java.awt.image package provides a set of classes for working with images. Day 25 covers these classes in detail, explaining the image filter architecture and how you can use it in your own Java programs.
- Day 14 gives a very basic introduction to networking in Java. Day 26 takes it further, with extensive examples of networking applets and applications, working with "live" data sent from a server, and connecting to databases from Java applets.
- On Day 27 we move into the future and describe what are known as the standard extension APIs. Sun is developing these APIs in conjunction with other interested parties, and many of the features you'll learn about in this chapter will be part of the 1.1 Java API.
- Day 28 finishes up with more future topics, including Sun's Java Beans API, Java chips, and the JavaOS. How will these technologies affect how you work in Java and how Java will affect you? Learn about it here as you finish up the book.
Preparing for the Future: The Upcoming Java 1.1 Release
At the time this book is being written, the current version of Java is known as the 1.0 API (or, more exactly, the 1.0.2 version of the JDK). A new version of Java is on the horizon, one that will add a significant number of new features to Java while still being backward compatible with the original version. This new version of Java, called Java 1.1, is expected to be available in a prerelease form in late 1996.
This book covers the Java 1.0 API in intimate detail. Where information about an upcoming feature of 1.1 is available, we have attempted to explain that new feature, how it will affect what you have already learned about the 1.0 API, and where to look for further information. In addition, the last two chapters of this book cover the more advanced features of 1.1 and how they will be used. These notes and comments will help you prepare for when 1.1 is released and help you migrate the code you may have already written quickly and easily to the new API.
Features expected to be in the 1.1 JDK include
- JDBC (the Java Database Connectivity interface) provides a mechanism for connecting Java applications and applets to SQL databases such as Oracle and Sybase. The JDBC, available in a prerelease form at this time from http://splash.javasoft.com/jdbc/, is covered on Day 27.
- RMI (Remote Method Invocation) is the ability to call a Java method from an object running elsewhere (for example, in a different Java environment running on the same machine or on any machine on the network). RMI is closely related to object serialization, which allows objects to be encoded into a stream of bytes, which can then be sent over a network or saved to a file. The result can then also be decoded back into a Java object at the other end. Object serialization is an extension of the stream classes discussed on Day 19. RMI is discussed in greater detail on Day 27. Information about both of these topics can be found at http://chatsubo.javasoft.com/current/.
- The Java native methods interface is the ability for Java to call system-specific libraries such as DLLs or loadable libraries written in C. Writing native methods is described on Day 20; enhancement in Java 1.1 will include a better API for making sure native method libraries are compatible with every implementation of the Java runtime across platforms.
- JIT compilers are tools that convert Java bytecode to native machine code. You'll learn about JIT compilers throughout this book, but particularly on Days 21 and 22. In Java 1.1 there will be better specifications for writing your own JIT or other tool that generates native code from Java bytecodes.
- Changes to the awt. Probably some of the more significant changes to Java will be in the area of the Abstract Windowing Toolkit, or awt, the portion of Java that controls drawing to the screen, creating user interface elements such as buttons and windows, and handling painting and user input between all those elements. This book covers the awt primarily in Week 2. Enhancements to the awt in Java 1.1 include printing, pop-up menus, supports for clipboards (copy and paste), internationalization for fonts, better scrolling capabilities, and delegation-based events. You'll learn more about these changes throughout Week 2.
- Security enhancements. JDK 1.1 will provide many features for implementing security in Java applications, including signatures, access control, key management, and message digests (MD5 hashes, for example). These additions won't affect much of 1.0 because they are new enhancements. You'll learn all about 1.1's security features on Day 27.
- Networking enhancements. Java 1.0 provides the java.net classes, which provide simple network connections, URL management, and simple client and server sockets. Java 1.1 provides more flexibility for the existing socket classes, a new MulticastSocket class, and BSD-style socket options. Learn about all these new features on Day 14 or from the URL http://java.sun.com/products/JDK/1.1/designspecs/net/index.html.
- Adapter classes allow you to implement an API defined by an interface or a class and have the flow of control move from the adapter class back to an enclosing object. Java 1.1 provides Java syntax for nesting class definitions inside other class definitions to more easily create adapter classes. You'll learn more on Day 6.
- Object reflection is the ability for Java to inspect an object and find out its methods and variables (and call and change them). Object reflection is useful for class browsers or other tools that need to find out information about an object on-the-fly, as well as component object systems that need defined ways of referring to other objects' contents. Java 1.1 provides many features for handling object reflection, including a number of new classes. You'll find out more on Day 4 or from http://java.sun.com/products/JDK/1.1/designspecs/reflection/index.html.
- Java 1.1 provides a number of new features for internationalization, particularly language-specific features such as strings, character set conversions, Unicode character display, and support for definable "locales."
- Java archives (JAR files) provide a mechanism for combining several classes into a single file for faster downloading over the Net. Netscape provides a single archive file mechanism for applets, but JAR files provide a more cross-platform file format, compression, and the ability to include media files in the archive. The capability to store Java classes in JAR files, and to use them with Java-enabled browsers, will be in Java 1.1. The current JAR file format specification is available from http://java.sun.com/security/codesign/jar-format.html.
You can learn more about all these features via information throughout this book or from the Java 1.1 preview page at http://www.java.sun.com/products/JDK/1.1/designspecs/.
Conventions Used in This Book
Text that you type and text that should appear on your screen is presented in monospace type:
It will look like this.
It mimics the way text looks on your screen. Placeholders for variables and expressions appear in monospace italic.
The end of each chapter offers common questions asked about that day's subject matter, with answers from the authors.
Sources for Further Information
Before, while, and after you read this book, there are several Web sites that may be of interest to you as a Java developer.
The official Java Web site is at http://java.sun.com/. At this site, you'll find the Java development software and online documentation for all aspects of the Java language, including the previously mentioned Java 1.1 preview page. It has several mirror sites that it lists online, and you should probably use the site "closest" to you on the Internet for your downloading and Java Web browsing.
There is also an excellent site for developer resources, called Gamelan, at http://www.gamelan.com/, which contains an enormous number of applets and applications, with sample code, help, and plenty of information about Java and Java development.
This book also has a companion Web site at http://www.lne.com/Web/JavaProf/. Information at that site includes examples, more information, and background for this book, corrections to this book, and other tidbits that are not included here.
For discussion about the Java language and the tools to develop in it, check out the Usenet newsgroups for comp.lang.java. This set of newsgroups-which includes comp.lang.java.programming, comp.lang.java.api, comp.lang.java.misc, comp.lang.java.security, and comp.lang.java.tech-is a terrific source for getting questions answered and for keeping up on new Java developments.
Praise for Teach Yourself Java
"If you get only one Java book, it should be Teach Yourself Java in 21 Days. Authors Laura Lemay and Charles L. Perkins cover all aspects of Java programming in an easy-to-read guide organized around daily lesson plans."
-Jay Munro, pc Magazine
" this is where to begin. Java in all its gory details: classes to applets, methods to multithreading."
-Thom Gillespie, Library Journal
"Teach Yourself Java gives a thoughtful treatment to under-the-hood issues of Java's implementation."
-Peter Coffee, pc Week
"If you buy one book on Java, this is the one to buy. Teach Yourself Java is one of the best introductions to hands-on Java programming. The setup of the book is extremely well thought out."
-Scott Sidel, Independent Web Review
"This is the best introduction to object-oriented programming ever written. This book does not assume that you know C or C++, but it offers tips for those who do. Laura Lemay is my favorite tech author. If you can afford only one Java book, then this is the one to get."
-David Geary
What's New in This Edition
Given the explosion of tools for building Java applications and the wide variety of things that people are doing with Java, for the Web and for general-purpose applications, there is no shortage of new things to talk about when it comes to Java.
This edition, therefore, is a fully revised and extended edition of the original Teach Yourself Java in 21 Days. It has been greatly expanded and enhanced, with all the original content updated, the weak parts fixed, and more examples added. This edition also contains a bonus week that adds further depth and detail about existing topics such as images, animation, and networking, as well as information about tools, debugging, and advanced data structures. In the bonus week you'll also learn about the following:
- Day 22 describes tools and utilities for programming in Java, including debugging techniques, Java development environments such as Symantec Café and Visual J++, the javadoc documentation system, and other tips and tricks.
- Day 23 covers creating structures for modeling various forms of data, both with the classes in the java.util package and by creating new classes.
- Day 24 goes into even more detail about animation in Java, building on the simple techniques covered in Week 2.
- Sun's java.awt.image package provides a set of classes for working with images. Day 25 covers these classes in detail, explaining the image filter architecture and how you can use it in your own Java programs.
- Day 26 takes a further look at client/server networking, with extensive examples of networking applets and applications and working with live data sent from a server, as well as connecting to databases from Java applets.
- Days 27 and 28 move into the future and describe what are known as the standard extension APIs. Many of the features you'll learn about on Day 27 will be part of Java 1.1. Day 28 finishes up with more future topics, including Sun's Java Beans API, Java chips, and the JavaOS.
The bonus week goes into great detail about upcoming features in Java 1.1 and the extension APIs. And with more than 250 pages of reference material in the appendixes, there's little you won't be able to discover using this book.
About This Book
This book teaches you all about the Java language and how to use it to create applets for the World Wide Web, as well as standalone applications. By the time you get through with this book, you'll know enough about Java and about the Java class libraries to do just about anything, inside an applet or out.
Who Should Read This Book
This book is intended for people with at least some basic programming background, which includes people with years of programming experience and people with only a small amount of experience. If you understand what variables, loops, and functions are, you'll be just fine for this book. The sorts of people who might want to read this book include you, if
- You're a real whiz at HTML, understand CGI programming (in Perl, AppleScript, Visual Basic, or some other popular CGI language) pretty well, and want to move on to the next level in Web page design.
- You had some BASIC or Pascal in school and you have a basic grasp of what programming is, but you've heard Java is easy to learn, really powerful, and very cool.
- You've programmed C and C++ for many years, you've heard this Java thing is becoming really popular, and you're wondering what all the fuss is about.
- You've heard that Java is really good for Web-based applets, and you're curious about how good it is for creating more general applications.
What if you know programming, but you don't know object-oriented programming? Fear not. This book assumes no background in object-oriented design. If you know object-oriented programming, in fact, the first couple days will be easy for you.
What if you're a rank beginner? This book might move a little fast for you. Java is a good language to start with, though, and if you take it slow and work through all the examples, you may still be able to pick up Java and start creating your own applets.
How This Book Is Structured
This book is intended to be read and absorbed over the course of four weeks. During each week, you'll read seven chapters that present concepts related to the Java language and the creation of applets and applications.
Conventions
| Note |
A note box presents interesting pieces of information related to the surrounding discussion. |
| Technical Note |
A technical note presents specific technical information related to the surrounding discussion. |
| Tip |
A tip box offers advice or teaches an easier way to do something. |
| Warning |
A warning box advises you about potential problems and helps you steer clear of disaster. |
| New terms |
New terms are introduced in new term boxes, with the new term in italics. |
| Type |
A type icon identifies some new Java code that you can type in. You can also get the code from the CD-ROM that accompanies this book. |
| Output |
An output icon shows the output from a Java program. |
| Analysis |
An analysis icon alerts you to the author's line-by-line analysis. |

