0% found this document useful (0 votes)
102 views516 pages

Java Programming

Uploaded by

Sheeba
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views516 pages

Java Programming

Uploaded by

Sheeba
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 516

abcd

net
ing
r
Sams.
Learn
Cente
Teach Yourself
JAVA
in 21 Days
S
S
F
Laura Lemay
Charles L. Perkins R
W
T
M

201 West 103rd Street


Indianapolis, Indiana 46290
v

030-4 FM 5 1/29/96, 8:10 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


S
F
R
W
abcd

net
ing
r
Sams.
Learn
Cente
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 back-
ground, 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 program-
ming? 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


M T
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.
W R

030-4 FM 1 1/29/96, 8:10 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


S
F S
W T
M T

21 Teach Yourself JAVA in 21 Days

Conventions
Note: A Note box presents interesting pieces of information related to the surround-
ing 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.
Caution: A Caution box alerts you to a possible problem and gives you advice to

! avoid it.
Warning: A Warning box advises you about potential problems and helps you steer
clear of disaster.
NEW☛
TERM New terms are introduced in New Term boxes, with the term in italics.
Type A type icon identifies some new HTML code that you can type in yourself.

Output An Output icon highlights what the same HTML code looks like when viewed by
either Netscape or Mosaic.

Analysis An analysis icon alerts you to the author’s line-by-line analysis.

ii

030-4 FM 2 1/29/96, 8:10 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


S
F S
W T
M T

21 Teach Yourself JAVA in 21 Days


To Eric, for all the usual reasons Acquisitions Editor
(moral support, stupid questions, comfort in dark times). Mark Taber
LL
Development Editor
For RKJP, ARL, and NMH Fran Hatton
the three most important people in my life. Software Development
CLP
Specialist
Merle Newlon
Copyright ©1996 by [Link] Production Editor
Publishing and its licensors Nancy Albright
FIRST EDITION Technical Reviewer
Patrick Chan
All rights reserved. No part of this book shall be reproduced, stored in a
retrieval system, or transmitted by any means, electronic, mechanical, Editorial Coordinator
photocopying, recording, or otherwise, without written permission from Bill Whitmer
the publisher. No patent liability is assumed with respect to the use of the Technical Edit
information contained herein. Although every precaution has been taken in Coordinator
the preparation of this book, the publisher and authors assume no
Lynette Quinn
responsibility for errors or omissions. Neither is any liability assumed for
damages resulting from the use of the information contained herein. For Formatter
information, address [Link] Publishing, 201 W. 103rd St., Indianapolis, Frank Sinclair
IN 46290. Editorial Assistant
International Standard Book Number: 1-57521-030-4 Carol Ackerman
Library of Congress Catalog Card Number: 95-78866 Cover Designer
Tim Amrhein
99 98 97 96 4 3 2 1
Book Designer
Interpretation of the printing code: the rightmost double-digit number is Alyssa Yesh
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 Production Team
first printing of the book occurred in 1996. Supervisor
Brad Chinn
Composed in AGaramond and MCPdigital by Macmillan Computer
Publishing Production
Michael Brumitt
Printed in the United States of America Jason Hand
All terms mentioned in this book that are known to be trademarks or Cheryl Moore
service marks have been appropriately capitalized. [Link] Publishing Ayanna Lacey
cannot attest to the accuracy of this information. Use of a term in this book Nancy Price
should not be regarded as affecting the validity of any trademark or service Bobbi Satterfield
mark. Tim Taylor
Susan Van Ness
Mark Walchle
Todd Wente
President, Sams Publishing: Richard K. Swadley
Indexer
Publisher, [Link] Publishing: George Bond
Tim Griffin
Publishing Manager: Mark Taber
Managing Editor: Cindy Morrow
Marketing Manager: John Pierce

vi

030-4 FM 6 1/29/96, 8:10 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


abcd

net
ing
r
Sams.
Learn
Cente
Overview
Introduction xxi
Week 1 at a Glance
Day 1 An Introduction to Java Programming 3

S
2 Object-Oriented Programming and Java 19
3 Java Basics 41

S
4 Working with Objects 61
5 Arrays, Conditionals, and Loops 79

F
6 Creating Classes and Applications in Java 95
7 More About Methods 111
Week 2 at a Glance
Day 8 Java Applet Basics R
129
9
10
Graphics, Fonts, and Color
Simple Animation and Threads
W 149
173
11
12
More Animation, Images, and Sound
Managing Simple Events and Interactivity T 195
217

M
13 User Interfaces with the Java Abstract Windowing Toolkit 237
14 Windows, Networking, and Other Tidbits 279
Week 3 at a Glance
Day 15 Modifiers 305
16 Packages and Interfaces 323
17 Exceptions 341
18 Multithreading 353
19 Streams 375
20 Native Methods and Libraries 403
21 Under the Hood 421
Appendixes
A Language Summary 473
B The Java Class Library 483
C How Java Differs from C and C++ 497
D How Java Differs from C and C++ 507

Index 511

vii

030-4 FM 7 1/29/96, 8:11 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


abcd

net
ing
r
Sams.
Learn
Cente
Contents
Introduction xxi
Week 1 at a Glance 1
Day 1 An Introduction to Java Programming 3
What Is Java? .............................................................................................. 4
Java’s Past, Present, and Future ................................................................... 6 S
Why Learn Java? ......................................................................................... 7
Java Is Platform-Independent................................................................. 7
S
F
Java Is Object-Oriented ......................................................................... 9
Java Is Easy to Learn .............................................................................. 9
Getting Started with
Programming in Java .............................................................................. 10
Getting the Software ............................................................................ 10
Applets and Applications ..................................................................... 11 R
W
Creating a Java Application .................................................................. 11
Creating a Java Applet ......................................................................... 13

T
Summary .................................................................................................. 16
Q&A ........................................................................................................ 16

M
Day 2 Object-Oriented Programming and Java 19
Thinking in Objects: An Analogy ............................................................. 20
Objects and Classes .................................................................................. 21
Behavior and Attributes ............................................................................ 23
Attributes ............................................................................................. 23
Behavior .............................................................................................. 24
Creating a Class ................................................................................... 24
Inheritance, Interfaces, and Packages ........................................................ 28
Inheritance........................................................................................... 29
Creating a Class Hierarchy................................................................... 30
How Inheritance Works ...................................................................... 32
Single and Multiple Inheritance ........................................................... 34
Interfaces and Packages ........................................................................ 34
Creating a Subclass ................................................................................... 35
Summary .................................................................................................. 38
Q&A ........................................................................................................ 39
Day 3 Java Basics 41
Statements and Expressions ...................................................................... 42
Variables and Data Types ......................................................................... 43
Declaring Variables .............................................................................. 43
Notes on Variable Names .................................................................... 44

ix

030-4 FM 9 1/29/96, 8:11 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


S
F S
W T
M T

21 Teach Yourself JAVA in 21 Days

Variable Types ..................................................................................... 45


Assigning Values to Variables ............................................................... 46
Comments ................................................................................................ 47
Literals ...................................................................................................... 47
Number Literals................................................................................... 47
Boolean Literals ................................................................................... 48
Character Literals ................................................................................. 48
String Literals ...................................................................................... 49
Expressions and Operators ........................................................................ 50
Arithmetic ........................................................................................... 50
More About Assignment ...................................................................... 52
Incrementing and Decrementing ......................................................... 52
Comparisons ........................................................................................ 54
Logical Operators ................................................................................ 55
Bitwise Operators ................................................................................ 55
Operator Precedence ............................................................................ 56
String Arithmetic ...................................................................................... 57
Summary .................................................................................................. 58
Q&A ........................................................................................................ 60
Day 4 Working with Objects 61
Creating New Objects .............................................................................. 62
Using new ............................................................................................ 63
What new Does ................................................................................... 64
A Note on Memory Management ........................................................ 64
Accessing and Setting Class and Instance Variables ................................... 65
Getting Values ..................................................................................... 65
Changing Values .................................................................................. 65
Class Variables ..................................................................................... 66
Calling Methods ....................................................................................... 67
Class Methods ..................................................................................... 69
References to Objects ............................................................................... 70
Casting and Converting Objects and Primitive Types .............................. 71
Casting Primitive Types ...................................................................... 71
Casting Objects .................................................................................. 72
Converting Primitive Types
to Objects and Vice Versa ................................................................. 73
Odds and Ends ......................................................................................... 73
Comparing Objects ............................................................................. 74
Copying Objects .................................................................................. 75
Determining the Class of an Object ..................................................... 76
The Java Class Libraries ............................................................................ 76
Summary .................................................................................................. 77
Q&A ........................................................................................................ 78

030-4 FM 10 1/29/96, 8:11 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


abcd

net
ing
r
Sams.
Learn
Cente
Day 5 Arrays, Conditionals, and Loops 79
Arrays ....................................................................................................... 80
Declaring Array Variables .................................................................... 80
Creating Array Objects ........................................................................ 81
Accessing Array Elements ..................................................................... 81
Changing Array Elements .................................................................... 82
Multidimensional Arrays...................................................................... 83
Block Statements ...................................................................................... 83
if Conditionals .......................................................................................... 83
The Conditional Operator ................................................................... 84
switch Conditionals ................................................................................... 85
for Loops .................................................................................................. 86
while and do Loops ................................................................................... 88
while Loops .......................................................................................... 88
do...while Loops ................................................................................... 89
Breaking Out of Loops ............................................................................. 89
Labeled Loops ...................................................................................... 90
Summary .................................................................................................. 91
Q&A ........................................................................................................ 92
Day 6 Creating Classes and Applications in Java 95
Defining Classes ....................................................................................... 96
Creating Instance and Class Variables ....................................................... 96
Defining Instance Variables ................................................................. 97
Constants ............................................................................................. 97
Class Variables ..................................................................................... 98
Creating Methods ..................................................................................... 99
Defining Methods ............................................................................... 99
The this Keyword ............................................................................... 101
Variable Scope and Method Definitions ............................................ 101
Passing Arguments to Methods .......................................................... 102
Class Methods ................................................................................... 104
Creating Java Applications ...................................................................... 105
Java Applications and Command-Line Arguments ................................. 106
Passing Arguments to Java Programs .................................................. 106
Handling Arguments in Your Java Program ....................................... 106
Summary ................................................................................................ 108
Q&A ...................................................................................................... 109
Day 7 More About Methods 111
Creating Methods with the Same Name, Different Arguments ............... 112
Constructor Methods ............................................................................. 115
Basic Constructors ............................................................................. 116
Calling Another Constructor ............................................................. 117
Overloading Constructors .................................................................. 117

xi

030-4 FM 11 1/29/96, 8:11 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


S
F S
W T
M T

21 Teach Yourself JAVA in 21 Days

Overriding Methods ............................................................................... 119


Creating Methods that Override Existing Methods ............................ 119
Calling the Original Method ............................................................. 121
Overriding Constructors .................................................................... 122
Finalizer Methods ................................................................................... 123
Summary ................................................................................................ 124
Q&A ...................................................................................................... 124
Week 2 at a Glance 127
Day 8 Java Applet Basics 129
How Applets and Applications Are Different .......................................... 130
Creating Applets ..................................................................................... 131
Major Applet Activities ...................................................................... 132
A Simple Applet................................................................................. 134
Including an Applet on a Web Page ........................................................ 136
The <APPLET> Tag.......................................................................... 136
Testing the Result .............................................................................. 137
Making Java Applets Available to the Web......................................... 137
More About the <APPLET> Tag ............................................................ 138
ALIGN .............................................................................................. 138
HSPACE and VSPACE ...................................................................... 140
CODE and CODEBASE .................................................................... 141
Passing Parameters to Applets ................................................................. 141
Summary ................................................................................................ 146
Q&A ...................................................................................................... 147
Day 9 Graphics, Fonts, and Color 149
The Graphics Class ................................................................................. 150
The Graphics Coordinate System ...................................................... 151
Drawing and Filling ............................................................................... 151
Lines .................................................................................................. 152
Rectangles .......................................................................................... 152
Polygons ............................................................................................ 155
Ovals ................................................................................................. 156
Arc ..................................................................................................... 157
A Simple Graphics Example............................................................... 161
Copying and Clearing ........................................................................ 163
Text and Fonts ....................................................................................... 163
Creating Font Objects ....................................................................... 163
Drawing Characters and Strings ......................................................... 164
Finding Out Information About a Font ............................................. 166
Color ...................................................................................................... 168
Using Color Objects .......................................................................... 168
Testing and Setting the Current Colors ............................................. 169
A Single Color Example ..................................................................... 170
Summary ................................................................................................ 171
Q&A ...................................................................................................... 171
xii

030-4 FM 12 1/29/96, 8:11 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


abcd

net
ing
r
Sams.
Learn
Cente
Day 10 Simple Animation and Threads 173
Creating Animation in Java .................................................................... 174
Painting and Repainting .................................................................... 174
Starting and Stopping
an Applet’s Execution ...................................................................... 175
Putting It Together ............................................................................ 175
Threads: What They Are
and Why You Need Them ................................................................... 177
The Problem with the Digital Clock Applet ...................................... 178
Writing Applets with Threads ............................................................ 179
Fixing The Digital Clock ................................................................... 180
Reducing Animation Flicker ................................................................... 182
Flicker and How to Avoid It .............................................................. 182
How to Override Update ................................................................... 183
Solution One: Don’t Clear the Screen ............................................... 183
Solution Two: Redraw
Only What You Have To ................................................................ 186
Summary ................................................................................................ 192
Q&A ...................................................................................................... 192
Day 11 More Animation, Images, and Sound 195
Retrieving and Using Images .................................................................. 196
Getting Images .................................................................................. 196
Drawing Images ................................................................................. 198
Modifying Images .............................................................................. 201
Creating Animation Using Images .......................................................... 201
An Example: Neko............................................................................. 201
Retrieving and Using Sounds .................................................................. 209
Sun’s Animator Applet ........................................................................... 211
More About Flicker: Double-Buffering................................................... 212
Creating Applets with Double-Buffering............................................ 212
An Example: Checkers Revisited ........................................................ 213
Summary ................................................................................................ 214
Q&A ...................................................................................................... 215
Day 12 Managing Simple Events and Interactivity 217
Mouse Clicks .......................................................................................... 218
mouseDown and mouseUp ................................................................... 219
An Example: Spots ............................................................................. 220
Mouse Movements ................................................................................. 223
mouseDrag and mouseMove ................................................................. 223
mouseEnter and mouseExit .................................................................. 223
An Example: Drawing Lines .............................................................. 224
Keyboard Events ..................................................................................... 228
The keyDown Method ....................................................................... 228
Default Keys ...................................................................................... 229

xiii

030-4 FM 13 1/29/96, 8:11 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


S
F S
W T
M T

21 Teach Yourself JAVA in 21 Days

An Example: Entering, Displaying, and Moving Characters .............. 229


Testing for Modifier Keys .................................................................. 232
The AWT Event Handler ....................................................................... 233
Summary ................................................................................................ 235
Q&A ...................................................................................................... 235
Day 13 The Java Abstract Windowing Toolkit 237
An AWT Overview................................................................................. 238
The Basic User Interface Components .................................................... 240
Labels ................................................................................................ 241
Buttons .............................................................................................. 242
Checkboxes ........................................................................................ 243
Radio Buttons .................................................................................... 244
Choice Menus ................................................................................... 245
Text Fields ......................................................................................... 247
Panels and Layout ................................................................................... 249
Layout Managers ............................................................................... 249
Insets ................................................................................................. 254
Handling UI Actions and Events ............................................................ 255
Nesting Panels and Components ............................................................ 258
Nested Panels .................................................................................... 258
Events and Nested Panels .................................................................. 258
More UI Components ............................................................................ 259
Text Areas .......................................................................................... 259
Scrolling Lists .................................................................................... 261
Scrollbars and Sliders ......................................................................... 262
Canvases ............................................................................................ 265
More UI Events ...................................................................................... 265
A Complete Example:
RGB to HSB Converter ....................................................................... 266
Create the Applet Layout ................................................................... 267
Create the Panel Layout ..................................................................... 267
Define the Subpanels ......................................................................... 269
Handle the Actions ............................................................................ 272
Update the Result .............................................................................. 272
The Complete Source Code ............................................................... 274
Summary ................................................................................................ 277
Q&A ...................................................................................................... 277
Day 14 Windows, Networking, and Other Tidbits 279
Windows, Menus, and Dialog Boxes ...................................................... 280
Frames ............................................................................................... 280
Menus ............................................................................................... 282
Dialog Boxes ...................................................................................... 285
File Dialogs........................................................................................ 287
Window Events ................................................................................. 288
Using AWT Windows in Stand-Alone Applications .......................... 288

xiv

030-4 FM 14 1/29/96, 8:11 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


abcd

net
ing
r
Sams.
Learn
Cente
Networking in Java ................................................................................. 289
Creating Links Inside Applets ............................................................ 290
Opening Web Connections ............................................................... 292
openStream() ...................................................................................... 293
The URLconnection Class ................................................................... 296
Sockets ............................................................................................... 296
Other Applet Hints ................................................................................ 297
The showStatus Method ..................................................................... 297
Applet Information ............................................................................ 298
Communicating Between Applets ...................................................... 298
Summary ................................................................................................ 299
Q&A ...................................................................................................... 300
Week 3 at a Glance 303
Day 15 Modifiers 305
Method and Variable Access Control ...................................................... 307
The Four P’s of Protection ................................................................. 307
The Conventions for Instance Variable Access ................................... 312
Class Variables and Methods .................................................................. 314
The final Modifier .................................................................................. 316
final Classes ....................................................................................... 316
final Variables .................................................................................... 317
final Methods .................................................................................... 317
abstract Methods and Classes .................................................................. 319
Summary ................................................................................................ 320
Q&A ...................................................................................................... 320
Day 16 Packages and Interfaces 323
Packages ................................................................................................. 324
Programming in the Large ................................................................. 324
Programming in the Small ................................................................. 327
Hiding Classes ................................................................................... 329
Interfaces ................................................................................................ 331
Programming in the Large ................................................................. 331
Programming in the Small ................................................................. 335
Summary ................................................................................................ 338
Q&A ...................................................................................................... 339
Day 17 Exceptions 341
Programming in the Large ...................................................................... 342
Programming in the Small ...................................................................... 345
The Limitations Placed on the Programmer ........................................... 348
The finally Clause ................................................................................... 349
Summary ................................................................................................ 350
Q&A ...................................................................................................... 351

xv

030-4 FM 15 1/29/96, 8:11 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


S
F S
W T
M T

21 Teach Yourself JAVA in 21 Days

Day 18 Multithreading 353


The Problem with Parallelism ................................................................. 354
Thinking Multithreaded ......................................................................... 355
Points About Points ........................................................................... 357
Protecting a Class Variable ................................................................. 360
Creating and Using Threads ................................................................... 361
The Runnable Interface ...................................................................... 362
ThreadTester ...................................................................................... 363
NamedThreadTester ........................................................................... 365
Knowing When a Thread has Stopped ................................................... 366
Thread Scheduling ................................................................................. 367
Preemptive Versus Nonpreemptive .................................................... 367
Testing Your Scheduler ...................................................................... 368
Summary ................................................................................................ 371
Q&A ...................................................................................................... 372
Day 19 Streams 375
Input Streams ......................................................................................... 377
The abstract Class InputStream ........................................................... 377
ByteArrayInputStream ......................................................................... 381
FileInputStream .................................................................................. 382
FilterInputStream ............................................................................... 383
PipedInputStream ............................................................................... 389
SequenceInputStream .......................................................................... 389
StringBufferInputStream ..................................................................... 390
Output Streams ...................................................................................... 391
The abstract Class OutputStream ........................................................ 391
ByteArrayOutputStream ...................................................................... 392
FileOutputStream ............................................................................... 393
FilterOutputStream ............................................................................. 394
PipedOutputStream ............................................................................ 399
Related Classes ....................................................................................... 399
Summary ................................................................................................ 399
Q&A ...................................................................................................... 400
Day 20 Native Methods and Libraries 403
Disadvantages of native Methods ............................................................ 404
The Illusion of Required Efficiency ........................................................ 405
Built-In Optimizations ...................................................................... 407
Simple Optimization Tricks............................................................... 407
Writing native Methods .......................................................................... 408
The Example Class ............................................................................ 409
Generating Header and Stub Files ..................................................... 410
Creating SimpleFileNative.c .............................................................. 414

xvi

030-4 FM 16 1/29/96, 8:11 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


abcd

net
ing
r
Sams.
Learn
Cente
A Native Library ..................................................................................... 417
Linking It All ..................................................................................... 418
Using Your Library ............................................................................ 418
Summary ................................................................................................ 418
Q&A ...................................................................................................... 419
Day 21 Under the Hood 421
The Big Picture ...................................................................................... 422
Why It’s a Powerful Vision ................................................................ 423
The Java Virtual Machine ....................................................................... 423
An Overview ...................................................................................... 424
The Fundamental Parts...................................................................... 426
The Constant Pool ............................................................................ 430
Limitations ........................................................................................ 430
Bytecodes in More Detail ....................................................................... 431
The Bytecode Interpreter ................................................................... 431
The “Just-in-Time” Compiler ............................................................ 432
The java2c Translator ........................................................................ 433
The Bytecodes Themselves ................................................................ 434
The _quick Bytecodes ........................................................................ 450
The .class File Format ............................................................................. 452
Method Signatures ................................................................................. 454
The Garbage Collector ........................................................................... 455
The Problem ...................................................................................... 455
The Solution ...................................................................................... 456
Java’s Parallel Garbage Collector ........................................................ 459
The Security Story .................................................................................. 459
Why You Should Worry .................................................................... 459
Why You Might Not Have To .......................................................... 460
Java’s Security Model ......................................................................... 460
Summary ................................................................................................ 470
Q&A ...................................................................................................... 470
A Language Summary 473
Reserved Words ...................................................................................... 474
Comments .............................................................................................. 475
Literals .................................................................................................... 475
Variable Declaration ............................................................................... 476
Variable Assignment ............................................................................... 476
Operators ............................................................................................... 477
Objects ................................................................................................... 478
Arrays ..................................................................................................... 478
Loops and Conditionals .......................................................................... 478
Class Definitions .................................................................................... 479
Method and Constructor Definitions ..................................................... 479
Packages, Interfaces, and Importing ........................................................ 480
Exceptions and Guarding ....................................................................... 481

xvii

030-4 FM 17 1/29/96, 8:12 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


S
F S
W T
M T

21 Teach Yourself JAVA in 21 Days

B Class Hierarchy Diagrams 483


About These Diagrams ........................................................................... 495
C The Java Class Library 497
[Link] ................................................................................................. 498
Interfaces ........................................................................................... 498
Classes ............................................................................................... 498
[Link] .................................................................................................. 499
Interfaces ........................................................................................... 499
Classes ............................................................................................... 499
[Link] ..................................................................................................... 500
Interfaces ........................................................................................... 500
Classes ............................................................................................... 500
[Link] ................................................................................................... 501
Interfaces ........................................................................................... 501
Classes ............................................................................................... 502
[Link] .................................................................................................. 502
Interfaces ........................................................................................... 502
Classes ............................................................................................... 502
[Link] ........................................................................................ 504
Interfaces ........................................................................................... 504
Classes ............................................................................................... 504
[Link] ........................................................................................... 505
[Link] ............................................................................................... 505
Interfaces ........................................................................................... 505
Classes ............................................................................................... 505
D How Java Differs from C and C++ 507
Pointers .................................................................................................. 508
Arrays ..................................................................................................... 508
Strings .................................................................................................... 508
Memory Management ............................................................................ 509
Data Types ............................................................................................. 509
Operators ............................................................................................... 509
Control Flow .......................................................................................... 510
Arguments .............................................................................................. 510
Other Differences ................................................................................... 510
Index 511

xviii

030-4 FM 18 1/29/96, 8:12 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


abcd

net
ing
r
Sams.
Learn
Cente
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.

xix

030-4 FM 19 1/29/96, 8:12 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


S
F S
W T
M T

21 Teach Yourself JAVA in 21 Days

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@[Link], or visit her home page at [Link]
lemay/.

Charles L. Perkins is the founder of Virtual Rendezvous, a company building what it spent two
years designing: a software layer above Java 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@[Link], or visit his Java page at http://
[Link]/java.

xx

030-4 FM 20 1/29/96, 8:12 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


abcd

net
ing
r
Sams.
Learn
Cente
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 of containing 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.

xxi

030-4 FM 21 1/29/96, 8:12 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


S
F S
W T
M T

21 Teach Yourself JAVA in 21 Days

■ 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
beta 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.
Teach Yourself Java in 21 Days uses primarily Java beta because that is the version that is most
current and is the version that will continue to be used in the future. The alpha API is obsolete
and will eventually die out. If you learn Java using beta API, you’ll be much better prepared for
any future changes (which will be minor) 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.

xxii

030-4 FM 22 1/29/96, 8:12 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


abcd

net
ing
r
Sams.
Learn
Cente
■ 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, includ-
ing 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.
xxiii

030-4 FM 23 1/29/96, 8:12 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


S
F S
W T
M T

21 Teach Yourself JAVA in 21 Days

■ 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” techni-
cal 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 [Link] 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 [Link]
This book also has a companion Web site at [Link] 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.

xxiv

030-4 FM 24 1/29/96, 8:12 PM

P2/V4SQC6 TY Java in 21 Days 030-4 louisa 12.31.95 FM LP#4


abcd

net
ing
SWEEK

r
Sams.
Learn
Cente
S

1
F 1

AT A GLANCE
R
W 2
T
M 3

4
■ An Introduction to Java Programming
Platform independence
The Java compiler and the java interpreter
■ Object-Oriented Programming and Java 5
Objects and classes
Encapsulation
Modularity
■ Java Basics 6
Java statements and expressions
Variables and data types
Comparisons and logical operators
■ Working with Objects 7
Testing and modifying instance variables
Converting objects
■ Arrays, Conditionals, and Loops
Conditional tests
Iteration
Block statements
1

030-4s AAG 01 1 1/29/96, 8:13 PM


P2/V4/sqc8 TY Java in 21 Days 030-4 Everly 12.11.95 AAG1 LP#2
S
S
F

M
T
W
R
WEEK

1 Week 1 at a Glance

■ Creating Classes and Applications in Java


Defining constants, instance and class
variables, and methods
■ More About Methods
Overloading methods
Constructor methods
Overriding methods

030-4s AAG 01 2 1/29/96, 8:13 PM

P2/V4/sqc8 TY Java in 21 Days 030-4 Everly 12.11.95 AAG1 LP#2


abcd

net
ing
r
Sams.
Learn
Cente
1
1

S
S WEEK
1
F
R
W
An Introduction to
T Programming
Java
M
by Laura Lemay

030-4s CH01.i 3 1/29/96, 8:34 PM


P2/V4sqc7 TY Java in 21 Days 030-4 sdv 12.22.95 Ch01 LP#4
S
S
F

M
T
W
R
DAY

1 An Introduction to Java Programming

Hello and welcome to Teach Yourself Java in 21 Days! Starting today and for the next three weeks
you’ll learn all about the Java language and how to use it to create applets, as well as how to create
stand-alone Java applications that you can use for just about anything.

NEW☛ An applet is a dynamic and interactive program that can run inside a Web page displayed
TERM by a Java-capable browser such as HotJava or Netscape 2.0.
The HotJava browser is a World Wide Web browser used to view Web pages, follow links, and
submit forms. It can also download and play applets on the reader’s system.
That’s the overall goal for the next three weeks. Today, the goals are somewhat more modest,
and you’ll learn about the following:
■ What exactly Java and HotJava are, and their current status
■ Why you should learn Java—its various features and advantages over other program-
ming languages
■ Getting started programming in Java—what you’ll need in terms of software and
background, as well as some basic terminology
■ How to create your first Java programs—to close this day, you’ll create both a simple
Java application and a simple Java applet!

What Is Java?
Java is an object-oriented programming language developed by Sun Microsystems, a company
best known for its high-end Unix workstations. Modeled after C++, the Java language was
designed to be small, simple, and portable across platforms and operating systems, both at the
source and at the binary level (more about this later).
Java is often mentioned in the same breath as HotJava, a World Wide Web browser from Sun