developing professional java applets
TRANSCRIPT
-
8/22/2019 Developing Professional Java Applets
1/548
CONTENTS
DevelopingProfessional
JavaApplets
y K.C. HopsonStephen E. Ingram
C O N T E N T S
ntroduction
Chapter1 The Java Development Environment Tough Problems in Search of One Solution
Why Java Is a Comprehensive Solution
Why Object-Oriented Is Important
Java as an Object-Oriented Language
Java as a Portable Environment
Java as High Performance
-
8/22/2019 Developing Professional Java Applets
2/548
CONTENTS
Java in the World of Distributed Computing
Java as a Secure Environment
General Features of the Java Programming Language
Data Types
Literals
Variables
Comments Operators
Keywords and Conditionals
Loops
Arrays
Applets and Standalone Applications
Creating an Applet
Creating a Standalone Application
Applets Versus Standalone Applications
Summary
Chapter2 Object-Oriented Development in Java
Introduction to Java Classes and Objects
Basic Structure of a Class
Creating an Object Instance
Using Methods Overloading Methods
Constructors
Inheritance in Java
Subclassing
Method Overriding
Calling Superclass Methods
Calling Superclass Constructors
Important Core Classes The Object Base Class
String Classes
Type Wrappers
More about Classes
Access Modifiers
Class Methods and Class Variables
The final Modifier
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (2 of 21) [7/31/02 10:12:32 AM]
http://-/?-http://-/?-http://-/?-http://-/?- -
8/22/2019 Developing Professional Java Applets
3/548
CONTENTS
The null Keyword and More about Garbage Collection
Scoping Rules
Casting Rules
Other Keywords
Introduction to Exception Handling
Structure of an Exception Handler
When to Catch Exceptions Exception Handlers and Exception Classes
Nested Exceptions
Organizing Projects in Java
Abstract Methods
Interfaces
Packages
The Java Developer's Kit
Summary
Chapter3 Building a Spreadsheet Applet
Overview of AWT: Part 1
AWT Classes
Components and Containers
Layouts
Event Handling Exception Classes
The Throwable Class
Exception Class Hierarchy
Exception Handlers and Throwable Classes
Writing Custom Exception Handlers
Class Organization
The Cell Class
The Cell Container Class The FormulaParserClass
The FormulaParserException Class
The ArgValue Class
The SpreadsheetCell Class
The SpreadsheetContainer Class
The SpreadsheetFrame Class
The SpreadsheetApplet class
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (3 of 21) [7/31/02 10:12:32 AM]
http://-/?-http://-/?- -
8/22/2019 Developing Professional Java Applets
4/548
CONTENTS
Summary
Chapter4 Enhancing the Spreadsheet Applet
Overview of AWT: Part 2
Windows and Frames
Menus
Dialogs
Colors
Fonts
The Toolkit Class
I/O and Streams
Structure of the java.io Package
I/O and Security
I/O Exceptions
InputStream Classes
OutputStream Classes
FilterOutputStream Classes and FileOutputStream
Other Output Classes
Other I/O Classes
Tutorial
Class Organization
Adding the Color Dialog Font Dialog Box
The FileDialog Class
Saving a Spreadsheet File
Opening a Spreadsheet File
Summary
Chapter5 Adding Graphs and Scrollbars to the
Spreadsheet
Tutorial
Class Organization
Adding Scrollbars
Adding the Scrollbar Class
Handling Scrollbar Events
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (4 of 21) [7/31/02 10:12:32 AM]
-
8/22/2019 Developing Professional Java Applets
5/548
CONTENTS
Inside the SpreadsheetContainer Paint Methods
Marking Cells
Drawing Graphs
Summary
Chapter6 Building a Catalog Applet
Basics of the Applet Class
Applets and HTML
Applets and Images
Applets and Audio
Under the Applet Hood
Creating and Reading a URL
Chapter Project
Class Organization
Catalog HTML
The Catalog Class
The CatalogButton Class
The SelectionCanvas Class
The MediaLoader Class
The MediaLoaderException Class
Summary
Chapter7 Java and Images
Displaying Images
Loading Java Images
Image Display
Image Observers
Tracking Image Loading The Consumer/Producer Model
Java Color Models
Default RGB
Direct Color
Index Color
Chapter Project: Displaying a Windows BMP Image
Using Image Types Not Supported by Java
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (5 of 21) [7/31/02 10:12:32 AM]
http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?- -
8/22/2019 Developing Professional Java Applets
6/548
CONTENTS
Memory Images
Loading Foreign Images
BMP File Format
Reading Unsigned Binary in Java
Creating the Color Table
Constructing the Image
Summary
Chapter8 Adding Threads to Applets
What Is a Thread?
Creating a Thread with the Thread Class
Enhancing Your First Multithreaded Applet
The Runnable Interface
Synchronization
A TestStack Class That Is Not Thread-Safe
Introducing the Synchronized Modifier
Notify and Wait
More About Threads
ThreadGroups
ThreadDeath
Talking Threads: Pipes and Threads
Chapter Project Class Organization
Catalog HTML and Preload File
The MediaLoaderThread and MediaObserver Classes
The MediaLoader Class
The MediaSweeper Class
The Queue Class
The BMPImage Class
The Catalog Class The CatalogButton Class
The SelectionCanvas Class
Summary
Chapter9 Java Socket Programming
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (6 of 21) [7/31/02 10:12:33 AM]
http://-/?-http://-/?- -
8/22/2019 Developing Professional Java Applets
7/548
CONTENTS
An Introduction to Sockets
Socket Transmission Modes
Java Connection-Oriented Classes
Iterative and Concurrent Servers
Java Datagram Classes
Applet Security and Sockets
Chapter Project: HTTP Server Application and Client Applet Chapter Project: HTTP Server Application and Client Applet
Basic Web Server
Client Datagram Applet
Client Applet
Summary
Chapter10 Native Methods and Java
Deciding to Use Native Methods
Native Methods from the Java Side
Writing Native Methods
Using Javah
Java Arrays
The Stubs Code
Chapter Project: A Database Interface Library Using ODBC
Calling Back Into Java Constructing Java Objects from C
Creating the Library
Database Server
Adding Packet Assembly to DGTP
The Election Server
Election Client
Summary
Chapter11 Building a Live Data Applet
Observers and the Model-View Paradigm
Chapter Project
General Architecture of the Project
Changes to the Server
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (7 of 21) [7/31/02 10:12:33 AM]
-
8/22/2019 Developing Professional Java Applets
8/548
CONTENTS
Applet Client
Summary
Chapter12 Handling Dynamic Content
Introducing the HotJava Browser
Dynamic Content
Security Model
Alpha3 Distribution Differences
Altering the HotJava Source
Buffered Streams Primer
Making the Changes
Compiling Under HotJava
Toward a More Perfect Server
Adding a Configuration File
Adding Standard Logging
Building Log Information
Altering the Send Routines
Creating New Content Types
Writing Content Handlers
Summary
Chapter13 Animation and Image Filters
Simple Animation Using Images
Image Producers
Image Consumers
Filtering an Image
FilteredImageSource
Writing a Filter
Static Image Filter: Rotation
Double Buffering
Dynamic Image Filter: FXFilter
Corporate Presentation Applet
How the PresentImage Applet Works
Summary
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (8 of 21) [7/31/02 10:12:33 AM]
http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?- -
8/22/2019 Developing Professional Java Applets
9/548
CONTENTS
Chapter14 Advanced Image Processing
Chapter Project
Class Organization
How It Works
Fractals and the Mandelbrot Set
Using the Applets
The Mandelbrot Class
CalculateFilterNotify Interface
CalculatorProducer Interface
The CalculatorFilter Class
The CalculatorImage Class
The MandelApp Class
The MandelZoomApp Class
The BmpImage Class
Automatic Documentation with javadoc
Summary
AppendixA Inside the Java Virtual Machine
The Class File
Layout
The Virtual Machine
Registers
Operand Stack
Primitive Types
Local Variables
The Verifier
Exception Handling
Bytecodes
Test Class Bytecodes
Garbage Collection
AppendixB Language Grammar
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (9 of 21) [7/31/02 10:12:33 AM]
http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?-http://-/?- -
8/22/2019 Developing Professional Java Applets
10/548
CONTENTS
Credits
To my wife, Ann, whose love, patience, assistance, and encouragement made it
possible for me to write this book.-K.C. Hopson
To my wife, Anne, and my son, Mitchell; their love and encouragement gave me
the strength to write this book.-Stephen Ingram
Copyright 1996 by Sams.net Publishing
IRST EDITION
All rights reserved. No part of this book shall beeproduced, stored in a retrieval system, orransmitted by any means, electronic, mechanical
photocopying, recording, or otherwise, without
written permission from the publisher. No patentability is assumed with respect to the use of thenformation contained herein. Although everyprecaution has been taken in the preparation of thbook, the publisher and author assume no
esponsibility for errors or omissions. Neither isny liability assumed for damages resulting fromhe use of the information contained herein. Fornformation, address Sams.net Publishing, 201 W03rd St., Indianapolis, IN 46290.
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (10 of 21) [7/31/02 10:12:33 AM]
-
8/22/2019 Developing Professional Java Applets
11/548
CONTENTS
nternational Standard Book Number: 1-57521-083
HTML conversion by :
M/s. LeafWriters (India) Pvt. Ltd.Website: http://leaf.stpn.soft.net
e-mail: [email protected]
rademarks
All terms mentioned in this book that are known tbe trademarks or service marks have been
ppropriately capitalized. Sams.net Publishingannot attest to the accuracy of this information.
Use of a term in this book should not be regarded
s affecting the validity of any trademark or servicmark.
ava is a trademark of Sun Microsystems, Inc.
President, Sams Publishing Richard K. Swadley
Publishing Manager Mark Taber
Managing Editor Cindy Morrow
Marketing Manager John Pierce
Assistant Marketing Manager Kristina Perry
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (11 of 21) [7/31/02 10:12:33 AM]
http://leaf.stpn.soft.net/mailto:[email protected]:[email protected]://leaf.stpn.soft.net/ -
8/22/2019 Developing Professional Java Applets
12/548
CONTENTS
cquisitions Editor Mark Taber Development Editor Kelly Murdock
oftware Development
pecialist
Cari Skaggs Production Editor Lisa M. Lord
opy Editors Howard Jones, Anne
Owen
Technical Reviewer Greg Guntle
ditorial Coordinator Bill Whitmer Technical Edit
Coordinator
Lynette Quinn
ormatter Frank Sinclair Editorial Assistant Sharon Cox
over Designer Tim Amrhein Book Designer Alyssa Yesh
roduction Team
upervisor
Brad Chinn
roduction Mary Ann Abramson, Stephen Adams, Carol G. Bowers, Georgiana Brigg
Jeanne Clark, Jason Hand, Daniel Harris, Mike Henry, Clint Lahnen, Pa
Lowell, Steph Mineart, Ryan Oldfather, Casey Price, Laura Robbins, Bob
Satterfield, Ian Smith, SA Springer, Chris Wilcox
cknowledgments
We would like to thank our acquisitions editor,Mark Taber, our development editor, KellyMurdock, and our production editor, Lisa Lord, fo
patiently guiding some lost sheep through theirrst book.
bout the Authors
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (12 of 21) [7/31/02 10:12:33 AM]
-
8/22/2019 Developing Professional Java Applets
13/548
CONTENTS
K.C. Hopson is president of Geist Software andServices, Inc., an independent consultant firm inhe Baltimore/Washington D.C. metro area.
However, K.C. thrives in cyberspace and enjoys
sing it anywhere in the world. He specializes inistributed computing solutions and has deepxperience in GUI programming (especially
Windows), relational databases, and client/serverprogramming. K.C. was a lead architect of the
oftware used in Bell Atlantic's Stargazernteractive television system and writes regularlybout Java. K.C. has a B.S. in applied mathematicrom the University of California-Irvine and a
master's in computer science from the University Maryland, Baltimore County. In his spare time, K.C
njoys his family, worships music of all kinds,tudies history, and loves literature.
K.C. can be reached [email protected], or visit his hom
page athttp://www.universe.digex.net/~chopson.
Stephen E. Ingram is an computer consultant in thWashington D.C. metro area, specializing in
mbedded data communications and object-
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (13 of 21) [7/31/02 10:12:33 AM]
mailto:[email protected]://www.universe.digex.net/~chopsonhttp://www.universe.digex.net/~chopsonmailto:[email protected] -
8/22/2019 Developing Professional Java Applets
14/548
CONTENTS
oriented design. He holds an electrical engineerinegree from Virginia Tech and has been
programming for 15 years. He was the architectbehind the language of Bell Atlantic's Stargazer
nteractive television project; it was here that herst encountered Java. When he's not working,
Steve likes to sail the Chesapeake Bay with his wnd son. Steve can be reached [email protected].
ntroduction
ava is frequently described as a programminganguage for the Internet. This reference mainlylludes to Java's ability to be executed as an
applet, which is a program that runs inside a Javanabled World Wide Web browser, such as
Netscape Navigator 2.0 or HotJava. Appletsaturally function as small programs that cannhance your Web page. This stems from Java's
tructure as a distributed language and itsorresponding ability to load small pieces of codes needed. In the short run, programmers will useava to add small snippets of code, such asnimations, to enhance a Web page experience.
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (14 of 21) [7/31/02 10:12:33 AM]
mailto:[email protected]:[email protected] -
8/22/2019 Developing Professional Java Applets
15/548
CONTENTS
ava applets, however, are much more than smallprograms that supplement Web pages. Java is a
ophisticated and extendable environment,providing the foundation for building industrial-
trength applications. This power stems fromava's many facets-from its object-oriented natureo its simplicity to its ability to function inistributed environments. Consequently, to viewava as a "neat" tool for sprucing up your Web
pages is a serious understatement of itsapabilities. Java applets will appear in moreuises than just the Internet, and Java's role insid
nternal networks-the so-called "Intranet"-is alreadbeing given serious consideration.
Developing Professional Java Appletsaims to helbring Java applets out of the world of lightweightprograms-like simple animations-into the world ofpractical programming. This book attempts to fill
ap that has been seriously lacking in currently
xisting Java literature: a book full of serious,practical, and professional Java projects and
xamples. The projects in this book illustrate howo create Java applets that solve real-life problemnd they do so in such a way that you will learn a
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (15 of 21) [7/31/02 10:12:33 AM]
-
8/22/2019 Developing Professional Java Applets
16/548
CONTENTS
he general features, as well as subtleties, of Javawhile you're working through practical applicationof serious projects. In doing so, you will not onlybecome a more capable Java programmer, but yo
might also develop insights on how to use Java toreate a great new application.
Who Should Read This Book
Developing Professional Java Appletsis intended
or people who do not want to spend 200 pagesearning basic Java (such as forloops), but want
o quickly step into serious Java programming. Too this, however, requires you to have some
background. In general, a basic background inprogramming and a rudimentary understanding ohe principles of object-oriented programminghould be enough. If you have any of the followinredentials, then you are set:
Have read and understood another book or
literature on the basics of Java.
Have some experience in C or C++.
f you are lacking these credentials, don't worry.ust take more time going through the first part of
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (16 of 21) [7/31/02 10:12:33 AM]
-
8/22/2019 Developing Professional Java Applets
17/548
CONTENTS
he book (an introduction to Java). If you have thebackground just described, however, this book wead you deep into Java programming before younow it!
ow This Book Is Organized
This book is based on the Java Development KitJDK), version 1.0. Most of the chapters of
Developing Professional Java Appletshave a
utorial section that covers some JDK topics,ollowed by a serious chapter project. The chapte
project is accompanied by a discussion of theproject's general architecture, as well as any Java
ubtleties it might uncover. By the time you areone with any given chapter, you will have beenxposed to at least one serious Java programminoncept.
Part I of the book is a quick overview of theundamentals of Java programming. If you have n
xperience with Java, this part should be enough et you ready for the heart of the book. It includes
plenty of examples to illustrate key ideas. Howevehe book's focus is on practical Java programmino some of the discussions of Java basics are
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (17 of 21) [7/31/02 10:12:33 AM]
-
8/22/2019 Developing Professional Java Applets
18/548
CONTENTS
erse. However, almost all the topics broached inPart I will reappear frequently throughout the restof the book.
Parts II through IV are the heart of the book. Eachof these parts walks through a serious project ovehe course of three chapters. By the end of each
part, you will not only have seen the developmentof a major project, but will have attained some dee
nderstanding of one or more crucial topics in Japrogramming.
n Part II, you'll see the development of apreadsheet applet. This applet will guide youhrough the basics of Java's graphical toolkit, AW
You will not only learn the general workings ofAWT, but will also be exposed to some of its
idden gems, such as its Toolkit class. Since (ateast for a while) most Java applets will use AWT he basis for their user interfaces, a solidnderstanding of the package is indispensable.
Part II also includes in-depth discussions of I/Otreams in Java, as well as an exploration of Java
powerful approach to exception handling.
Part III uses a catalog-style applet to introduce yo
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (18 of 21) [7/31/02 10:12:33 AM]
-
8/22/2019 Developing Professional Java Applets
19/548
CONTENTS
o the more advanced concepts of URL streams,hreads, and image processing. This catalog applehows how to tie information on one catalog pageo that on another. The applet features a media
oader that uses threads and advanced imagingoncepts to bring in images that may be needed ihe future; this is a "pre-loader" that can be used educe the latencies often associated with images
By the end of this part, you will have been throug
ome of Java's most complex features.
Part IV takes you into the world of Javalient/server programming. It introduces you toava network programming through the creation on HTTP server. This server will actually downloa
ava applets to a client! You will also be shownow to use Java native methods-code written in C
by tying in databases (through the ODBCmechanism) to your server. Finally, you will see a
pplet that gets data from the server as it changes
n real-time-what the book calls "live data." Afterhis part of the book, you will have seen seriousreatments of most of the major concepts in Java
programming.
Part V lets you have a little break-but just a little
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (19 of 21) [7/31/02 10:12:33 AM]
-
8/22/2019 Developing Professional Java Applets
20/548
CONTENTS
one. Rather than one large project, each chapteras a smaller project. The focus is on moredvanced uses of images and threads, but there ilso a discussion of HotJava and its content-
andling features. The goal of Part V is to furtherefine the knowledge you have gained in the firstour parts of the book. By the time the book ends,ou should feel that you have a solidnderstanding of everything needed to build high
uality, professional Java applets.houghts Before Starting
There are a variety of Web sites cropping up thatelp you with various aspects of Java. The main
aunching pad for Java ishttp://www.javasoft.com/, which is where yo
an download the latest Java release and all kindsof first-rate documentation. The newsgroupcomp.lang.javahas excellent discussions of all
spects of Java programming, from novice to
dvanced. A couple of other Web sites, such ashttp://www.digitalfocus.com/and
http://www.gamelan.com/, offer good starting
places for exploring Java in cyberspace.
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (20 of 21) [7/31/02 10:12:33 AM]
http://www.javasoft.com/http://www.digitalfocus.com/http://www.gamelan.com/http://www.gamelan.com/http://www.digitalfocus.com/http://www.javasoft.com/ -
8/22/2019 Developing Professional Java Applets
21/548
CONTENTS
Finally, it should be pointed out that the JDK 1.0 iot without bugs. An unfortunate side-effect of th
s that some features that work on one platformmight not work on another. If you are having
solated, inexplicable problems running any of thepplets in this book, consider downloading the
atest version of the JDK for your platform.
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/index.html (21 of 21) [7/31/02 10:12:33 AM]
-
8/22/2019 Developing Professional Java Applets
22/548
Chapter 1 -- The Java Development Environment
Chapter 1
The Java Development Environment
CONTENTS
Tough Problems in Search of One Solution
Why Java Is a Comprehensive Solution
Why Object-Oriented Is Important
Java as an Object-Oriented Language
Java as a Portable Environment
Java as High Performance
Java in the World of Distributed Computing
Java as a Secure Environment
General Features of the Java Programming Language
Data Types
Literals
Variables
Comments
Operators
Keywords and Conditionals
Loops
Arrays
Applets and Standalone Applications
Creating an Applet
Creating a Standalone Application
Applets Versus Standalone Applications
Summary
va is a programming language that provides a foundation for developing Internet applications. Java
oes this through applets, which are programs executed as part of a Web page and displayed with a J
abled browser, such as HotJava or Netscape Navigator 2.0. However, Java's features need to be
nderstood in a context much broader than just running Internet applications. Java is a language desig
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (1 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
23/548
Chapter 1 -- The Java Development Environment
solve a variety of problems that have plagued the computing community for years; running well on
ternet is almost a by-product of solving these problems.
hat are these problems? And how does Java solve them? This chapter will attempt to answer those
uestions. Through the course of this chapter, you will be given the background needed for
nderstanding why Java, applets, and the Internet are such a natural match. This background will not
nly help you better understand the techniques used to program the Java applets developed throughou
is book, but the extra knowledge of the "big picture" may also help you come up with novel ways tply this new technology. Java and the Internet are very much like the old Western frontier-pathfind
ho break new ground may find the gold that lies underneath.
Tough Problems in Search of One Solution
key word often used when discussing the "information superhighway" is convergence. People talk
out the convergence of telecommunications and computing, television and computers, consumer
pliances and telecommunications, and so forth. Each of these converging factors comes from areaschnology that, until recently, have not had much in common. For example, the technology of fiber
ptics does not have much to do directly with the problems of computing. At the same time that these
sparatetechnologies have converged, there have also been pressures from withincomputing to brin
gether disciplines historically considered unrelated. This convergence within computing has been
ought about by various pressures that have arisen:
An overwhelming need to deal with the software crisis has developed. This term has been coi
to describe problems that have plagued the software community. Software development has b
marred by high cost, low quality, and ever-increasing demand; these problems have been bothcaused and exacerbated by increasing software complexity. Because of these trends, there is
tremendous interest in any technique that can increase the productivity of software developers
improve reliability, and make it easier to design software that tackles complex problems. Ove
last decade the technology that has been viewed as having the best chance of successfully dea
with these problems is object-oriented programming. Object-oriented features of abstraction,
encapsulation, and modularity are particularly well suited for making complex real-world
problems easier to model and, hence, design. A true object-oriented language's support for
inheritance and dynamic binding improves software reuse and also, as a consequence,
programmer productivity. The garbage collection facility in some object-oriented languagesimproves reliabilityby freeing the programmer from the intricate concerns of memory
management.
The predominance of a variety of operating systems and platforms has created a heavy deman
portablesoftware. Programs need to be written that will not only run on several different
platforms, but do so in a way that fits into the native "look and feel" of the environment.
Furthermore, portable software needs to have the high performancethat is typical of the softw
written for the target platform. Interest in soft-ware that is portable but slow is waning rapidly
The rapid growth of computer networks has been matched by a corresponding rise of interest
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (2 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
24/548
Chapter 1 -- The Java Development Environment
distributed computing. This discipline is concerned with the problems of software distributed
across multiple computers. Distributed computing issues include interprocess communication
concurrent processing, data sharing and replication, and security. Although the Internet is the
well-known distributed environment, it is in just the early stages of using the full potential of
distributed computing. Until recently, for example, there has been no solution to the problem
dynamically downloading an application both efficiently and securely.Efficiencyis important
since you want to download only the code you need when you need it; you don't want to wait
thirty minutes to download a 3MB application. Even more important, you need to be concernewith the securityof the code. You won't run applications from the Internet if it means giving t
green light to hackers around the world to attack your hard disk. You also do not want a poorl
written Internet application to crash your system-the software has to be reliable.
ach of these problems has been seriously addressed from many fronts, but no approach has
multaneously addressed all these problems. For example, there might be a programming language t
ood for rapid development but isn't portable, or a development environment might be portable, but
uld not work in a distributed environment without opening you up to serious breaches of security. A
ngle solution to all these problems has been lackinguntil Java!
Why Java Is a Comprehensive Solution
he designers of Java created a programming environment to attack each and every one of these
oblems. As a comprehensive solution to these pressing issues, Java needs to be understood as not ju
ogramming language, but as a general-purpose environment. Its unique combination of a programm
nguage, compiler, and runtime environment provides a general architecture well suited for addressi
any of the concerns that have been plaguing the computing community for years. This general
velopment environment is often referred to with the solitary termJava.
part, Java's evolution into a comprehensive solution stems from its twisted history of being a langu
r general consumer electronics to being one for PDAs and set-top boxes for interactive television.
eatures common to each of these potential platforms include severe memory constraints and the nee
pport multiple operating systems. These problems forced the language to address the problems of
stributed computing, efficiency, security, portability, and reliability. For Java to be a successful
nguage, furthermore, it would also have to address the problems associated with the software crisis
ould need to be object-oriented.
eing object-oriented carried another bonus for Java. The object-oriented message-passing model of
voking class methods makes it a natural for network-based application development. Consequently
ing object-oriented is one of the cornerstones of Java, so it's a good place to begin a tour of its gene
chitectural features.
Why Object-Oriented Is Important
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (3 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
25/548
Chapter 1 -- The Java Development Environment
hy is it important for Java to be an object-oriented language? As stated before, modern programmi
nguages need to address the problems of the software crisis. Perhaps the most serious difficulty a
ftware engineer encounters is the inherent complexity involved in modeling a real-world problem.
hrough the past decades of computing, analysis techniques have come in and out of fashion that aim
ake modeling the world a more comprehensible and stable practice. When you were taking your fir
asses in programming, you might have seen flowcharts used as a modeling tool. The Structured
nalysis school of thought uses data flow diagrams to model the world. These approaches have some
ntributions to make, but they have one serious problem: they are heavily oriented toward theoceduralside of the activities being modeled. The problem with a procedural approach is that it do
ot translate well to software that is compact, easy to maintain, and reusable. In its worst
mplementations, a system based on the procedural model has a different function for every different
procedure that could occur. You have probably seen such systems-they are so incomprehensible an
rd to follow that the only goal of the poor soul who has to maintain the system is to "just make it
ork."
bject-oriented analysis, design, and programming is a radical departure from the procedural model.
cus is not on the procedures of the modeled world, but on the objectsappearing in it. Objects are atural thing to model because that's what the world is made of. Planes, dogs, and computers are all
bjects. Even abstract concepts, such as a priority queue, can be thought of as an object. What all obj
ve in common is that they have stateand behavior. For example, the state of a plane can be partiall
dicated by its speed and location, but its behavior might be represented by its ability to change altit
nother feature of objects is that they are self-contained; in other words, they are modular. When
odeling a car engine, for example, you can focus on the characteristics of each object in the engine
pposed to the flow of gas and energy through it. The object model breaks the engine down into a ser
components that can be described on their own terms, as opposed to what they are in a complex glew of things. Instead of writing a single huge procedure describing what's going on in the car, you
cus on how each of the individual elements behaves.
nally, objects have the quality of being hierarchical. A large complex object, a house, for example,
nsists of other objects, such as its physical structure, the electrical system, the plumbing, and so for
hese are in turn made up of yet other objects, such as a chimney, the light switches, and a sink. The
n be broken down into yet smaller components such as wood, wires, and pipes. By modeling a syst
sed on hierarchy, you can use the model of smaller, more easily understood objects, such as a wire
nstruct more complex objects, such as a light switch. Since the switch is now seen as an object thatnsists of yet simpler objects, its complexity is easier to understand and manage.
object-oriented systems, objects communicate through a message-passingmechanism. When an ob
ceives a message, it may change its state and behavior as part of the response. For example, sendin
essage of "play" to a CD player object might result in the CD playing a music track. This message-
ssing aspect of objects translates very nicely into the needs of network programming, where
ansactions are carried out by the mechanism of messages. It is particularly well suited to distributed
stems because objects communicate by a standard message-passing mechanism, in which the actua
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (4 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
26/548
Chapter 1 -- The Java Development Environment
cation of the objects becomes less important. If your object needs to talk to an object, it isn't
rticularly important if it is on your computer or a remote host. All that really counts is that the obje
ts your message.
ava as an Object-Oriented Language
va is unusual for an object-oriented programming language in that it is "objects all the way down."
nlike C++, which is a confusing combination of objects and functions, everything in Java is an obje
rings are objects, numbers are objects, threads are objects, even applets are objects. Because of this
va has all the helpful features of object-oriented systems just described. Its core constructs of classe
bjects, methods, and instance variables are, by their very nature, managed in a modular fashion. Jav
pport for inheritance allows you to build new classes from other classes. Each class you construct
comes a tool that can be used to create yet more complex classes.
va's particular object-oriented implementation allows it to have yet even more desirable features th
ose already discussed. It has a runtime garbage collectorthat removes objects from memory that yo
o longer need. No longer will your program run out of memory because you forgot to explicitly dele
object. The garbage collector, which your program doesn't even have to be aware of, does this for
urthermore, Java's total orientation toward objects removes another construct that has been a blight
ogrammers-the pointer. Java hides almost all aspects of memory management from the programme
C++ programmers who have had to deal with complex bugs caused by the misuse of pointers or ba
ointer arithmetic will no longer have to deal with this entire class of problems. In Java, you will nev
al with pointers, only objects. Because of this combination of garbage collection and removal of th
ointer construct, Java has generally taken the problem of memory management away from you.
onsequently, programs written in Java are more reliable.
va's unique object-oriented implementation gives it another set of desirable characteristics-simplici
dfamiliarity. In many ways, its syntax is similar to C and C++, thus making it familiar. On the oth
nd, it strips out all the programming constructs of this language that are historical artifacts contribu
tle to writing object-oriented programs. For example, the structure construct is removed because
erything in Java is an object. Unions are removed because they make you think too much about ho
emory is laid out, a low-level memory consideration that Java's garbage collection and removal of
ointers tries to abolish. Other procedural features of C and C++ that are removed include functions,
hich are replaced by class methods; preprocessor constructs, such as typedefand ifdef; the ha
otostatement; and, of course, pointers. Java also replaces the complex and troublesome multiple
heritance of C++ by a simpler combination of single inheritance and interfaces. With all these featu
mind, Java becomes a simpler and easier language to use.
va has all the object-oriented features discussed in the previous section. It uses message passing to
bjects communicate, and it supports dynamic binding, allowing a message to be sent to an object ev
ough its specific type may not be known until runtime. Abstract classes and interfaces enable you t
ecify a design without having to worry about a specific implementation. With Java's access control
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (5 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
27/548
Chapter 1 -- The Java Development Environment
nstructs, you can define different levels of access to your class's methods and variables that are
ailable to external classes.
ava as a Portable Environment
ortabilityis critical to success in the emerging world of networked applications and commerce. On
ternet, you cannot make assumptions about what kind of platform your applet will run on. Not only
ou have to write software that will run on the client's underlying architecture-such as 80x86, Powerp
68000 series-but you must also ensure it will have the correct look and feel of the native interface.
ake things even tougher, this software needs to be fast and compact.
va takes a multipronged approach to this challenge. At the heart of this approach is the fact that the
va compiler generates bytecodesthat are interpretedat runtime. The fact that bytecodes are generat
important because it avoids the problem of basing the binary code on a basic set of primitive types
ch as integers and floating point-that would be tied to a specific platform. For example, even somet
simple as an integer data type is implemented in a different manner on different platforms (16-bit
me, 32-bit on others). Java defines its own set of primitive data types and reconstructs large 16-bit
2-bit values at runtime by composing them out of individual bytecodes. Java consistently uses the b
dian format to do this, thus avoiding another portability conflict about how platforms store primitiv
ta types. You can also quickly and efficiently convert the bytecodes at runtime to the underlying na
rmats if necessary. In short, Java's underlying encoding scheme is architecture-neutral.
he bytecode-based system is important to writing a portable interpreter. The bytecodes generated by
mpiler are based on the specification of aJava Virtual Machine,which, as its name suggests, is no
ecific hardware platform but a machine implemented in software. The virtual machine is very simi
a real CPU with its own instruction set, storage formats, and registers. Since it is written in softwa
owever, it is portable. All that's needed to take Java code compiled on one platform and run it on
other is to provide a Java interpreter and runtime environment. The runtime system is written in an
sily portable fashion. Once you have this system, everything becomes easy. You don't even have to
ort the Java compiler-it is written in Java!
nother advantage of the Java interpreter is that it improves software development by eliminating the
nk phase of the development process. You can go straight from compiling your code to executing it
nking actually occurs at runtime through mechanisms discussed in the section "Java as a Secure
nvironment."
couple of higher-level features also improve Java's portability. The Abstract Window Toolkit (or
WT) is constructed to be a visual interface that is portable across platforms. This way your applets
ok good regardless of the underlying interface. They will have the proper "look and feel" on Micro
indows, the Macintosh, or X-Windows. Although not a portability issue in the strict sense, Java sto
aracters by using the 16-bit Unicode format as opposed to the 8-bit ASCII standard. Unicode is use
ou need to support international character sets. Since the Internet is an international network, this
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (6 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
28/548
Chapter 1 -- The Java Development Environment
nsideration is important.
ava as High Performance
ne of the reasons why Java's portable solution is such a coup is that interpreted platforms have
nerally been very slow. Often their performance is so poor that systems based on these interpreters
ve been unusable. Java's bytecode system, however, provides a "lean and mean" interpreted solutio
n't based on multimegabyte executable "image" files. Rather, the runtime system works with small
nary class filescompiled to Java virtual machine code. These files typically have a size of only a fe
lobytes.
owever, Java offers more than just the byte-code system to get high performance. Since the byte-co
stem is at a low level, it can be easily converted at runtime to the native platform. Just-in-time Java
mpilers will be out in the near future to allow this. Another performance enhancement is a by-prod
another Java feature. When a class is brought into memory at runtime, it runs through a verificatio
ocess as part of the Java security mechanism (discussed in the section "Java as a Secure Environme
his process not only guarantees that the code you are loading is secure, but the end result is code tha
quires less runtime checks. These checks, which otherwise would hurt performance, now don't need
executed. For example, the runtime system does not have to check for stack overflows on verified
de.
ne of the key features that Java offers to improve performance is multithreading.Most interactive
plications are characterized by large periods of time during which the user pauses between actions
cide what to do next. In traditional single-threaded environments, the application may sit idle durin
ch periods. In multithreaded environments, however, the application can perform other tasks during
ese types of delays or at any other time. This is critical for network applications, which can take lon
riods of time to load files. Wouldn't it be more efficient if you could read the current page of text w
e next page is being downloaded? Multithreading also greatly improves the usability of multimedia
plications. For example, you need to be able to interact with your system while a sound or a movie
aying. Multithreading is useful for even more down-to-earth things, such as running a background
read that spell checks your document as you are typing in words.
ou can use Java's easy-to-use multithreading environment to perform all kinds of optimizations to y
ogram. In fact, the designers of Java have taken great pains to make sure it's easy to write
ultithreaded programs. Historically, writing multithreaded applications has been quite difficult-a ke
ason they have appeared infrequently. Furthermore, Java uses threads to improve its own performa
he garbage collector that takes care of your memory management concerns runs in the background
w-priority thread. So even when your program is doing nothing, the garbage collector could be bus
ptimizing memory!
here are some other interesting things Java does to guarantee good performance. As stated earlier, J
"objects all the way down." In some object-oriented systems, primitives such as integers and floati
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (7 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
29/548
Chapter 1 -- The Java Development Environment
oint numbers are implemented only as objects. So to perform an operation such as adding two numb
ou actually have to call an object method. If you are doing some serious number crunching, this wil
solutely kill your performance. Java has an intermediate solution to resolve the dilemma between
ving good performance and being a pure object-oriented system. It implements "type wrappers" to
imitives, such as numbers, and make them appear as objects. This way, methods-such as converting
umbers to strings-can be performed by using the object-oriented method style. However, if you need
ork with raw data types, you can use the primitive formats to produce such things as CPU-intensive
mages like fractals. Java can even be used to create the computation-hungry Mandelbrot set. It's rathmarkable that Java can do this; if you don't believe it can, then see Chapter 14, "Advanced Image
ocessing."
you really need that final push to your performance, Java can link to executable code written in a lo
vel native language such as C. Java code that does this is said to use native methods. This technique
so be used to implement platform-specific features. However, using native methods is not without i
awbacks; it will probably compromise the portability of your code. Fortunately, Java performance
nerally good enough that you don't need to bring in native methods very often.
nally, it is important to remember that the Java community is constantly working on techniques to
mprove performance but not compromise all the other features of Java, such as portability. The just-
me compilers that will be out later this year are among the most impressive of such optimizations.
ava in the World of Distributed Computing
uch of what has been discussed so far makes Java well suited for network computing. In particular
ghtweight nature of the binary class files makes it possible to download Java code without seriousrformance hits. Multithreading is also critical for latency-laden network operations; your applet can
ownload code and resources in the background while the end user is deciding the next action to take
ortability frees you from knowing how your applet will run and what it will look like on your poten
ient's unknown platform.
nother feature of Java that makes it excellent for distributed computing is that it's dynamic. Since th
no linking phase after compilation, the resolution of references is put off until runtime. Java also d
ot calculate the layout of objects in memory until they are used at runtime. Consequently, if you add
w method to one class, you don't have to recompile another class that uses the class but not the meC++, you are constantly having to recompile multiple classes because one is "dependent" on the ot
is is known as the "fragile superclass problem." In its typical efficient manner, Java solves the
perclass problem while taking care of other issues. Since the Java dynamic system removes difficu
used by unnecessary dependencies, it's easy to download a special subclass to handle a specific
uation without worrying about "linking" problems.
he Java development package also gives you a variety of good communication constructs. The mes
ssing mechanism of its objects can be used to let two different applets communicate; this is known
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (8 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
30/548
Chapter 1 -- The Java Development Environment
nter-applet communication." Sockets, pipes, and thread synchronization constructs also provide oth
sy-to-use communication mechanisms. In short, Java provides all the basics for creating distributed
stems.
ava as a Secure Environment
lthough distributed systems are extremely powerful, they open the door to a range of security probl
hich are particularly serious on a vast open network like the Internet. For normal data transmission,
ve to be concerned with someone eavesdropping on your information as it passes through the netw
you have a server on the Internet, you have to worry about someone breaking in and wreaking havo
n your internal network. And if you're downloading applications from the net, you have to worry ab
causing damage to your host system.
he kind of damage a poorly written application could inflict on your host spans a range of extremes
ne hand, a poorly written application can misuse the resources of your system, taking resources you
ight need elsewhere. For example, a C program that mismanages memory can simply take memory
other one of your applications needs. If the program is really bad, it can cause your system to lock
ortunately, it's usually easy to recover from such problems. However, the other end of the extreme i
uite so innocent. A malicious program can attack some of the most critical resources of your compu
ch as your hard disk, causing damage less easily fixed. If the program is a virus, it can be even mor
rnicious. It can lie in wait for weeks or even months, then one day pounce on your computer and
nnecting network, causing hours or even days of lost work time. If this attack came from an applic
at you ran from the World Wide Web, you would probably be reluctant to use the Web again.
onsequently, bad Web programs not only threaten your system, but the viability of the Web as a wh
he designers of Java know just how important security is. For this reason, they built a multi-layered
curity system whose presence is felt throughout Java. This security model consists of four main lay
The languageitself is designed to be safe. A strict compilerprevents generating bytecodes th
don't completely follow extensive safety rules.
A runtime bytecode verifierthat inspects class bytecodes as they are loaded into the system.
Since code loaded at runtime has already passed through the compilation stage, Java cannot kn
that it hasn't been produced by a malicious or weak compiler that does not follow all the
language's safety rules.
Once code has been verified, it needs to be loaded into a runtime namespace. This is performe
a module called the ClassLoader, represented by a like-named class. Java has a different
namespace depending on whether the loaded class came from a local file system or across a
network. These separate namespaces prevent a class from passing itself off as a new low-leve
class. Therefore, it can't do such things as replacing the existing Security Manager (discussed
briefly in the next bulleted item).
The final layer performs checks on the code as it's being executed. This layer makes sure the c
does not violate any security restrictions defined for the current environment; it's generally
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (9 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
31/548
Chapter 1 -- The Java Development Environment
represented by a module called the Security Manager, which corresponds to a Java class of a
similar name. An applet that can delete a file on your computer is an example of something th
falls under the auspices of the Security Manager. The workings of Security Managers can vary
different environments. Extremely conservative Java-enabled browsers, such as Netscape
Navigator, actually prevent applets from reading or writing to your local file system altogethe
The HotJava browser, on the other hand, can be configured to authorize file operations more
flexibly.
gure 1.1 gives an overview of the lifetime of Java code as it travels through the layers of security.
hose modules related to security are set off in boldface.
nce security is such a critical part of Java, it is worth taking a moment to look at it in greater detail.
oing so, you will get some greater insight into the inner workings of Java.
gure 1.1 : The Java life-cycle in relationship to its security layers.
rst Security Layer: The Language and Compiler
ou have already seen a couple of reasons why Java is a secure language. A key ingredient here is
moving pointers from Java. Without pointers, a bad or malicious program cannot invade the memo
ace of other applications. This removes a major source of attack for viruses. For example, a threate
ogram cannot use Java as a launching pad to directly attack your operating system kernel. Furtherm
e absence of pointers makes the Java applet itself more secure and reliable. An applet won't crash
cause of a "dangling pointer," as is often the case in C and C++.
nother security feature of the language is its class access mechanism. Classes can control the kinds
cess other classes have to their methods and variables. There are four access modifiers, ranging fro
ublic, which indicates availability to all classes, to private, which makes a method or variable
cessible only from within the class where it's defined. These modifiers can make your class more
cure by denying other classes access to critical behavior. For example, if you have a class that man
itical data in a private method, another class cannot invoke that method to change the data. Access
odifiers will be discussed in more detail in the next section.
he compiler uses very strict checking to ensure adherence to these and other Java language construcva is a strongly typed language, so runtime bugs aren't introduced because of freely casting one typ
bject to another. A language like C is notorious for its loose casting mechanism. A pointer to a struc
n be fairly easily cast into a long integer, and vice versa. When such casting is done incorrectly,
rnicious and difficult-to-find bugs can be introduced, but this kind of casting is eliminated in Java.
sts must be explicit, and those that don't follow the semantics of the language are disallowed. Beca
e compiler is so strict, many errors that would otherwise appear at runtime are caught at compilatio
nce runtime bugs are potentially dangerous and can be time-consuming and difficult to track down
ood to catch as many mistakes as possible during compilation. Java's strict compiler is one reason th
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (10 of 26) [7/31/02 10:12:59 AM]
http://e%7C/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/f1-1.gifhttp://e%7C/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/f1-1.gifhttp://e%7C/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/f1-1.gifhttp://e%7C/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/f1-1.gif -
8/22/2019 Developing Professional Java Applets
32/548
Chapter 1 -- The Java Development Environment
vironment is said to be robust.
econd Security Layer: The ByteCode Verifier
he bytecode verifier is the most critical line of defense in the Java security system. If a rogue class c
t through this layer, you could be in real trouble! However, this is unlikely. The verifier uses variou
chniques, including a theorem prover, to ensure that the bytecodes of the class being loaded do not
olate any of the structural constraints Java places on incoming code. The verifier is, therefore,ositioned to catch any potential malicious actions caused by bytecodes produced by a hostile compi
subject to post-compilation tampering.
erification goes through a couple of steps. The first step is to verify the format of the incoming file
ake sure it is indeed a Java class and has been properly constructed. The next step is much more
mplex. The verifier basically sets out to prove that the code has a variety of properties. If the bytec
ake it through this phase of the verifier, then you'll know the following things:
The code does not cause stack overflows or underflows.
The operand types of the bytecode opcodes are proper. For example, an opcode that works wi
integer operand cannot have an operand that is an object reference.
No illegal casting is attempted.
Object access rules are followed.
s a result of these properties being proved, the runtime system will know a couple of other importan
ings, the most important being no forged pointers in the code.
beneficial side effect of the verification process is that the interpreter is free from performing many
ese checks as the code is being executed. For example, it does not need to conduct expensive check
e if a stack overflow is about to occur. Because such checks are not necessary, the interpreter will r
uch faster.
nother security-related step occurs when the interpreter loads the verified bytecodes. When the
terpreter brings in a class, it defines the memory layoutof the class. Recall that this is a feature of J
ynamic linking used to solve the "fragile superclass" problem. Dynamic linking also has a security
vantage. In traditional languages, memory is laid out at compile time. A malicious programmer,
nowing the layout of memory in the executable code, could then tamper with the pointers to get aro
curity problems. Since Java performs memory layout at runtime, however, this potential security
ypass is thwarted.
hird Security Layer: The Class Loader
fter a class is verified, it's ready for runtime use. The Class Loader brings each class into a unique
amespacethat corresponds to its origin. The default namespace is for classes that come from the loc
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (11 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
33/548
Chapter 1 -- The Java Development Environment
e system. Such classes are called built-ins; they can never be replaced by a class that comes from a
ternal source because there is a separate namespace for each network source of classes. When a cla
ferenced, Java looks first for a built-in class. If it isn't found, then Java inspects the namespace of th
ferencing class. This approach prevents network classes from replacing a built-in, or a class from o
twork source overriding one from another source. The security implications of this approach are su
ut important. Java tries to implement as much as possible through Java classes; for example, the
ecurity Manager module is represented by a SecurityManager class, you get access to system resour
rough the System class, and, as will be seen shortly, class loader policies are implemented byassLoader classes. By preventing built-ins from being overridden, Java protects critical modules, s
the SecurityManager or System. It's easy to imagine what could happen if a network class was allo
replace the SecurityManager class.
ubclasses of the ClassLoader class are used to enforce namespace policies. The Class Loader system
n consist of multiple instances of ClassLoader subclasses. For example, one Class Loader can be u
r classes brought from inside a firewall, but another Class Loader class can be used for those broug
om the Internet. The local file system, by default, does not use a ClassLoader class. Instead, it searc
r classes in directories listed in the CLASSPATHenvironment variable; you can modify this path toclude the directories that have your classes. Keep in mind that there's a subtle difference between th
ass Loader mechanism, which applies to the entire Java runtime environment, and instances of the
assLoader class, which implement specific policies.
ourth Security Layer: The Security Manager
ven after a chunk of bytecode has gotten past the verifier and the class loader, it is still technically i
osition to cause some damage. Suppose that a class downloaded from the Internet has some code to
lete files from your hard disk. This can be done legitimately by calling the delete()method of tle class and so will pass the verifier and class loader. Fortunately, the final security layer, represent
y the SecurityManager class (also known as the Security Manager), will prevent this from occurring
he Security Manager is responsible for enforcing a set of policies for protecting the runtime
vironment from unauthorized transactions. Whenever a potentially "dangerous" action is about to
ppen, the Security Manager is asked for authorization to perform the action. Based on how the
anager is implemented, the action may be denied or granted.
ifferent browsers and applet viewers can use the Security Manager in an appropriate way. Once
stalled into the runtime system, the Security Manager cannot be replaced. These browsers may granvels of authorization for different actions. For example, the Netscape Navigator has a very conserv
ecurity Manager. The most dangerous class of actions, those of reading and writing from the hard d
e prohibited altogether. On the other hand, the HotJava browser has a more flexible configuration.
n be set up to grant full disk access from applets loaded locally, some access to applets loaded from
ithin the firewall, and no access for those brought in over the Internet.
wide variety of actions are subject to authorization by the Security Manager. When a class is asked
rform a potentially dangerous action, such as a file delete, it will ask the SecurityManager class for
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (12 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
34/548
Chapter 1 -- The Java Development Environment
thorization. If it isn't permitted, a security exception will occur. Besides all file-related activities, th
tions of the most importance to security are network accesses. Once more, restrictions are usually
sed on how the SecurityManager is set up, but there are a few generalities. An applet loaded over t
ternet can connect only to the host from which it originated; it will not be allowed to connect to
ywhere from inside the client's firewall, nor will it be permitted to use the client to act as a launchi
d into some other Internet site. An applet is also prevented from running as a network server (this h
me implications that are explored later). Restrictions enforced by the SecurityManager will be
scussed throughout the book as the appropriate topics dictate.
General Features of the Java ProgrammingLanguage
ou will now be guided through a very quick tour of the basics of the Java language. If you have
perience with C or C++, then much will be familiar-you might want to skip over parts of this sectio
ou don't know these languages, don't worry. The basic mechanics of the language are easy, and youe many examples throughout the book. Discussion of classes, methods, and objects will be postpon
ntil the next chapter.
ata Types
s stated earlier, everything in Java is an object. Thepartialexception to this is the primitive data ty
hese data types have a standard size across all platforms; this standardization is a key aspect of Java
ortability. Table 1.1 lists the primitive data types.
Table 1.1. Primitive Java data types.
Data Type Size
byte 8-bit
short 16-bit
int 32-bit
long 64-bit
float 32-bit floating point
double 64-bit floating point
char 16-bit Unicode
you are a C or C++ programmer, you might have noticed a couple of things. First of all, there is no
nsignedtype specifier. The chardata type has been replaced by the byteprimitive. The char
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (13 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
35/548
Chapter 1 -- The Java Development Environment
pe is now 16 bits, instead of the old 8 bits, because Java bases character data on the Unicode charac
t. Unicode is a standard that supports international characters, thus broadening the potential base in
hich your application can run. Although Unicode is a much broader standard than ASCII, you will
obably have many opportunities to program in the 8-bit standard. Some default class behavior and
calization methods will be available for doing this. This book will focus on ASCII output.
he only primitive data type not in Table 1.1 is boolean. A booleanvariable cannot be converte
number and has only two values: trueor false.
ou might have noticed that these primitive data types present apartialexception to Java's pure obje
iented nature. It is "partial" because Java has a suite of classes used to encapsulate these data types
bjects. These classes are called type wrappersand are discussed in Chapter 2, "Object-Oriented
evelopment in Java."
iterals
teralsare used to represent the primitive types. Integers are defined in a manner similar to C. They
literally set to a decimal value, such as 10. A hexadecimal value is indicated with a leading 0x; 15
presented by 0xF. Octal values (base 8) are prefaced by 0.
oating point numbers are represented by the standard decimal point notation, such as 3.1415. These
stored as a 32-bit floator a 64-bit double; the latter is the default. The notation style of 6.1D
1F can also be used to designate the number as a doubleor float, respectively.
haracters can be represented by a single character in quotes such as 'a'. Escape sequences are usepresent special characters and are preceded by a backslash (\). For example, tab is \t, newline is \
d so forth. See your Java references for a listing of all the escape characters.
he last literal is not based on a primitive data type. Strings are represented by zero or more characte
ouble quotes. An example is "This is a Java book!". The literal string can also use escape
aracters. For example, to add a new line to the previous example you would write: "This is a
ava book!\n".
ring literals are implemented as objects of the String class. Operations on strings do not occur onaracter arrays (as in C), but through class methods; these operations are discussed in more detail in
xt chapter.
ariables
va has three types of variables: instance, class, and local. The first two types are talked about in the
xt chapter in the context of the discussion on classes. Local variables can be declared inside metho
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (14 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
36/548
Chapter 1 -- The Java Development Environment
ocks.Blocksare statements appearing in braces { }. Any local variable declared inside a left brace
lid until the right brace, at which point the variable goes out of scope.
dividual variables are declared in the general format:
or example, to declare a doublecalled pi:
double pi;
ou can also asign a value to it:
double pi = 3.1415;
ariable names are prefaced by letters, an underscore, or a dollar sign. They can use most characterscluding numbers. However some symbols, such as those used in operators, should not be used. For
ample, you should not call a variable pi+3.
omments
va has three comment styles. Two are similar to those used in C and C++. A double slash (//) mea
at everything to the end of the line should be ignored:
// Ignore this
verything between the characters /*and */is also ignored. This can be spread over several lines. I
rst part of the comment starts with /**, then a special documenting feature is indicated. How this
orks is discussed in Chapter 14.
perators
able 1.2 lists a quick summary of operators in Java, which are fairly simple to use. The following coclares two integers, assigns values to them, and adds them to a third variable:
int x,y;
x = 3;
y = 4;
int z = x + y;
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (15 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
37/548
Chapter 1 -- The Java Development Environment
he final value is 7.
he following code applies the bitwise ANDoperator to the end of the previous example to get the va
int q = z & 4;
ou'll see examples of other categories of operators in the upcoming sections.
Table 1.2. Classification of operators.
Classification Operators
Arithmetic + - * / %
Relational Operators < > >= >>> ~ &= |= =Assignments = += -= /= %=
Bitwise Assignments &= |= = >>>= =
Ternary Operator (if...elseshorthand) ?:
Increment ++
Decrement --
xpressions that have multiple operators are resolved according to where they are in a hierarchy ofecedences, shown in Table 1.3. Operators higher up in the precedence table are evaluated first. If
ultiple operators on the same line have the same precedence, then they are resolved by left-right ord
you are confused or cannot remember precedence, then a nice rule is "When in doubt, use
rentheses."
Table 1.3. Operator precedence.
. [] ()
++ - ! ~
* / %
+ -
> >>>
< > =
== !=
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (16 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
38/548
Chapter 1 -- The Java Development Environment
&
^
|
&&
||
?:= and other assignments
Bitwise Assignments
eywords and Conditionals
able 1.4 lists Java keywords; they are reserved for Java statements, so you can't use them for things
riable names. They are identifiers for such things as data types, conditionals, control flow construc
ass definitions, and object implementations. Most of these keywords will be described in this and thxt chapter. Those that are reserved but currently not implemented are italicized.
Table 1.4. Java keywords.
Abstract boolean
break byte
byvalue case
catch char
class const
continue default
do double
else extends
false final
finally floatfor goto
if implements
import instanceof
int interface
long native
new null
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (17 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
39/548
Chapter 1 -- The Java Development Environment
package private
protected public
return short
static super
switch synchronized
this threadsafe
throw transient
true try
void while
n if...elseconditional is used to execute code based on whether a booleantest is true. Sin
atements can follow, or multiple statements can be declared in braces:
if (test == true)
// ... A single statement to execute if test if true
else {
// ... multiple statements to execute if test if false
}
he test must return a booleanvalue. This means an expression such as
if (1)
not valid because it returns a numeric, but not a boolean. It's acceptable to nest if...else
atements or call them in a nested series, such asif...else...if...else...if...else.
he latter can also be simulated with the switchconditional. Not being restricted to just boolean
mparisons, the switchconditional uses a comparison with a general primitive to conduct its test.
llowing code uses an integer to perform its test:
switch ( Count ) { case 1:
// ... test 1
break;
case 4: {
// ... do some operation...
return 0;
}
case 24: break;
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (18 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
40/548
Chapter 1 -- The Java Development Environment
default:
return -1;
}
he casestatements can appear in braces.
oops
va has three looping operations. The forconstruct loop is structured as follows:
for (init; test; post-test)
he first part of the expression is any initialization at the start of the loop. The test is a simple or com
pression. The last part is an expression such as an increment or decrement of a variable. The forl
followed by a single statement or a block of code. For example,
for (k = 0; k < 10; ++k) {
// ... do something
}
ops ten times.
whileloop is just the test portion of the forloop:
while (test)
he do...whileconstruct performs the test and the end of the loop:
do {
// ... do something
} while (test);
he breakconstruct is used to exit from a loop, and the continuestatement skips to the next iter
the loop. Labeled loops can also be used to control where to go in complex loops. If a label follow
reakstatement, then the code breaks out of the nearest loop that has the matching label. The follow
ample effectively quits both loops when the variable jis greater than 100:
int i,j;
quit: for (i = j = 0; i < 100; ++i) {
for (int k = 0; k < 10; ++k) {
// ... Do something
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (19 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
41/548
Chapter 1 -- The Java Development Environment
if (j > 100)
break quit;
}
}
the breakstatement in this example was replaced by the following,
if (j > 100) continue quit;
en the code would jump to the next iteration of the outer forloop.
rrays
rrays are first-class objects in Java; they are not just a pointer to memory as in C. Consequently, Jav
rays are a lot safer. You cannot indiscriminately assign an element to just any index in an array. Javakes sure the index is valid-this prevents the difficult-to-track memory access violations that occur
sily in C. If you try to access a bad array index in Java, an exception will be thrown and no action w
taken.
ecause Java arrays are objects, their semantics are a little different from their counterparts in C or C
he thing that confuses most new Java programmers is how to allocate a new array. First, you cannot
clare an array with a prefixed size; it must be declared as an uninitialized variable:
int numbers[]; // For integer arraysString myStrings[]; // For arrays of String objects
nother way to declare array variables is to put the braces after the type. Some programmers conside
is method more readable.
String[] myStrings;
s you might have noticed from these examples, arrays can be used for both primitive data types and
asses.
he next step is to create the array by using the newoperator to construct an object instance; this wil
scussed in more detail in the next chapter.
int numbers[] = new int[5]; // For integer arrays of length
5
String myStrings[] = new String[20]; // For arrays of
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (20 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
42/548
Chapter 1 -- The Java Development Environment
length 20 of String objects
hese examples create an integerarray of 5 elements and a String array of 20 elements. However
rays still don't actually contain anything. Each slot is initialized to a default value. Integers are all s
and String elements are all set to null(indicating no object).
s easy to add elements to the array after it's created, much as you do in C++. It is a zero-based syste
ith integer indexes. Therefore, to assign the first element you would call the following:
myStrings[0] = "My First String"
numbers[0] = 10;
you try to make an invalid assignment to an invalid index, an ArrayIndexOutOfBoundsException w
thrown:
numbers[10] = 10;
hapter 2covers how exceptions are handled; for now, you just need to know that such exceptions o
runtime. The preceding error will not be caught by the compiler.
publicinstance variable called lengthis used to get the size of an array:
int q = numbers.length; // This is 5
rray sizes are final; any attempts to change the length variable will lead to problems.
va doesn't support multidimensional arrays. However, they can be effectively simulated by using ar
arrays, which can be initialized in several different ways. The simplest way is to define the array w
eset sizes:
int k[][] = new int[5][4];
k[1][3] = 999; // Assign a value to it
his example creates a 5 4 array of arrays assigned to the variable k. The second line shows that
signing an element to the array is straightforward, much like C or C++.
nother way to create a multidimensional array is to declare and then later assign its sizes:
int z[][];
int outerSize = 5;
int innerSize = 4;
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (21 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
43/548
Chapter 1 -- The Java Development Environment
z = new int[outerSize][innerSize];
ot all the dimensions need to be known at the time of allocation-only one dimension is required:
int j[][] = new int[5][];
j[0] = new int[4];
j[1] = new int[4];
this example, the outer array is set to size 5, then two of its elements are set to arrays of size 4. It is
teresting to note that the statement
j.length
ill return size 5, but
j[0].length
ill return size 4.
Applets and Standalone Applications
va can work with two kinds of applications:Applets, as stated at the beginning of this chapter, are
ograms executed as part of a Web page and displayed with a Java-enabled browser; standalone
pplications, on the other hand, are general-purpose Java applications that don't need a browser to rulthough applets and standalone applications are compiled in a similar fashion, they are created
fferently.
reating an Applet
sting 1.1 shows the code of a minimum applet, which is stored in a file called FirstApplet.java on t
ook's CD-ROM. It is compiled with the following command line call to the Java compiler:
javac FirstApplet.java
he output from the compiler consists of Java bytecodes in a file called FirstApplet.class. This class
ready to be directly run from the interpreter-no further steps are necessary.
he code consists of one class called FirstApplet, a subclass of the Applet class. The Applet class is u
tie the applet into the browser environment; it will be described in more detail in Chapter 6, "Build
Catalog Applet."
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (22 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
44/548
Chapter 1 -- The Java Development Environment
Listing 1.1. An applet that compiles but does nothing.
import java.applet.Applet;
public class FirstApplet extends Applet {
}
o run the applet in the browser, you need to create an HTML file. Listing 1.2 shows the HTML text
eded to run the applet. Note the second line of the listing: The tag is a special HTML
tension used to launch Java applets; notice especially the CODEattribute. The value assigned to it
dicates the class that will be run. In this case, it is the FirstApplet class that was just compiled. The
WIDTH> and tags are used to specify the bounding area of the applet, so you can cont
hat the applet looks like on your Web page. How Applet tags are used in HTML files is discussed iore detail later in Chapter 6.
Listing 1.2. The HTML text to run the applet.
First Applet
he program called appletviewer is used to run a Java applet from outside a browser. It's limited in
pability-it lacks all the features that a browser has-but it's good for rapid development. You can lau
applet from appletviewer by passing it the name of the HTML file that starts the applet on the
mmand line:
appletviewer FirstApplet.html
Note
le:///E|/copy1/prashant/books/Books/Docs/Developing%20Professional%20Java%20Applets/ch1.htm (23 of 26) [7/31/02 10:12:59 AM]
-
8/22/2019 Developing Professional Java Applets
45/548
Chapter 1 -- The Java Development Environment
Most of the projects and examples in the book can be run by loading
the HTML in the example directory of the CD-ROM into the
appletviewer program or a browser such as Netscape. When there
are additional steps required, such as in the Part IV server programs,
you should look at the README file in the working directory of the
CD-ROM.
reating a Standalone Application
sting 1.3 shows the code of a simple standalone application, which is stored in a file called
andalone.java on this book's CD-ROM. Like the preceding sample applet, and class files in general
mpiled with the program javac.
he code in a standalone application differs from an applet's code in two ways: first, standalone
plications do not need an instance of the Applet class; second,they are started by a call to the mainethod, as in C programs. The main()method is the first routine executed in the program, which y
art by invoking the Java interpreter:
java Standalone
he .class extension should not be specified as part of the main parameter. Additional parameters can
ecified after this; they are passed to the main()method as an array of String objects, as the exam
ows.
he example just prints text to the standard output console by using a call to the println()metho
e System class: System.out.println. You will