Teach Yourself Java in 21 Days tyjfm.htm

- Teach Yourself JAVA
- (c)About This Book
- Who Should Read This Book
- How This Book Is Structured
- Conventions

- Copyright © 1996 by Sams.net Publishing

- Overview

- Acknowledgments
- About the Authors
- Introduction

- Who Should Read This Book
- How This Book Is Organized

- Conventions Used in This Book
- Web Sites for Further Information

### Teach Yourself JAVA

Laura Lemay
Charles L. Perkins

Sams.net
201 West 103rd Street
Indianapolis, Indiana 46290

### (c)About This Book

This book teaches you all about the Java language and how to use it to create applets and applications. 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.

### 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 or 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 all 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 of days will be easy for you.

### How This Book Is Structured

This book is intended to be read and absorbed over the course of three 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 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 offers advice or teaches an easier way to do something.

Caution: A Caution alerts you to a possible problem and gives you advice to avoid it.

Warning: A Warning advises you about potential problems and helps you steer clear of disaster.

New terms are introduced in New Term boxes, with the term in italics.

To Eric, for all the usual reasons
(moral support, stupid questions, comfort in dark times).
LL

For RKJP, ARL, and NMH
the three most important people in my life.
CLP

##### Copyright © 1996 by Sams.net Publishing

FIRST EDITION

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 authors 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-030-4

Library of Congress Catalog Card Number: 95-78866

99 98 97 96 4 3

Interpretation of the printing code: the rightmost double-digit number is the year of the book's printing; the rightmost single-digit, the number of the book's printing. For example, a printing code of 96-1 shows that the first printing of the book occurred in 1996.

Printed in the United States of America

All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams.net Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.

President, Sams Publishing:

Richard K. Swadley

Publisher, Sams.net Publishing:

George Bond

Publishing Manager:

Mark Taber

Managing Editor:

Cindy Morrow

Marketing Manager:

John Pierce

Acquisitions Editor

Mark Taber

Development Editor

Fran Hatton

Software Development Specialist

Merle Newlon

Production Editor

Nancy Albright

Technical Reviewer

Patrick Chan

Editorial Coordinator

Bill Whitmer

Technical Edit Coordinator

Lynette Quinn

Formatter

Frank Sinclair

Editorial Assistant

Carol Ackerman

Cover Designer

Tim Amrhein

Book Designer

Alyssa Yesh

Production Team Supervisor

Brad Chinn

Production

Michael Brumitt

Jason Hand

Cheryl Moore

Ayanna Lacey

Nancy Price
Bobbi Satterfield

Tim Taylor

Susan Van Ness

Mark Walchle
Todd Wente

Indexer

Tim Griffin

## Overview

Introduction
Week 1 at a Glance
Day 1 An Introduction to Java Programming
2 Object-Oriented Programming and Java
3 Java Basics
4 Working with Objects
5 Arrays, Conditionals, and Loops
6 Creating Classes and Applications in Java
7 More About Methods111
Week 2 at a Glance
Day 8 Java Applet Basics
9 Graphics, Fonts, and Color
10 Simple Animation and Threads
11 More Animation, Images, and Sound
12 Managing Simple Events and Interactivity
13 User Interfaces with the Java Abstract Windowing Toolkit
14 Windows, Networking, and Other Tidbits
Week 3 at a Glance
Day 15 Modifiers
16 Packages and Interfaces
17 Exceptions
18 Multithreading
19 Streams
20 Native Methods and Libraries
21 Under the Hood
Appendixes
A Language Summary
B Class Hierarchy Diagrams
C The Java Class Library
D How Java Differs from C and C++
Index

### 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.

### About the Authors

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 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 reach her by e-mail at lemay@lne.com, or visit her home page at http://www.lne.com/lemay/.

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.

### 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, multi-user 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 as such, 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 where Teach 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.

#### Who Should Read This Book

Teach Yourself Java in 21 Days 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 one or more of the following is true:

- 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 onto the next level in Web page design.
- You had some Basic or Pascal in school, you've got 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 all 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. Teach Yourself Java in 21 Days assumes no background in object-oriented design. If you know object-oriented programming, the first couple of 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 Organized

Teach Yourself Java in 21 Days describes Java primarily in its current state—what's known as the 1.0 API (Application Programming Interface). This is the version of Java that Netscape and other browsers, such as Spyglass's Mosaic, support. A previous version of Java, the alpha API, was significantly different from the version described in this book, and the two versions are not compatible with each other. There are other books that describe only the alpha API, and there may still be programs and browsers out there that can only run using alpha Java programs.

The 1.0 API is, as of this writing, the most current version, the one supported by Java-enabled browsers like Netscape Navigator 2.0, and the one most likely to be supported in the future. The alpha API is obsolete and will eventually die out. If you learn Java using the current API, you'll be much better prepared for Java's future than if you have to worry about both APIs at once.

Java is still in development. "Beta" means that Java is not complete and that things may change between the time this book is being written and the time you read this. Keep this in mind as you work with Java and with the software you'll use to create and compile programs. If things aren't behaving the way you expect, check the Web sites mentioned at the end of this introduction for more information.

Teach Yourself Java in 21 Days covers the Java language and its class libraries in 21 days, organized as three separate weeks. 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 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, as well as how to put together a Java application (an application being a Java program that can run on its own without a Web browser).
- Day 7 builds on what you learned on Day 6. On Day 7, 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 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 what threads and their uses are.
- 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; on that day you'll learn about using Java's Abstract Windowing Toolkit to create a user interface in your applet including menus, buttons, checkboxes, and other elements.
- On Day 14, you explore the last of the main Java class libraries for creating applets: windows and dialogs, networking, and a few other tidbits.

Week 3 finishes up with 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.
- Finally, 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.

### 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.

to mimic the way text looks on your screen. Variables and placeholders will appear in monospace italic.

The end of each chapter offers common questions asked about that day's subject matter with answers from the authors.

### Web Sites for Further Information

Before, while, and after you read this book, there are two 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, the HotJava web browser, and online documentation for all aspects of the Java language. 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 a site for developer resources, called Gamelan, at http://www.gamelan.com/.

This book also has a companion Web site at http://www.lne.com/Web/Java/. Information at that site includes examples, more information and background for this book, corrections to this book, and other tidbits that were not included here.