41bb726c

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

Day 2   Object-Oriented Programming and Java

Day 3   Java Basics

Day 4   Working with Objects

Day 5   Arrays, Conditionals, and Loops

Day 6   Creating Classes and Applications in Java

Day 7   More About Methods

Day 8   Java Applet Basics

Day 9   Graphics, Fonts, and Color

Day 10   Simple Animation and Threads

Day 11   More Animation, Images, and Sound

Day 12   Managing Simple Events and Interactivity

Day 13   Creating User Interfaces with the awt

Day 14   Windows, Networking, and Other Tidbits

Day 15   Modifiers, Access Control, and Class Design

Day 16   Packages and Interfaces

Day 17   Exceptions

Day 18   Multithreading

Day 19   Streams and I/O

Day 20   Using Native Methods and Libraries

Day 21   Under the Hood

Day 22   Java Programming Tools

Day 23   Working with Data Structures in Java

Day 24   Advanced Animation and Media

Day 25   Fun with Image Filters

Day 26   Client/Server Networking in Java

Day 27   The Standard Extension APIs

Day 28   Emerging Technologies

appendix A   Language Summary

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

appendix G   java.awt.image Package Reference

appendix H   java.awt.peer Package Reference

appendix I   java.io Package Reference

appendix J   java.lang Package Reference

appendix K   java.net Package Reference

appendix L   java.util Package Reference


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 EditorKitty Wilson
Copy Editors Kimberly K. Hannel, Colleen Williams IndexerJohnna 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 AmrheinBook Designer Gary Adair
Copy Writer Peter FullerProduction Team Supervisor Brad Chinn
ProductionCynthia 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!

Laura Lemay
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:

Week 2 is dedicated to applets and the Java class libraries:

Week 3 includes advanced topics for when you start doing larger and more complex Java programs or when you want to learn more:

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:

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

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:

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

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.