0% found this document useful (0 votes)
7K views1,491 pages

Java Bible

Java Bible:Table of Contents Introducing java a Mouthful of java. Object-oriented programming and terminology. Applet design basics.
Copyright
© Attribution Non-Commercial (BY-NC)
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)
7K views1,491 pages

Java Bible

Java Bible:Table of Contents Introducing java a Mouthful of java. Object-oriented programming and terminology. Applet design basics.
Copyright
© Attribution Non-Commercial (BY-NC)
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/ 1491

Java Bible:Table of Contents

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Preface
Acknowledgments

PART 1—Introducing Java


CHAPTER 1—An Overview of Java
Java Environment
Java language
Java runtime environment
Java tools
Java applets
Java applications
Java handlers
Java Virtual Machine (the JVM)
Understanding Java
A Mouthful of Java
Simple
Object-oriented
Distributed
Interpreted
Robust
Secure
Architecture-neutral
Portable
High-performance
Multithreaded
Dynamic
Java in a Nutshell
Java Versus C/C++
Data types
Classes and methods
Operators
Command-line arguments
Strings

file:///F|/books/java%20books/Java%20Bible/ewtoc.html (1 of 16)6/26/2005 7:54:31 PM


Java Bible:Table of Contents

Comments
Odds ‘n’ ends
Summary
CHAPTER 2—Object-Oriented Programming and Terminology
So What Shall We Look at in This Chapter?
Object-Oriented Terminology
Abstraction
Combining state and behavior
Variables and methods
Encapsulation (information hiding)
Interfaces
Messages: Objects communicating with objects
Modularity
Classification
Inheritance
Object-Oriented Analysis and Object-Oriented Design
Notation method
Summary
CHAPTER 3—Applet Design Basics
Get Started by Walking Away from the Computer
Sketching a user interface
Giving the Webber Control
Mouse control
Keyboard control
Stop when stopped!
Flexibility through applet parameters
Bandwidth Considerations
Battling bandwidth bottlenecks
Images and colors
Webber System Considerations
Images and colors
Processing bottlenecks
Fonts
File Access and Network Connections
Testing locally, releasing globally
Other Considerations
A universal language
Layout managers

file:///F|/books/java%20books/Java%20Bible/ewtoc.html (2 of 16)6/26/2005 7:54:31 PM


Java Bible:Table of Contents

Inter-applet communications
Dual-purpose programs
Managing Source Code
Only one class to a source file
Document, document, document
Variable names
Altering variables
Avoiding native code
Peeking under the covers
Packages
Summary
CHAPTER 4—Installing and Configuring the Java BDevelopment Kit
Getting the JDK
Expanding the JDK Archive
Setting Up Your Java Environment
Solaris
Windows 95
Windows NT
Testing the JDK Installation
Using Java Tools
Compiling
Executing applications with the interpreter
Eecuting applets with the Applet Viewer
Summary

PART II—Getting Up to Speed


CHAPTER 5—Getting Started: HelloWorld Application and HelloWorld
Applet
Application Versus Applet
HelloWorld Application
Application directory structure
Entering and saving the source
Class declaration
Method declaration
Access modifiers
Compiling the source code
Executing the application
HelloWorld Applet

file:///F|/books/java%20books/Java%20Bible/ewtoc.html (3 of 16)6/26/2005 7:54:31 PM


Java Bible:Table of Contents

Applet directory structure


Entering and saving the source
Compiling
Executing the applet
Creating an HTML file
WIDTH and HEIGHT
HTML case sensitivity
Executing the applet
Living on the Web
Onward and upward
Summary
CHAPTER 6—Extending, Enhancing, Debugging, and Uploading
To Enhance or Extend?
Extending the HelloWorldApplet class
Stepping Through the Code
Importing classes
Documentation comments
Class declaration
Variables
Methods
Creating the HTML file
Botching the Code
Be warned
Stages in debugging your code
Debugging Tips and Warnings
Disable sound and graphics
Quit programs you don’t need
Don’t try to copy/paste in the DOS box
Clear breakpoints and resume program
Making Applets Live on the Web
Web server directory layout
Uploading the files
Testing the applet
Getting complex and flexible
Odds ‘n’ Ends
this and super
Fundamental applet methods
CHAPTER 7—Command-Line Arguments and Applet Tag Attributes

file:///F|/books/java%20books/Java%20Bible/ewtoc.html (4 of 16)6/26/2005 7:54:31 PM


Java Bible:Table of Contents

Need for Flexibility


Java Command-Line Arguments
Supporting command-line arguments
Java command-line arguments versus C/C++
Argument variable type
Argument variable contents
Java strings are first-class objects
Java strings behave predictably
Java Command-Line Argument Conventions
Word arguments
Arguments that require arguments
Flags
Other conventions
Using Command-Line Arguments in the HelloWorld Application
Enhancing the HelloWorld application
Executing with command-line arguments
Spaces and quotations
Parsing arguments
Applet Attributes
What are applet attributes?
Similarity to command-line arguments
Applet “parameter” attributes
Alternate applet context
Using Applet Attributes in MediaHelloWorld
URLs and exceptions
Understanding the code
Writing the HTML document
Applet usage guide
Summary
CHAPTER 8—Surfing the Web for Java Source Codey
Java Developer Resources
Code repositories
Support areas
Search Engines
Alta Vista
Do the Right Thing
Electronic mail and Web page footnotes
Applet-based credit

file:///F|/books/java%20books/Java%20Bible/ewtoc.html (5 of 16)6/26/2005 7:54:31 PM


Java Bible:Table of Contents

HTML comment tags


Give As Good As You Get
Summary

PART III—Programming Elements and Techniques


CHAPTER 9—Tokens, Types, and Values
Brass Tacks
Tokens
Keywords
Identifiers
Literals
Separators
Operators
Types and Values
Types
Values
Primitive types and values
Reference types and values
Standard default values
Summary
CHAPTER 10—Language Fundamentals
Variables
Declaring variables
Initializing and storing values in variables
Array initialization
Variable scope
Expressions
Operators
Operator precedence
Forcing order
Types of operators
Control-Flow Statements
if statements
switch statement
Loops
break and continue statements
Exceptions
Call stack

file:///F|/books/java%20books/Java%20Bible/ewtoc.html (6 of 16)6/26/2005 7:54:31 PM


Java Bible:Table of Contents

Throwing exceptions
Catching exceptions
try-catch clause
Catch or declare: It’s the law
Finally
Summary
CHAPTER 11—Classes, Interfaces, and Packages
Classes
Class Declaration
Modifiers
Superclass
Classes and interfaces
Class Body
Variables
Methods
Abstract classes and methods
Inner Classes
Nested top-level classes and interfaces
Member classes
Local classes
Anonymous classes
Interfaces
Packages
Using packages
Explicit class references in imported packages
Naming conflicts
Package levels
Creating packages
Unique names
JAR Files
Summary
CHAPTER 12—Strings and Arrays
Strings (Java.lang.String)
Java strings are first-class objects
String versus StringBuffer
Creating strings
Accessor methods
Type wrappers

file:///F|/books/java%20books/Java%20Bible/ewtoc.html (7 of 16)6/26/2005 7:54:31 PM


Java Bible:Table of Contents

String literals
Concatenation and the + operator
Character constants
StringBuffer (java.lang. StringBuffer)
Creating StringBuffer objects
Modifying StringBuffer objects
Arrays
Instantiating arrays
Auto-initialization
In-line initialization
Anonymous arrays
Setting and retrieving array elements
Array of Arrays
Exceptions
Utility Classes (java.util Package)
Hashtable
Vectors
Stacks
StringTokenizer
Resource bundles
Miscellany
Summary
CHAPTER 13—Input/Output: Java Streams
About Streams
Standard System Streams (java.lang. System)
Standard output (System.out)
Standard input (System.in)
Standard error (System.err)
java.io Streams
InputStream
OutputStream
Special-purpose streams
Filtered Streams
Buffered I/O
Line numbers
LineNumberReader
Pushing back
Typed I/O

file:///F|/books/java%20books/Java%20Bible/ewtoc.html (8 of 16)6/26/2005 7:54:31 PM


Java Bible:Table of Contents

PrintStream
PrintWriter
Object Serialization
More I/O
Summary
CHAPTER 14—Threads
About Threads
Using Threads in Applets
Creating Threaded Objects
Thread Attributes
Thread body
Thread state
Thread priority
Daemon threads
Thread groups
Multithreaded Programs
Synchronization
Deadlock
Bringing It All Together
Summary
CHAPTER 15—Weaving Applets into Web Pages
Applet Tag Syntax
CODEBASE attribute
NAME attribute
WIDTH and HEIGHT attributes
Alignment
Vertical and horizontal space
ARCHIVE attribute
Communicating with Non-Java Browsers
Applet Parameters
Going Gold
Dual-Purpose Applets
Preparing for the Future
Summary

PART IV—Abstract Windowing Toolkit


CHAPTER 16—Abstract Windowing Toolkit Overview
Abstract Windowing Toolkit

file:///F|/books/java%20books/Java%20Bible/ewtoc.html (9 of 16)6/26/2005 7:54:31 PM


Java Bible:Table of Contents

Fundamental organization
java.awt
Handling Events
The hierarchical model
Handling action events
Handling non-action events
The delegation model
Coordinate System
The x,y coordinates
Integer values
Putting It All Together
Containers
Layout managers
Summary
CHAPTER 17—Graphics, Fonts, Color, and Images
Graphics (java.awt. Graphics)
Lines
Rectangles
3D (beveled) rectangles
Ovals
Polygons
Arcs
Fonts (java.awt. Fonts)
Creating and using fonts
FontMetrics
Color (java.awt. Color)
Foreground and background colors
Images (java.awt. image and java.awt.Image)
Animation
Scaling images
Printing (java.awt.PrintJob)
Printing pages
Summary
CHAPTER 18—Widgets
GUI Components (java.awt.Component)
Buttons
Check Boxes
Choice Menus

file:///F|/books/java%20books/Java%20Bible/ewtoc.html (10 of 16)6/26/2005 7:54:31 PM


Java Bible:Table of Contents

Scrolling Lists
Summary
CHAPTER 19—More Widgets and Containers
Scroll Bars
Labels
Text Components
TextField
TextArea
Canvases
Containers (java.awt. Container)
Panels
Grouping components
Coordinates
Summary
CHAPTER 20—Windows
Windows
Frames
Frame menu bars and menus
Menu shortcuts
Menu events
Dialogs
Window Events
Summary
CHAPTER 21—Laying Out Components
Types of Layouts
Default: FlowLayout
Layout Managers
FlowLayout
GridLayout
GridBagLayout
BorderLayout
CardLayout
Insets
Drawing and Updating Components
Summary
CHAPTER 22—Bringing It All Together with JDK 1.1
Designing the JavaDraw Application/Applet
Interface-Driven Development

file:///F|/books/java%20books/Java%20Bible/ewtoc.html (11 of 16)6/26/2005 7:54:31 PM


Java Bible:Table of Contents

A call to arms: pencil and paper first


Fleshing out bare bones
Objects, Shmobjects!
Code Warrior-Digging into the Implementation Phase
Summary
CHAPTER 23—Introducing Java Foundation Classes
JFC’s Components
Examining Swing Classes
Model-View-Controller (MVC) architecture
Inheritance differences between Swing and AWT
Packages
Summarizing the Swing Classes
Other Foundation Classes
Internet Foundation Classes
Application Foundation Classes
Summary
CHAPTER 24—Getting in the Swing of Things
Introduction to the Swing Packages
Swing Objects
AbstractButton
JButton
JCheckBox
JComboBox
JFrame
JLabel
JList
JMenu
JPanel
JPopupMenu
JProgressBar
JRadioButton
JScrollBar
JSlider
JSplitPane
JTabbedPane
JTextArea and JTextField
JToggleButton
Summary

file:///F|/books/java%20books/Java%20Bible/ewtoc.html (12 of 16)6/26/2005 7:54:31 PM


Java Bible:Table of Contents

CHAPTER 25—Bringing it All Together with JDK 1.2


Get Going with JDK 1.2
JDK 1.2 incompatibilities
Changes in binary compatibility
Changes in language compatibility
Changes in runtime compatibility
Changes in API compatibility
Changes in tools compatibility
Advanced Swing Objects
Tooltips and toolbars
JTree
Text framework/Document interface
JTable
Layouts
BoxLayout
ScrollPaneLayout
ViewportLayout
Event Listeners
Wrapping Up JFC and Swing (for Now)
Summary

PART V—Advanced Java


CHAPTER 26—JavaBeans
JavaBeans Basics
Software components and software component models
Software components—the next “big thing”?
Software component models—“master plans” or “means to an end”?
You can run, but you can’t hide...
BeanBox Builder Tool Basics
Introducing the Beans Development Kit
Cooking Up Your First Bean
Properties, events, and methods
Descriptors
Two-bean example
Going the Distance
Extensible Runtime Containment and Services protocol
Activation Framework specification
Native-platform-capable Drag-and-Drop specification

file:///F|/books/java%20books/Java%20Bible/ewtoc.html (13 of 16)6/26/2005 7:54:31 PM


Java Bible:Table of Contents

Enterprise JavaBeans specification


Summary
CHAPTER 27—Networking
Stacking Data with Addresses and Ports
What’s in an address?
From network to internetwork
The TCP/IP stack
URL Operations
Basic URL manipulations
The great Web-page snatch
Encoding the URL string
URLConnection operations
The incoming headers
Sockets
Finding an address
Setting up a simple socket server
Sending from a simple socket client
RMI Operations
The package
The interface
The implementation
The stubs and the skeletons
Starting the registry
Starting the server
The applet that makes the call
The HTML
Summary
CHAPTER 28—JDBC: Java API for Database Connectivity
Introduction to JDBC
Universal database connectivity from Java
Basic characteristics of JDBC
JDBC components
Ready for client/server
Data definition and manipulation using SQL
JDBC drivers
Overview of the API
Typical uses
Connecting to a remote database

file:///F|/books/java%20books/Java%20Bible/ewtoc.html (14 of 16)6/26/2005 7:54:31 PM


Java Bible:Table of Contents

Choosing an appropriate driver


Locating the database
Creating a connection
Performing database queries and updates
Database queries and updates
Retrieving the results
Putting the JDBC to Work
The JDBC API
Interface java.sql.CallableStatement
Interface java.sql.Connection
Interface java.sql.Driver
Interface java.sql.PreparedStatement
Interface java.sql.ResultSet
Interface java.sql.ResultSetMetaData
Interface java.sql.Statement
Class java.sql.Date
Class java.sql.DriverManager
Class java.sql.DriverPropertyInfo
Class java.sql.Time
Class java.sql.Timestamp
Class java.sql.Types
Class java.sql.DataTruncation
Class java.sql.SQLException
Class java.sql.SQLWarning
Advanced Techniques
Database prepared statements
Stored procedures
Database transactions
Three-tiered design
Summary
CHAPTER 29—Multimedia
3...2...1...Action!
MediaTracker (java.awt. MediaTracker)
Adding that professional splash
Flicker-free animation: double-buffering
Putting It All Together: A Sprite Engine
A sprite for thought
Start your sprite engine

file:///F|/books/java%20books/Java%20Bible/ewtoc.html (15 of 16)6/26/2005 7:54:31 PM


Java Bible:Table of Contents

Lightweight sprites: SpriteShadows


Clipping and parallax scrolling
A mystic temple and Jane on Mars
Bright lights, loud city
A sound-event model
Summary
CHAPTER 30—The Future of Java

Appendix A
Appendix B
Index

file:///F|/books/java%20books/Java%20Bible/ewtoc.html (16 of 16)6/26/2005 7:54:31 PM


file:///F|/books/java%20books/Java%20Bible/about.html

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Preface
Welcome to Java Bible, a designed to teach programmers how to develop dynamic, distributed Web
content using the Java language. Although experience with C or C++ is helpful, it’s not required. Not
only is this book a comprehensive reference for the Java language, it actually teaches you how to create
and deploy dynamic software products using the most exciting programming language ever!

Unlike many programming books that get placed on the bottom shelf of your bookcase, this one is
different: Java Bible is designed to be both a guide and a reference. As you learn the ropes of Java,
you’ll appreciate the attention given in each chapter, teaching you the ins and outs of the language and
the issues you’ll face along the way. Once you’re comfortable programming in Java, this book

As a comprehensive reference to the massive Java language, Java Bible is packed with information
necessary to refine your programming skills. Specifically, you’ll find it rich with source code examples,
Application programming interface (API) tables, hints, tips, and warnings that are meant for the
experienced Java programmer. As a result, you’ll find yourself turning to this book long after it has
helped you become a master Java developer.

What You’ll Need

The only thing you’ll need to become an experienced Java programmer is this book and a computer
capable of running the Java Development Kit (JDK). The CD-ROM provided contains all the tools
you’ll need to write, compile, test, and debug all levels of Java program. Specifically, it comes with the
JDK for the following supported platforms: Windows 95/NT, Sun Solaris, and the Macintosh.

Additionally, the CD-ROM is packed with more than 100 applets, their complete source code
(graciously contributed by scores of Java developers from around the world), and online tutorials. This
alone is reason enough to clear off a space on your desk for this book/disc combo. But that’s just the
beginning. You’ll also find back issues of JavaWorld, IDG Books’ Web-based magazine for Java
developers, containing “living” articles in HTML format. Here you’ll find a raft of in-depth Java
articles, applets, and their source code written by professional Java developers.

file:///F|/books/java%20books/Java%20Bible/about.html (1 of 6)6/26/2005 7:54:32 PM


file:///F|/books/java%20books/Java%20Bible/about.html

Use or Lose It: How to Use This Book

The only way to learn a programming language is to use it! And that’s exactly what this book is
designed to do: get you up and running with Java. Although the text itself is meant to be read, the
examples in it are meant to be used

Of course, as you get more experienced with Java, you’ll outgrow the introductory programs provided in
the text. That’s why the listings become more complicated the deeper you get into it, and why such a
wide range of real, working applets and their source code have been provided on CD-ROM Think of this
book and the CD-ROM as inseparable, and use them both.

Feel free to jump around from part to part or chapter to chapter as you see fit. If you’ve already dabbled
in the Java language and know how to write and compile programs, there’s absolutely no need to do it
all over again. Instead, you might want to take a peek at the tables, tips, warnings, and other reference
materials provided for the experienced programmer.

As you read this book. you’ll notice we “flip-flop” between the UNIX and Windows styles when it
comes to entering commands on the command line (see “Commandline entries” later in this preface) or
discussing the JDK and a general sense. Because Java is a cross-platform technology, we attempt to give
equal play to both platforms. Because the majority of the book was written on a Windows system, you’ll
notice that the text and examples tend to favor that platform. Whether you’re a Windows user or a UNIX
user, however, you should realize that any platform-specific material presented in the text must be
adapted to the particular machine you are using Once you are comfortable doing so, the material
discussed in this book will be easily applied to the platform you use.

The Many Versions of Java

This book provides information on all three available versions of the Java platform. JDK 1.0, JDK 1.1,
arid JDK 1.2, which was still in beta 2 during final review of this manuscript. As this book went to
press, Sun released beta 3 of JDK 1.2, and a beta 4 and final product release were yet to come.

We faced a difficult choice in deciding whether to publish the Java Bible today or to wait for the JDK
1.2 final release We have chosen the former course because the JDK 1.2 changes of greatest importance
to readers of this book are either complete or well-specified, and because we suspect most of you want
to know about these now rather than later. For those developing applications with Java 1.1, this book
covers a number of classes that are in final release, but are not yet integrated with the Java JDK 1.2. The
most important of these are tire new JFC 1.1 classes and Swingset components for creating cross-
platform graphical user interfaces (GUIs). Let’s face it; Java is a moving target. We will do our best to
keep you informed of new developments at http: //www. idgbooks.com. We also encourage you to
periodically check the JavaSoft Web site (http: //java.sun.com) for news of JDK 1.1 maintenance
releases and 1.2 betas. And of course, JavaWorld (http: //www. JavaWorld.com) is the place to look for
in-depth technical updates and breaking Java news.

file:///F|/books/java%20books/Java%20Bible/about.html (2 of 6)6/26/2005 7:54:32 PM


file:///F|/books/java%20books/Java%20Bible/about.html

Part I: Introducing Java

Part I is the foundation for the entire book. This part introduces the Java programming language and its
concepts. You gain an understanding of how the Java programming language was developed and why
Java has become all the rage with Web-based application developers. You are introduced to object-
oriented programming concepts and design methodologies. After that introduction, you learn how to
apply its techniques to building your own Java applications and Webbased applets.

This part also introduces the tools that comprise Sun’s Java Development Toolkit (JDK)—the tools you
use to create your own Java programs.

Part II: Getting Up to Speed

In this part, you walk through the process of designing, developing, testing, and debugging your first
Java application. You learn how to design your applications to function as both standalone applications
and Web-based applets. You also are introduced to the debugging tools provided with the Java
Development Toolkit, and you learn how to use the Java debugger to stomp those annoying bugs. This
part shows you how to modify your Java applications and applets to accept and use the parameters
specified by command-line arguments. By the time you finish this part, you’ll know how to use the Web
to find and borrow Java applications and objects that can get your applications up and running even
faster!

Part III: Programming Elements and Techniques

This part introduces the brass tacks of the Java programming language. Beginning with the basic
concepts of tokens, types, and values, the chapters explore all the nooks and crannies of Java. You are
introduced to the language basics such as defining and using variables, controlling program flow,
creating your own classes, and handling exceptions. All the standard Java packages and
classes—including strings, arrays, streams, and threads—are reviewed in detail. Finally, this part shows
you how to weave your Java applications into Web pages and how to package your Java applications
efficiently, using Java Archive (JAR) files for fast Web access.

Part IV: Abstract Windowing Toolkit

This part introduces the Abstract Windowing Toolkit. Although the AWT is being replaced by the Java
Foundation Classes (JFC) in JDK 1.2, understanding the AWT will help you Support older Java
applications anti give you a solid foundation for understanding the JFC. This part shows you how to add
graphics, fonts, windows, and user-interface controls—such as buttons, list boxes, combo boxes, menus,
and sliders—to your own Java applications. Each AWT object described also includes a complete
reference for you to use when you develop your own applications.

file:///F|/books/java%20books/Java%20Bible/about.html (3 of 6)6/26/2005 7:54:32 PM


file:///F|/books/java%20books/Java%20Bible/about.html

This part includes a step-by-step guide to the development of the JavaDraw application—a basic graphic-
drawing application. You’ll learn how to use the AWT classes to design and implement your
application. To get you ready to move to the latest and greatest Jawa Development Kit—version
1.2—this part introduces the powerful newcomers to JDK 1.2: the Java Foundation Classes and the new
user interface classes included in them, nicknamed Swing. A detailed review of each interface
component in the Swing classes demonstrates why these classes are poised to replace the Abstract
Windowing Toolkit for Java-based user-interface development.

Part V: Advanced Java

This section introduces you to some advanced topics that outline exciting Java capabilities and
directions. In this part you learn how to implement and use JavaBeans, standalone components that can
be used by other applications, including the Java applications you create. Java also provides complete
support for networking anti database connectivity. These chapters also discuss adding network
connectivity to your Java applications, and how to use the Java Database Classes (JDBC) to add
database support Finally, this part reviews the support provided by Java for multimedia applications.

Conventions

As you go through this book, there are a few elements you’ll find in nearly every chapter. These are
conventions established to help make the text easy to read and consistent from start to finish.

Source code

Any time you encounter source code, it will be in a special font; this applies to code listings as well as
code fragments. This way, it’s easy to identify code throughout the book Whether in a fragment or a
numbered listing, code in the text appears in the following style:

import java.net.*;
public class GetAddresses {
public static void main(String[] argv) {
InetAddress ia;
try {
ia = InetAddress.getLocalHost();
System.out.println(“Local host:” + ia);
ia = InetAddress.getByName(null);
System.out.println(“Null host: ” + ia);
ia = InetAddress.getByName(“www.idgbooks.com”);
System.out.println(“IDG host: ” + ia);
} catch(UnknownHostException e) {
System.out.println(e);
}

file:///F|/books/java%20books/Java%20Bible/about.html (4 of 6)6/26/2005 7:54:32 PM


file:///F|/books/java%20books/Java%20Bible/about.html

}
}

Code elements that appear in the running text—such as the names of objects, classes, variables,
methods, and the like—are also shown in the code font (for example, the JComponent class or the
toCharArray() method), as are the file and folder names and Web URLs.

Command-line entries

Any time a cornmand-line entry appears in the book, it will reside on its own line and in the code style
to distinguish it from the rest of the text. Although the majority of command-line examples are in the
Microsoft Windows format, many are in the UNIX format. In most cases, the precise format doesn’t
matter, since you’re able to use the command for your particular platform as long as you follow the
format conventions for it. Many times, command-line entries are generic enough to be used “as is,”
regardless of the platform you’re running; therefore, the commandline prompt is identified with a
greater-than symbol (>), as in the following example:

> javac myprogram.java

Icons

A number of special icons appear throughout the book to call your attention to topics of special
relevance and interest.

The CD-ROM icon identifies materials provided on (you guessed it) the CD-ROM that
accompanies this book. For details on the contents of the CD-ROM, see Appendix B.

The Note icon is used to bring your attention to things you might otherwise be tempted to
highlight with a fluorescent marker.

The Tip icon is used to point out a tip or technique that will save you time, effort, money, or
all three!

The Warning icon is used to alert you to potential problems that might wreak havoc on your
Java programs. Throughout the text, this icon pinpoints bugs, errors, oversights, gaffes, and
anything else that may disrupt your Java programs.
JDK 1.1 and 1.2 icons point out specific parts of Java that have changed since JDK 1.0 was
released. Although much of the basic Java syntax has been maintained since the initial release,
which enables us to cover most topics from a common standpoint, it’s worth highlighting
important changes in JDK 1.1 and JDK 1.2.

file:///F|/books/java%20books/Java%20Bible/about.html (5 of 6)6/26/2005 7:54:32 PM


file:///F|/books/java%20books/Java%20Bible/about.html

A note on our examples in the text

This book’s cover tells you that two authors collaborated in writing this book. Most chapters, however,
were written by one author or the other, drawing upon individual experience. Thus we’ve used first-
person-singular constructions in many of the examples and opinions (“I recommend,” “in my
experience,” and so forth). We hope this convention helps maintain the book’s personal tone. But do
remember two of us are out there—so the use of I may change from chapter to chapter.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/about.html (6 of 6)6/26/2005 7:54:32 PM


Java Bible:About the Author

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Acknowledgments
From Aaron Walsh:

I’d like to give special thanks to the many people who made this book possible, especially to my co-
author, John Fronckowiak, for all his fine work and great help. I’d also like to thank the small army of
writers and developers who have contributed their time and effort to the charge, especially Paul
Kinnucan, Doug Schwartz, Piroz Mohseni, Bernard Van Haecke, Arthur Griffith, and Charley
Cleveland; and to Rich Burridge, who, as technical editor of this book, kept us all on track.

In addition, I’d like to extend great thanks to Barbara Mikolajczak of Mantis Development Corporation,
for finding and capturing most of the Web sites sprinkled throughout this book, and for building the CD-
ROM that comes with it; to Lisa Sontag for her help with permissions for those Web sites; and to Heidi
Steele, whose developmental editing contributed so much to the quality of the book. And finally, special
thanks to the good folks at IDG Books Worldwide without whom this book would never have seen the
light of day—especially John Osborn, Matt Lusher, Barry Childs-Helton, Lenora Chin-Sell, and Jake
Mason.

From John Fronckowiak:

I would like to thank everyone that helped make this book possible: my wife, Diane, for helping me
work through the day-to-day ups and downs while helping to keep me focused on my larger goals; and
my family—Mom, Dad, Klm, Mike, Marie, Mom S., Alicia, and Becky—for understanding and
supporting my desire to write. I’d also like to send special thanks to Studio B Productions, Inc. for
presenting me with the opportunity to work on this project—David Rogelberg, who believed in me and
my abilities; and Brian Gill, who provided an immeasurable amount of assistance in working through
the many details of this project I could never handle on my own, and many words of encouragement.
Thanks to John Osborn, who believed that I could offer something to this project, and Matt Lusher, who
helped immensely in running the marathon this book presented! Finally, thanks to my cat, Eiffel, and
Quaker parrot, Elmo, for providing companionship and many loud meows and squawks!

To my nephew Dane, with love. —Aaron Walsh

file:///F|/books/java%20books/Java%20Bible/about_author.html (1 of 2)6/26/2005 7:54:32 PM


Java Bible:About the Author

For my family. —John Fronckowiak

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/about_author.html (2 of 2)6/26/2005 7:54:32 PM


Java Bible:An Overview of Java

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

PART 1
Introducing Java
Part I provides a foundation for the entire book. In this part you are introduced to the Java programming
language and its concepts. You gain an understanding of how the Java programming language was
developed and why Java has become all the rage with Web-based application developers. Before you
begin programming with Java, it’s useful to understand the object-oriented programming concepts and
design methodologies introduced in this part. Object-oriented programming requires a different way of
thinking from that used with traditional programming languages (such as C). Following your
introduction to object-oriented programming, these chapters show you how to apply their techniques to
building your own Java applications and Web-based applets.

In addition to exploring Java technology, this part introduces the tools that comprise Sun’s Java
Development Toolkit (JDK)—the tools you use to create your own Java programs. You’ll also learn
how to get the latest Java JDK installed on Solaris, Windows 95, and Windows NT platforms.

CHAPTER 1
An Overview of Java
In This Chapter

Getting familiar with the Java environment

Understanding the Java programming language

An introduction to the basic concepts of the java language

How Java differs from C and C++

What is Java? This entire book is devoted to answering that question. Java is the most important
advance in programming technology of the past decade; it promises a whole new programming

file:///F|/books/java%20books/Java%20Bible/ch01/01-01.html (1 of 4)6/26/2005 7:54:33 PM


Java Bible:An Overview of Java

paradigm of portability and robust object-oriented capabilities. By the time you finish this book, you will
have learned Java in all its glory. If you’re new to programming, this will be a whole new world for you;
if you’re already a developer but don’t know Java, you’ll most likely be convinced to switch to Java as a
primary programming language. But before you toss your old development environment out the
window, perhaps an introduction to Java is in order. After all, Java is an entirely new technology, with
many facets that work together to get the job done.

Java Environment

Following is a brief rundown of Java’s main features. You’ll find more detailed information on these in
subsequent chapters of this book.

Java language

The Java language is an object-oriented programming language developed by James Gosling of Sun
Microsystems. Although its roots are in C++, it is a completely new software development language.
Unlike C++, it is entirely object-oriented and designed expressly with distributed, platform-independent
environments in mind. The Java language is designed to create executable content, such as applets,
applications, and handlers. In fact, Sun’s Hot Java Web browser, the first Java-savvy browser, is an
application written entirely in the Java language.

A Brief History of Java

Sun Microsystems developed the Java programming language in 1991 as part of a research project that
sought to create software for consumer electronic devices such as television sets, television set-top
boxes, and VCRs. Java’s primary goal at that time was to be small, fast, efficient, and easily portable to
a wide range of hardware devices. Pursuing that goal has made Java the general-purpose programming
language it is today.

Java was used in several projects by Sun, but it really was invisible until the release of the HotJava
browser in 1994. Sun wrote HotJava quickly to demonstrate the prowess of Java as a language for the
Internet, and to show the complexity of possible applications that could be developed.

The first Java Development Kits were released shortly afterward. Version 1.0 of the JDK included tools
for developing applets and applications for Sun Solaris 2.3, Windows NT, Windows 95, and Macintosh.
Shortly after the first JDK release, Java took the world by storm—and it hasn’t stopped making news
since!

Java runtime environment

file:///F|/books/java%20books/Java%20Bible/ch01/01-01.html (2 of 4)6/26/2005 7:54:33 PM


Java Bible:An Overview of Java

Once you have written an applet, application, or handler in the Java language, it’s up to the runtime
environment to execute the code. The Java runtime environment, also called the Java architecture, is
made up of the Java language and the Java Virtual Machine, which together provide the means to
execute Java code. The Java runtime environment is portable and platform-neutral; it is the basis of
Java’s distributed computing capabilities, and it will eventually be available for most popular personal
computing platforms.

Currently, the Java runtime environment is available to end users through Sun’s Hot Java browser,
Netscape Communications Corp.’s Netscape Navigator browser, and Microsoft’s Internet Explorer.

Java tools

The tools Java uses provide developers with everything they need to begin creating Java code. They
include the Java compiler, interpreter, documentation, debugger, and class libraries from which you
build actual Java programs (applets, applications, and handlers). In addition, the Hot Java browser and
Applet Viewer provide a runtime system for executing Java code.

Java applets

Java applets are pieces of executable Java code that are embedded in an HTML document using the
<APPLET> tag. When a Java-capable browser accesses such a page, it automatically downloads the
executable code pointed to by the special tag. When the code arrives, the Java runtime environment
executes it within the browser.

Applets are different from applications because they are derived from a special class of Java code (the
Applet class) and rely on a Java-enabled environment, such as the Hot Java browser, in which to execute.

Java applications

Standalone software applications written in the Java language are known as Java applications. They can
be executed outside of a Java-enabled environment (such as the Hot Java browser or Applet Viewer). In
fact, the Hot Java browser itself is actually a standalone Java application.

Java handlers

Java handlers are special pieces of Java code that process incoming information and convert it into an
object that the Java environment can use.

In essence, handlers provide the Java environment with a mechanism for dynamically learning how to
deal with incoming data. For example, while connected to the World Wide Web, your Java-savvy
browser may come across data that it doesn’t inherently know how to display. First-generation browsers

file:///F|/books/java%20books/Java%20Bible/ch01/01-01.html (3 of 4)6/26/2005 7:54:33 PM


Java Bible:An Overview of Java

would either pass the data off to a helper application or would be incapable of displaying the data at all;
the Java-savvy browser dynamically learns to display the data through the assistance of a handler that
the data identifies. (In this case, the handler would be downloaded to the browser and executed, giving
the browser the ability to display the previously unknown data.)

Java supports two types of handlers, protocol handlers and content handlers. Protocol handlers extend
Hot Java’s knowledge of (you guessed it) protocols. If the browser comes upon a protocol it doesn’t
understand, it can dynamically learn the protocol by simply downloading and executing the associated
protocol handler, assuming one exists.

Content handlers, on the other hand, extend Hot Java’s knowledge of (surprise, surprise) content. The
combined power of protocol and content handlers is truly incredible; a Java-capable browser can learn as
it goes, eliminating the need for costly upgrades and the difficulties of maintaining the kitchen sink
when it comes to content and protocols.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch01/01-01.html (4 of 4)6/26/2005 7:54:33 PM


Java Bible:An Overview of Java

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Java Virtual Machine (the JVM)

The Java Virtual Machine (JVM) is a specification to which you must write Java code. All Java code is
compiled for use on this non-existent machine, which is actually a set of specifications for how the code
should be generated during the program compilation process. Writing code that runs under the Java
Virtual Machine helps ensure platform independence. To guarantee true platform independence, though,
your application must include no code native to a particular platform, and depend on no native methods
of that or any other platform. Truly platform-independent code that is entirely Java can be certified by
Sun as 100% Pure Java.

You really won’t deal directly with the Virtual Machine when writing Java programs, unless of course,
you’re porting it to a new platform. But even that is unlikely, because the Virtual Machine has already
been ported to the Sun Solaris, Windows NT, Windows 95, Windows 3.1, and Apple Macintosh, BeOS,
OpenVMS, FreeBSD, IRIX, NEXTStep, OS/390, OS/400, RiscOS, VxWorks, SunOS, AIX, BSDI,
Digital Unix, HP 3000, Linux, NetBSD, OpenBSD, OSF/1, SCO, UnixWare, AmigaOS, DG/US, EPOC
16, HP-UX, MachTen, NetWare, OS/2, Reliant Unix, Solaris, and UXP/DS at the time of writing. The
Microsoft Windows 95, NT 4.0, and Sun Solaris Java Virtual Machine are directly provided by Sun.
Many Java-enabled browsers, such as Netscape Communicator and Internet Explorer, provide their own
Java Virtual Machine implementations. This is an important point for developers, since the Java Virtual
Machines supported in your favorite Web browser may not include support for the latest Java features. It
took Netscape almost six months after the release of Java Version 1.1 to include its complete support in
Netscape Communicator, and due to legal wrangling, Internet Explorer’s Java Virtual Machine still
doesn’t support all of the Java 1.1 features.

Understanding Java

Now that you know more about Java, it’s time to go beyond the concepts and to get to know the entire
Java environment—the Java language, runtime environment, and tools—on a deeper level. And what
better way to start than with the technology at the center of it all?

The Java technology consists of three entities:

• The language itself

file:///F|/books/java%20books/Java%20Bible/ch01/01-02.html (1 of 3)6/26/2005 7:54:33 PM


Java Bible:An Overview of Java

• A runtime environment
• A set of tools

At the core of everything is the programming language formerly known as Oak. Without the language
itself (now known simply as Java), the runtime environment and tools would have no purpose. And so it
only makes sense that more often than not, when people speak casually of Java, they are referring to the
programming language.

But what makes the language so revolutionary? Haven’t we been introduced to a number of
programming-language “revolutions” over the years, each of which failed in one way or another to
measure up to the hype surrounding them? In the software-development industry we’re accustomed to
new languages that promise to change the way we program, become the next level of software
development, make our jobs easier, and advance the state of the art. So why get in a tizzy about Java?
What’s so great about it that this time we should believe the hype and bother to learn a new paradigm at
the expense of time and money?

These are all valid questions, many of which will only be answered as the language itself enters the
mainstream. For now, Java is effectively brand spanking new. Yes, it has been under development for
more than six years, but it’s only now seeing the light of day. So what’s all the buzz about? What makes
Java special? To find out, we can start with a rousing marketing message coming directly from Sun.

A Mouthful of Java

Java: A simple, object-oriented, distributed, interpreted, robust, secure, architecture-neutral, portable,


high-performance, multithreaded, and dynamic language.—Sun’s definition of Java

That’s quite a mouthful of buzzwords, especially considering that just about every one of them is a goal
in the forefront of modern software development. Rather than simply accepting this definition and
moving on, let’s see how the Java language embodies these qualities.

Simple

Programming isn’t simple, no matter how you look at it. Even the most rudimentary programming
languages such as BASIC are far too complex to expect an average computer user to sit down in front of
one and whip up a functional software product. No, the general public will never think Java is simple.
Those buzzwords listed in the Sun definition are enough to send tingles of fear up and down a
nonprogrammer’s spine. But what about those of us who develop software for a living or hack around
just to keep ourselves amused?

Well, to programmers, the Java language indeed appears simple. Not overly simple, mind you, but
simple enough to get going without having to spend time learning a completely new language. For
starters, Java is designed to be as close to C++ as possible, to ensure that today’s massive base of C++

file:///F|/books/java%20books/Java%20Bible/ch01/01-02.html (2 of 3)6/26/2005 7:54:33 PM


Java Bible:An Overview of Java

programmers can migrate easily to the new language. Because Java has its roots in C++, anyone already
familiar with C++ will get up to speed with Java in no time.

People who now program in C need more time getting into the Java frame of mind. Java is an object-
oriented language through and through; C isn’t. Procedural programmers must first learn to think in
terms of objects and methods.

Not only that, but procedural programmers altogether unfamiliar with C syntax (do we have any
Pascalites in the room?) will have to come up to speed with both object-oriented programming and the
syntax of the Java language.

Although C++ programmers have an advantage right off the bat, C programmers need only familiarize
themselves with the object-oriented approach to software development before plunging right in. And the
others? Well, it’s a bit more work than learning a new syntax.

Luckily, Java is simpler to learn than C++, because Java developers intentionally removed much of the
difficulty programmers encountered with the earlier programming language. Indeed, Java was built to be
easier to learn and use than C++; as a result, it does give up some of the power found in C++. However,
the C++ features that Java omits are not used as often as one might think, and often they lead to overly
complex software design and difficulties in maintaining code.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch01/01-02.html (3 of 3)6/26/2005 7:54:33 PM


Java Bible:An Overview of Java

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Specifically, operator overloading, multiple inheritance, and extensive automatic coercion have been
omitted (although method overloading is supported). Some C++ programmers may be clutching their
chests and breathing quick, shallow gasps of air at this very moment. But until they regain control of
their lungs and vocal cords, you’d be hard-pressed to figure out whether it’s from joy or shock.

Hey, you can’t please everyone all the time, and Java doesn’t try to. By eliminating what it believed to
be the worst of C++—for better or worse—the Java team stripped away much of the complexity of the
language. Score one for simplicity.

While eliminating complexity, the Java team introduced garbage collection to further simplify the
language. Although this makes the internal Java system more complex overall, it takes the burden of
memory management off the programmer. Not only is software easier to write, thanks to the fact that
memory management comes “for free,” but bugs related to memory are dramatically reduced. Score two
for simplicity.

Java support is currently built in to the most popular Web browsers, Netscape Communicator and
Microsoft Internet Explorer 4.0.

Object-oriented

If the Java language is at all complex, it is because the language is entirely object-oriented. To the
uninitiated, object-oriented equals fear. But to those who are comfortable with thinking in terms of
objects, it equals bliss. If you haven’t already given object-oriented software development a shot, or
have abandoned earlier efforts to learn this new paradigm out of sheer frustration, now is the time to take
up the challenge. You won’t be sorry.

The premise of object-oriented programming (OOP) is simple: every programming task is considered in
terms of objects and their relationships. Think of it as similar to the challenge of building a sculpture out
of Lego bricks. Procedural programming techniques are like hand-crafting each brick when it is
needed—which takes an inordinate amount of time and effort on the programmer’s part. Each brick
requires considerable attention to how it looks, feels, and fits into the larger work.

Object-oriented programming puts the focus on the larger work itself, on what the final sculpture should

file:///F|/books/java%20books/Java%20Bible/ch01/01-03.html (1 of 3)6/26/2005 7:54:34 PM


Java Bible:An Overview of Java

be. Rather than creating a hand-crafted brick for each part of the whole, the object-oriented approach
relies on a generic form of a Lego brick, from which all other such bricks are derived. You save the time
and effort of handcrafting individual bricks; you simply use the generic brick as a template and build on
that (see Figure 1-1). The template gives you all the basic properties, and you customize it to fit your
needs. The result is a dramatic increase in productivity and reusability.

Figure 1-1: Deriving specialized objects from generic objects

For instance, if you derived a special-purpose brick from the generic brick as you worked on (say) the
hands of a sculpture, you’d only need to tweak each piece of Lego a bit more to get it to look like a
finger. Heck, they all look and act about the same; they just need a little bit of customizing here and
there. Why fashion a different type of brick for each of the ten fingers? Simply customize your basic
template to look like a finger, and then derive the rest of the fingers from that. You could then derive the
toes of your sculpture from the fingers you’ve created (they’re just stubby little fingers anyway). No
sense crafting those little fellas from scratch, no sir.

When all is said and done, you’ve put more attention and work into the sculpture as a whole than into
the individual bricks. And the biggest benefit? The next time you need to create a Lego sculpture—even
though it may differ in form and function from your previous one—the bulk of the real work is already
done. You simply derive the new sculpture from your existing one, tweaking it here and there to
customize it as needed. Sure, this is a simplified view of object-oriented programming, but the basic
approach is the essence of working with objects.

In the object-oriented world, you focus primarily on the design of your bricks (objects) and on the
operations that go along with it (methods). If you have done a good enough job of defining the basic, all-
purpose piece of Lego (and have not been all thumbs about it, to stretch this analogy even further), you
can then derive all special-purpose pieces of Lego from it.

The object-oriented functions of Java are essentially those of C++. Although current C++ programmers
will feel right at home, those without object-oriented experience will need to spend a little time getting
comfortable with this terminology and its associated concepts. To help jump-start the process, we’ll
explore object-oriented programming in more detail in Chapter 2.

Although C is not an object-oriented language, it forms the basis for C++. Because Java is
rooted in C++, Java code will look very familiar to C programmers, as far as the syntax of the
language is concerned.

Distributed

file:///F|/books/java%20books/Java%20Bible/ch01/01-03.html (2 of 3)6/26/2005 7:54:34 PM


Java Bible:An Overview of Java

Java is built with network communications in mind; these communication features are thrown in for
free. It has a comprehensive library of routines for dealing with network protocols such as the
Transmission Control Protocol/Internet Protocol (TCP/IP), the Hypertext Transfer Protocol (HTTP), and
the File Transfer Protocol (FTP). As a result, Java applications can open and access objects across the
Internet with the same ease that programmers normally expect when accessing a local file system.

This is another dramatic advantage over C and C++. You don’t have to worry about implementing the
details of networks yourself; Java comes with everything needed for truly distributed computing. A good
example of this is the Hot Java browser which, thanks to the Java language, understands how to access
and handle objects over the World Wide Web. Most other programming languages require you to either
write these networking layers yourself or purchase a library of networked code for this purpose; Java
provides these capabilities from the start.

The Future of Java Security—Java Protected Domains

The future of Java security will introduce Java Protected Domains. This is a Java security
component that has its scope defined by a set of objects that are accessible by a principal. A
principal is an entity that has accountability—in other words, it is an object for which
authorizations can be granted and revoked. A prime example of a Java Protected Domain is the
Java Sandbox itself. With the Java Sandbox—in which all code is considered untrusted,
therefore restricted—file and network access are tightly controlled. Java Protected Domains
are distinct; they may only interact with each other through trusted code, or through explicit
permissions. Java Protected Domains can be controlled on a user and application basis.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch01/01-03.html (3 of 3)6/26/2005 7:54:34 PM


Java Bible:An Overview of Java

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Interpreted

The Java language is interpreted, in other words, an interpreter must be available for each hardware
architecture and operating system on which you want to run Java applications. Traditionally, interpreted
programs are not converted into machine code, as compiled programs are. Instead, they remain in a
human-readable form, which an interpreter executes line by line.

Software developers often cringe at the thought of using interpreted language for “serious” programming
projects. Interpreted languages are notorious for being slow in comparison to their compiled brethren
and often draw heat for that reason alone.

Through the innovative use of its Virtual Machine, however, Java overcomes many of the speed issues
that bog down other interpreted languages. Java code actually goes through a compile process that
outputs what is known as Java bytecode. Java bytecode is machine-independent, conforming to the Java
Virtual Machine’s specifications, and you can run it on any system that supports the Java environment.
This code is at an intermediate stage, not fully compiled, but close enough to actual machine code that
the interpretation process takes much less time than it would otherwise.

To further reduce the overhead of interpretation, Java implements multithreading (which permits
programs to juggle several tasks at once) and handles interpretation efficiently in the background.
Compiling Java code to an intermediate stage—and then interpreting it in the background through
threads-results in much faster interpretation and gives Java a significant speed boost over traditional
interpreted languages.

The Java Virtual Machine is not really a machine at all! It’s a set of specifications that define
how Java bytecode is to be handled on a given computer system. Java programs can execute
on any computer that has a virtual machine present. Currently, the Virtual Machine exists for
Sun Solaris, Windows NT, Windows 95, Windows 3.1, and Apple Macintosh, BeOS,
OpenVMS, FreeBSD, IRIX, NEXTStep, OS/390, OS/400, RiscOS, VxWorks, SunOS, AIX,
BSDI, Digital Unix, HP 3000, Linux, NetBSD, OpenBSD, OSF/1, SCO, Unixware, AmigaOS,
DG/US, EPOC 16, HP-UX, MachTen, NetWare, OS/2, Reliant Unix, Solaris, and UXP/DS.

file:///F|/books/java%20books/Java%20Bible/ch01/01-04.html (1 of 4)6/26/2005 7:54:34 PM


Java Bible:An Overview of Java

Robust

Reliability is extremely important to software developers, especially professionals whose reputation and
careers are on the line for the products we create. It behooves us, therefore, to create robust programs
that are unlikely to fail under unknown or adverse conditions. Although this goal may sound obvious,
many languages (C in particular) are a long way from providing developers with the tools needed for
developing robust programs.

The C language, for example, is very relaxed in terms of type checking, resulting in programming errors
that fall through the cracks, only to surface later—and often at the most inopportune moments. C++ is a
much more strongly typed language, but because it is rooted in the C language, it fails to catch a number
of bugs during compile time. Not so with Java.

Java requires declarations, ensuring that the data types passed to a routine are exactly the data types the
routine requires. Furthermore, Java doesn’t allow automatic casting of data types, as C and C++ do; the
programmer must explicitly write casts. By forcing the programmer to do so, Java drastically reduces the
likelihood that slippery logic errors will be introduced into your code.

The most significant difference between Java and C/C++ is the use of a pointer model that prohibits
overwriting memory and corrupting data. Instead of pointer arithmetic, Java supports true arrays on
which subscript (boundary) checking is enforced. Since a programmer can’t mistakenly overwrite data
or access an array element out of bounds, the language eliminates the possibility of these common bugs.
The result is a very robust development system that frees the programmer from such concerns.

Java, unlike C/C++, eliminates entirely the support for true pointers.

Secure

Any time network access happens, security concerns become a big issue. Security has always been a
worry, even on the local level before networks became so popular. Now that executable content is
available, imagine the Trojan horses that might hide the most horrible viruses and interlopers come to
invade our privacy. After all, what better way to get into a user’s computer system than through the front
door? Because applets are automatically downloaded and executed, they’d never know what hit ’em,
right?

Not so. The Java team designed Java for networked and distributed environments from the onset, and it
addressed the issue of security from the very beginning. Security is a critical part of the Java
environment. Java allows you to create virus-free, tamper-free systems, thanks to the number of security
checks it performs before a piece of code can be executed.

file:///F|/books/java%20books/Java%20Bible/ch01/01-04.html (2 of 4)6/26/2005 7:54:34 PM


Java Bible:An Overview of Java

First of all, pointers and memory allocation are removed during compile time. By blocking memory
allocation and memory access until runtime, Java prevents programmers from assuming memory
locations in advance and “jumping” into memory.

Second, the interpreter verifies all bytecodes before they are executed, as shown in Figure 1-2. If the
code isn’t valid Java code, it won’t execute. Deviant code is blocked before it can become a problem.
Such things as illegal access to memory space, violation of access privileges, illegal class access, and
illegal data conversions are not permitted. As a result, a potential virus has no way of gaining access to
data structures, objects, or memory locations.

Figure 1-2: Java’s interpreter verifies all bytecode.

And finally, all Java applets are treated as untrusted code executing in a trusted environment. This
means that all applets downloaded from the Web are restricted in what they can do once they reach your
machine. Even after passing the bytecode-verification process, applets are prohibited from accessing
files on your computer. Nor can they make network connections outside of the Web server they came
from. This prevents applets from accessing Web resources other than those available on the site from
which they were downloaded. As an added security measure, applets are prohibited from executing any
code (such as external code libraries and applications) that cannot be verified in the same way that an
applet itself is. Figure 1-3 illustrates this.

Figure 1-3: Applet security restrictions

However, we all know that every security measure employed by Java is nothing more than a juicy
enticement to the world of virus authors and thrill-seeking hackers. Although Java shouldn’t be possible
to infiltrate, someone will surely find a way. And, as certainly as a security hole will be found and
exploited, it will be immediately sealed by the Java team. JavaSoft works in close conjunction with the
security team at Princeton University to find and fix Java security problems. Such is the cat and mouse
game of security in our modern world. Stay tuned.

file:///F|/books/java%20books/Java%20Bible/ch01/01-04.html (3 of 4)6/26/2005 7:54:34 PM


Java Bible:An Overview of Java

Sun is currently investigating a variety of security models for future Java releases, including
the use of encryption and authentication devices, in the hope of relaxing restrictions applied to
applets. The goal is to allow developers to create trusted applets—applets guaranteed to be
free of malicious intent or capabilities. For detailed information regarding current and future
Java security models, visit Sun’s Java home page at http://www.javasoft.com/.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch01/01-04.html (4 of 4)6/26/2005 7:54:34 PM


file:///F|/books/java%20books/Java%20Bible/ch01/images/01-01.jpg

file:///F|/books/java%20books/Java%20Bible/ch01/images/01-01.jpg6/26/2005 7:54:35 PM
Java Bible:An Overview of Java

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Architecture-neutral

Because Sun designed Java to support distributed applications over computer networks, you can use it
with a variety of CPU and operating-system architectures. To achieve this design goal, a Java compiler
produces architecture-neutral object files, or Java bytecode, from the Java source code you write.
Assuming that the Java runtime environment exists on the client-system end, the resulting bytecode
executes regardless of platform.

This architecture works, not only for networks, but also for standard software distribution. With Java
you can create a single executable that can be run on any computer that has the Java runtime
environment, as shown in Figure 1-4.

Figure 1-4: Java is architecture-neutral (platform-independent).

Such platform independence is possible thanks to a compiler that generates bytecode instructions that
are completely independent of any specific computer architecture. As a result, Java programs can be
executed on any computer since the bytecodes they are composed of may be dynamically translated into
native machine code by any Java runtime environment.

The Java Runtime Environment

The Java runtime environment is actually an interpreter that converts architecture-neutral Java bytecode
files into native machine code that can be executed. A Java runtime environment is typically installed on
end-user systems when the user installs a Java-savvy Web browser such as Netscape Navigator or
Internet Explorer. Although this is the most popular way to get a Java runtime environment up and
running, it’s only useful for running Java applets embedded in Web pages. To run full-blown Java
applications, you must install a Java runtime environment that operates independent of Web browsers.
This is easy enough, since Sun’s Java Development Toolkit (JDK)—and most Java development tools,

file:///F|/books/java%20books/Java%20Bible/ch01/01-05.html (1 of 3)6/26/2005 7:54:35 PM


Java Bible:An Overview of Java

for that matter-come with a standalone Java runtime environment.

Because Java runtime environments are merely Java bytecode interpreters that conform to the Java
Virtual Machine (JVM), vendors are free to produce their own. (It’s worth noting that people often use
the terms Java runtime environment and Java Virtual Machine interchangeably because the Java runtime
environment is an implementation based on the JVM specification.) In fact, it’s only a matter of time
before all major operating system vendors, such as Microsoft and Apple, build Java runtime
environments directly into the operating system. When they do, users won’t have to bother installing a
runtime environment themselves; Java will be supported at the operating-system level!

Portable

Assuming the Java runtime environment is present on a given computer, Java bytecode will execute
properly. Thanks to its architecture-neutral capabilities, the Java system is highly portable.

One part of the portability equation is Java’s representation of data types. C and C++, although touted as
being highly portable, are hampered by being implementation-dependent. That is, the size of primitive
data types, and the arithmetic performed on them, changes from system to system. An int (integer data
type) on one system isn’t necessarily the same size as an int on another. As a result, ease of portability
suffers.

In Java, however, primitive data-type sizes and the behavior of arithmetic on these types are explicitly
specified. For example, int is always a signed 32-bit integer value, and float is always a 32-bit floating-
point number conforming to the Institute of Electrical and Electronics Engineers’ IEEE 754
specifications. When you use primitive data types in Java, their representation and arithmetic behavior
are consistent from system to system.

The Java class libraries include portable interfaces for each platform on which the runtime environment
is available. For example, an abstract Windows class and implementations of it are available for Sun
Solaris, Windows, and the Macintosh. When using these graphics interfaces, Java automatically loads
the appropriate platform-specific interfaces for the current machine.

Finally, the entire Java system itself is portable. The current compiler is written in Java (although it was
originally written in C) and the runtime is written in ANSI C, with a clean portability boundary. The
Java system can therefore be ported to just about any computing environment, the most popular of which
(Sun Solaris, Windows, and Macintosh) are already available or currently under development.

High-performance

Java performance is impressive for an interpreted language, mostly because of the development of just-
in-time (JIT) compilers that optimize the bytecodes on the fly. According to Sun, Java programs execute
at speeds “nearly indistinguishable” from native C/C++ programs.

file:///F|/books/java%20books/Java%20Bible/ch01/01-05.html (2 of 3)6/26/2005 7:54:35 PM


Java Bible:An Overview of Java

Although interpreting bytecodes is faster than interpreting raw programming languages, since they are
already in an intermediate stage, the Java architecture is also designed to reduce overhead during
runtime. Additionally, threads are incorporated into the language, which further enhances the overall
perceived speed of Java executables.

Although Java’s performance is impressive when compared to other interpreted languages,


many developers are concerned that it is still too slow to use where raw speed is a factor. Some
accounts have Java programs running anywhere from 10 to 30 times slower than their C/C++
counterparts. While this debate heats up, Sun is working to improve the overall speed of Java
programs. Future releases of Java are likely to include an optimized compiler and a faster
runtime environment.

In addition, several leading software tool vendors, such as Borland, Symantec, Microsoft, and
Metrowerks, have developed just-in-time (JIT) compilers that convert Java bytecodes into native
machine code before execution. As a result of JIT compilers, browser vendors can now greatly increase
the speed of Java applet execution. In fact, the latest versions of both Netscape Navigator and
Microsoft’s Internet Explorer utilize JIT compiler technology, making non-JIT Java-savvy browsers
look slow by comparison. By the time you read this, a number of just-in-time compilers should be
available for speed-conscious developers.

HotSpot Virtual Machine

With the release of the Java SDK 2.0 in earlier 1998, a new and faster virtual machine is
promised—Java HotSpot Virtual Machine. HotSpot VM gets its name from the fourth-generation
bytecode interpreter technology JavaSoft acquired when it purchased Animorphic Systems. HotSpot VM
achieves faster speeds by enabling the VM to look for loops and dynamically compile the bytecode into
machine code. The VM also will look for repetitive method calls that can be dynamically integrated into
the application and “inlined” for faster execution. The HotSpot Virtual Machine promises application
execution speed similar to C and C++ applications.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch01/01-05.html (3 of 3)6/26/2005 7:54:35 PM


file:///F|/books/java%20books/Java%20Bible/ch01/images/01-02.jpg

file:///F|/books/java%20books/Java%20Bible/ch01/images/01-02.jpg6/26/2005 7:54:35 PM
file:///F|/books/java%20books/Java%20Bible/ch01/images/01-03.jpg

file:///F|/books/java%20books/Java%20Bible/ch01/images/01-03.jpg6/26/2005 7:54:36 PM
Java Bible:An Overview of Java

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Multithreaded

Multithreading is a major feature of Java, giving executables the ability to maintain several threads of
execution at one time. Not to be confused with multitasking, the capability of an operating system to run
more than one program at once, multithreading permits applications to juggle several tasks at once.

For instance, in a nonthreaded environment, only one line of execution exists for programs. Typically,
an event loop is used to keep track of the particular task at hand. This loop identifies which task is to be
executed (such as refreshing the contents of a window, tracking user input, or printing a document), and
passes it off to the appropriate routine(s). Once the task is handled, another can begin. Because only one
task at a time can be handled, the system must wait until the current task has been completed before
handling a new one.

Although programming languages such as C and C++ allow the developer to implement multithreading,
it takes a considerable amount of effort compared to Java, which implements threading synchronization
directly. Based on C.A.R. Hoare’s widely used monitor and condition-variable paradigm, Java supports
multithreading in a clean and robust implementation.

So what can you do with threads? Just about anything, really; you can assign each line of execution to a
thread and synchronize that thread with other threads as needed. They can dramatically improve
interaction with users, handling multiple requests at once. With threads, real-time response times are
possible.

A good example of threads in action is the garbage collection feature of the Java language. This facility
is a low-priority thread which runs in the background as other tasks are executing. It monitors objects
and all references to them, disposing of them when they are no longer in use. Because this process is
controlled by a thread running in the background, other threads go on undisturbed.

Another powerful example of multithreading would be a program that supports simultaneous input,
output, and user interaction, such as taking real-time audio input from a microphone while
synchronizing it with a video image being played on the screen. In this case, such a system could match
incoming audio to the lips of computer-generated characters in real time. Such a computer karaoke
program would take all the difficulty out of singing in sync with a video image, always the most

file:///F|/books/java%20books/Java%20Bible/ch01/01-06.html (1 of 3)6/26/2005 7:54:36 PM


Java Bible:An Overview of Java

embarrassing part of the party piece. (On second thought, is there any part of karaoke that isn’t
embarrassing?)

Okay, this is pretty demanding. Although it’s not likely that you could develop such a program using
Java today, future versions of the language may be fast enough to keep up. Nonetheless, it’s a valid
example of threads handling different parts of a program.

For the power of multithreading to be fully realized, however, the systems on which Java code is
executed must also support threads. Because true preemptive multitasking and multithreading are at the
foundation of all modern operating system developments, in the near future most platforms will be up to
par. For the lime being, Java’s multithreading capabilities are limited by the underlying architectures of
the systems on which it executes.

Dynamic

Fundamentally, distributed computing environments must be dynamic. Java was designed to adapt in a
constantly evolving environment. It is capable of incorporating new functionality, regardless of where
that functionality comes from—the local computer system, local and wide area networks, and the
Internet are all potential contributors.

In object-oriented C++ environments, as in most programming environments, developers don’t write


every line of code themselves. Instead, they rely on a wide array of class libraries to extend the
functionality of their programs. If a developer needs to add support for a particular feature, such as the
ability to play moving videos, he or she simply links in new class libraries that can handle the job.

Sometimes, these libraries are distributed in ways the developer can’t control, such as with an operating
system or windowing environment. In these cases, updates to libraries might reach the customer before a
developer has the chance to recompile the program using them. When a customer is running an old
version of the developer’s product, and it attempts to dynamically link in an updated library such as this,
there is the potential for real problems. Since the program hasn’t been recompiled to handle the updated
class library, it will likely break.

If the developer had the ability to simply recompile the program with the updated library, and then get it
into customers’ hands in time, everything would be fine. In this regard, the object-oriented goal of C++
falls short of the mark

Contrast these limitations of C++ with Java, which is capable of dynamically linking in new class
libraries, methods, and instance variables at runtime, without fear of breaking the system. Java can also
determine the type of a class at runtime through a query, making it possible to either dynamically link in
new classes or abort the mission altogether depending on the results of such queries. These capabilities
give Java programs a level of flexibility when executing not possible with most other programming
languages.

file:///F|/books/java%20books/Java%20Bible/ch01/01-06.html (2 of 3)6/26/2005 7:54:36 PM


Java Bible:An Overview of Java

Java in a Nutshell

It’s clear that the Java language is an extremely sophisticated and powerful new entry into the world of
programming. It’s also clear that the language is a perfect fit for the World Wide Web. But what’s not so
clear is where Java will be in a year or two.

Yes, it started off with tremendous momentum. The Web world is all wound up over its potential, and
for good reason. Just the first few Java applets to hit the Web were impressive enough, beyond anything
the Web had to offer by itself, and reams of even more impressive work have surfaced, and continue to
do so, since the language moved from release to release. The fact that Java itself was used to create the
Hot Java browser proves the language is capable of more than applets; it can also be used for full-blown
applications.

But will it survive and become the next great programming language? Will it ever equal or overthrow C+
+ in terms of industry acceptance? Although this remains to be seen, the Java language is clearly
positioned for such a steady and successful rise to the top. For starters, it is based on technology that the
next generation of software programs will require. Like it or not, we’re moving into a networked world
where distributed computing will become the norm.

Java has everything it takes to make the transition from desktop to network-based computing a smooth
one. it was built specifically for that, and it’s clearly up to the task. However, the professional software
development industry is slow to change and Java might not have had such a brilliant chance were it not
easily learned by C++ programmers and had it not maintained compatibility with both C and C++.

The ability to use C and C++ within Java is very important. C++ succeeded where Objective C did not
because it was backward-compatible with the volumes of C code that programmers had spent years
developing. Companies have a lot of time and effort represented in old code, not to mention money, and
so it’s to Java’s benefit that it can coexist with existing C/C++ source code.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch01/01-06.html (3 of 3)6/26/2005 7:54:36 PM


file:///F|/books/java%20books/Java%20Bible/ch01/images/01-04.jpg

file:///F|/books/java%20books/Java%20Bible/ch01/images/01-04.jpg6/26/2005 7:54:37 PM
Java Bible:An Overview of Java

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Heavy hitters in the technology world have already jumped feet-first into Java. Borland, Symantec,
Metrowerks, Macromedia, Microsoft, Mitsubishi Electric, Fuji, Xerox, Andersen Consulting, U.S. Postal
Service, NASA, Novell, Sybase, Oracle, and scores of others are already working with Java. But more
importantly, Java is fast becoming a must-have technology in the latest crop of Web browsers.

Perhaps more important is integration of Java into all the popular Web browsers—including Netscape
Communicator and Microsoft Internet Explorer. Thanks to this development, Java will be seen and used
by more people in a shorter period of time than any other programming language, ever.

In order for Java to become the next de facto development language, it will have to do all this and more.
It’s nearly impossible to shift an entire industry to a new standard just because an up-and-coming
technology holds such promise. Java is new, brand new, and will have to deliver on all its promises
before it stands a chance of taking over the programming world. But, if early indicators are any sign of
things to come, hold on tight. A revolution is in the air and sweeping out into the ether.

Java Versus C/C++

Java was developed to address the inadequacies of C++; perhaps now is the best time to take a look at
the differences between it and the C/C++ languages.

First, remember that Java is closer to C++ than to C. It’s a fully object-oriented language, while C is not.
C++ maintained a backward compatibility with C, and in doing so sacrificed the possibility of becoming
a full-fledged object-oriented language.

Sure, C++ is more than capable in terms of object-oriented development, there’s no denying that. Many
believe that C++ is the be-all-and-end-all of programming languages and staunchly defend its position in
the object-oriented programming world. But there are just as many, if not more, who feel it falls short of
being a true object-oriented language. In fact, that’s exactly what prompted the development of Java; C+
+ just didn’t cut it.

While the years-old debate over C++ and its viability as an OOP language rages, which I’m not eager to
get into here, let’s take a look at what Java does differently than C/C++.

file:///F|/books/java%20books/Java%20Bible/ch01/01-07.html (1 of 4)6/26/2005 7:54:37 PM


Java Bible:An Overview of Java

Data types

Java omits three key data types that C/C++ supports: pointers, unions, and structs.

Pointers

Conventional wisdom insists that C and/C++ programmers must become proficient in the use of pointers
if they are to master these languages. Although pointers are no problem once you’ve spent the time
learning how to use them and become comfortable with the nuances of their implementation, beginners
often struggle greatly with them. Despite these difficulties, mastering the use of pointers made it
possible for C/C++ programmers to directly access memory locations and infiltrate the innards of data
structures.

Significantly, Java does away with pointers entirely, passing all arrays and objects by reference without
the use of the pointer type at all. As a result, memory locations can’t be infiltrated as they could (and
often are) with C/C++. The lack of a pointer type makes it impossible for a program to accidentally, or
intentionally, overwrite data at a location in memory. This makes for a much more secure and bug-free
development experience, because the whole pointer-management process is eliminated.

Unions and structs

Both union and struct data types are omitted from the Java language, immediately raising the question,
How can this be good?

Although these types do not exist, the Java language provides similar functionality within the framework
of an object. For example, a typical C/C++ struct needed to define the various fields of a book record
used in an inventory control program might look something like this:

struct Book {
char title[TITLESIZE]; /* book name (ex. “Java Bible”) */
int pubCode;
/* code to identify publisher (ex. 3435 = IDG) */
char authFirst[NAMESIZE];
/* author’s lastFirst nName (ex. “WalshAaron”) */
long isbnCode; /* ISBN book code */
int quantity; /* number of books in stock */
double msrp; /* manufacturer’s suggested retail price */
double (*calc_price) (double, double);
/* price at time of purchase*/
};

file:///F|/books/java%20books/Java%20Bible/ch01/01-07.html (2 of 4)6/26/2005 7:54:37 PM


Java Bible:An Overview of Java

Aside from the fact that this is a simple example, whereas lots of additional information might be
included in a real implementation, the above structure is very typical of those found in many C/C++
implementations. The last line, in particular, is worth looking at:

double (*calc_price) (double, double);

This line of code is actually a pointer to a function. When the structure for a book is allocated and
initialized, the programmer must supply one of these, as defined in the struct declaration. In our
example, the calc_price function takes two doubles as arguments and returns a double that is the
computed sale price of the book. Such a calc_price function might look like this:

double calc_price (double msrp, double discount) {


/* calculate and return price based on discount percentage: */
return (msrp — (msrp*discount) );
};

Here we have a struct that lays out the various fields to be used and a function that is used to calculate
the sale prices, based on whatever the current discount percentage is. When a book record is allocated
and initialized, the function pointer goes along with it:

main( ) {
struct Book FoundJava = {
“Java Bible” /* title */
3435, /* code to identify book’s publisher */
“Walsh”, /* author’s last name */
4367758, /* ISBN code */
100, /* number in stock */
49.95, /* manufacturer’s suggested retail price */
calc_price /* pointer to the function calc_price */
};
}

Now, suppose the book was being sold at a discount of 15 percent. In C, the following line of code
would perform the calculation and output the sale price:

printf(“price = %f\n”, FoundJava.calc_price (FoundJava.mspr,


0.15) );

This is all well and good, but what happens in Java, where structs don’t exist?

file:///F|/books/java%20books/Java%20Bible/ch01/01-07.html (3 of 4)6/26/2005 7:54:37 PM


Java Bible:An Overview of Java

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch01/01-07.html (4 of 4)6/26/2005 7:54:37 PM


Java Bible:An Overview of Java

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

In Java, classes perform all the functionality of unions and structs, making those data types obsolete. In
addition, classes in Java allow the programmer to write cleaner code that combines the object (the Book
layout) and methods (the routines that operate on the object; calc_price, in this case) in one unit, while
providing a mechanism for keeping certain information private.

For instance, many fields of the book record shouldn’t be available to routines other than those that have
an absolute need to modify their content. With C, any field in the Book structure can be easily accessed
and changed. This might seem like a good idea at first, but in reality, only certain pieces of code should
have access to this private information. This is exactly what Java provides, as shown in Listings 1-1 and
1-2:

Listing 1-1: The Book class definition

class Book {
String title;
int pubCode;
String authLast;
long isbnCode;
int quantity;
private double msrp;
double calc_price (double discount) {
return (msrp - (msrp*discount) );
/* notice that this function is part of the class definition
itself, and is not an external function, as with C */
}

Listing 1-2: The Book class constructor

Book(String a_title, int a_code, String a_auth, long a_isbn,

file:///F|/books/java%20books/Java%20Bible/ch01/01-08.html (1 of 4)6/26/2005 7:54:37 PM


Java Bible:An Overview of Java

int a_quant, double a_msrp) {


title = a_title;
pubCode = a_code;
authLast = a_auth;
isbnCode = a_isbn;
quantity = a_quant;
msrp = a_msrp;
}
}

What we have here is the same basic concept of a structure and the calc_price function, yet all bundled up
into a single object. The Book class, the code template from which an object can be created when
executed, not only describes all the data but also the routine calc_price previously residing outside the
structure. Here, the routine is part of the object, an inherent part of the class. As such, it references the
data element msrp directly to perform the calculation.

Classes and methods

In Java, as with other OOP languages, we have declared what is known as a class (Book) and the method
(calc_price) that goes along with it. You can think of a class as a template for creating objects, where an
object is a variable created from a given class. Classes can include both data, known as instance
variables, and the routines that operate on that data, known as methods. In the Book class example we’ve
been working with, both data and methods are included in the declaration.

In addition to declaring a number of standard instance variables (title, pubCode, authLast, isbnCode,
quantity), one has been declared private. Since msrp is a private instance variable of the Book class, it can
only be accessed by objects created from the original Book class. This prevents msrp from being accessed
or modified without proper cause; it keeps this data safe and private, available only to those methods
that should have access to it.

We’ve also included a second method that has the same name as the class itself (Book). Methods having
the same name as the class they are part of are known as constructors, and they are invoked when a new
object is created from that class. When put into action, a new Book object is instantiated from the class
we created:

class MyClass {
public static void main(String args[]) {
Book FoundJava = new Book(“Java Bible”, 3435,
“Walsh”, 4367758, 100, 49.95);
System.out.println(“price = ” +

file:///F|/books/java%20books/Java%20Bible/ch01/01-08.html (2 of 4)6/26/2005 7:54:37 PM


Java Bible:An Overview of Java

FoundJava.calc_price(0.15) );
}
}

What we have with Java is functionally equivalent to what we had with structs and a separate calc_price
routine, yet it’s all within one easy-to-use chunk of code-the Book class!

Additionally, we’ve been able to create code that prevents unauthorized use of instance variables. This is
easily seen in our example, as we can calculate the price of a book without having to access msrp
directly. The calc_price method has access to the private msrp instance variable and performs the
calculation for us without our having to reference this data directly. We simply feed the calc_price
method a discount percentage and it does the rest.

No matter how many different Book objects are instantiated, we only need to pass a discount amount to
the calc_price method for each. We don’t have to bother accessing this value directly and are freed of the
responsibility of keeping track of variables such as these. We let the object take care of itself, as it
should.

Operators

As you’ll see in Chapter 13, Java supports almost all operators found in C, and the Java operators have
the same precedence and associativity as their C counterparts. In addition, Java introduces several new
operators:

+
>>>
& and |
instanceof

Although + may appear to be the arithmetic addition operator, when applied to strings it is actually a
concatenation operator. As you’ll learn in Chapter 15, Java strings are objects that may be joined
together (concatenated) with the + operator.

Although it might appear that having two operators of the same name implies operator
overloading, Java doesn’t support overloading of operators as C++ does. The arithmetic + and
string concatenation + operators are two completely different operators, each operating on its
own data types.

>>>

file:///F|/books/java%20books/Java%20Bible/ch01/01-08.html (3 of 4)6/26/2005 7:54:37 PM


Java Bible:An Overview of Java

In Java, the >>> operator performs a right shift with sign extension. All integer values in Java are signed
values. As a result, Java introduces a >>> operator that performs a right shift while treating the value on
which it is operating as an unsigned value: bits are shifted right with zero sign extension.

& and |

Although the & and | operators perform bitwise operations when applied to integral values (& performs a
bitwise AND, | performs a bitwise OR), it’s another story when these operators are applied to boolean
values. Unlike C/C++, where boolean values may be treated as integral values, Java Booleans are
actually objects that resolve to true or false. As a result, when these two operators are applied to boolean
values, logical operations are performed (& performs a logical AND, | performs a logical OR).

Java’s logical & and | operators always evaluate both operands. They don’t “shortcircuit” when the
result is known after evaluating only the left operand (as their C/C++ counterparts do). In cases where
you want a short-circuit logical evaluation, use the && and | | operators.

Since pointers are not implemented in Java, the & (dereference) operator from C/C++ isn’t
supported. For that matter, neither is the * (reference) operator.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch01/01-08.html (4 of 4)6/26/2005 7:54:37 PM


Java Bible:An Overview of Java

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

instanceof

Java’s instanceof operator is used to determine if an object was created from a specific class (objects and
classes are explained in Chapter 4). Use of the instanceof operator is shown in Appendix B, the Java
Language Reference.

Although the instanceof operator may conjure up fond memories of a similar sounding operator
found in C/C++, Java doesn’t support sizeof. You’ll also note that, unlike C/C++, Java doesn’t
support the comma operator to combine two expressions into one, except in a very limited
fashion in the conditional portion of for loops, as discussed in Chapter 12.

Command-line arguments

Command-line arguments are those arguments sent to an application program when it is invoked from,
you guessed it, the command line. For instance, when you are at the DOS prompt in a DOS
environment, you execute a program by typing the name of the program:

c:\>crunch

In this example, the program named crunch would be executed. We’ve simply typed the program name at
the command prompt and pressed Enter. The program, if available, is executed. Let’s say, for illustrative
purposes, that crunch takes two files and compresses them into a single file. How do we specify which
files to compress and the name of the file that would result? Since we didn’t provide command-line
arguments above, crunch might prompt us for the names of each when it is executed:

First File to crunch: fileone


Second File to crunch: filetwo
Compress and save as: mycrunch

This is fairly straightforward, since crunch prompted us for the name of each file to compress and the
name of the file to save the compressed files into. Here, we’d expect the file my crunch to contain our
crunched files, when all is said and done.

file:///F|/books/java%20books/Java%20Bible/ch01/01-09.html (1 of 3)6/26/2005 7:54:38 PM


Java Bible:An Overview of Java

But what if we didn’t want to bother with these prompts and knew right from the beginning what files to
compress? If crunch supported command-line arguments, we could supply these names at the same time
as we execute the program:

C:\>crunch fileone filetwo mycrunch

Upon executing, crunch would see that the file names had been specified as command-line arguments and
bypass the prompt altogether. The result would he the same as if we had manually entered the names at
each prompt, although the use of command-line arguments makes the process a little faster, since we
don’t have to bother typing these three file names upon executing.

Some programs expect all user input to come directly from the command line at execution time and
don’t bother to prompt you for information if it has been omitted from the command line. These
programs simply return an error message, if even that, to let you know they were unable to complete the
job successfully.

So how does a program such as crunch get these command-line arguments and make use of them? In C/C
++, the operating system passes them directly to the program through the use of argument variables:

argc— specifies the number of arguments appearing on the command line


argv—a pointer to an array of strings containing the arguments

In C/C++, the operating system passes the entire command line as arguments to the program, including
the name of the program itself. In our example, then, the first argument in the argv parameter would be
crunch. But Java is a little different; in Java, only one parameter is passed to the executable:

args—an array of strings that contain the arguments

The args parameter is simply an array containing the command-line arguments. Rather than bothering
with two parameters, as C/C++ does, Java only needs this one.

But how does the Java program know how many parameters are included, since only an array is passed,
without the benefit of an argc parameter? It’s simple; arrays in Java include a length variable that can be
used to extract the number of arguments in the array itself, eliminating the need for an argc parameter:

args.length;. /* retrieve the number of elements


in the args array */

Another difference between Java and C/C++ command-line arguments is seen in the content of the
argument array. Where the C/C++ argv parameter contains the name of the program itself, such as crunch,
Java’s args parameter contains only the command-line arguments (such as fileone, filetwo, and mycrunch, in

file:///F|/books/java%20books/Java%20Bible/ch01/01-09.html (2 of 3)6/26/2005 7:54:38 PM


Java Bible:An Overview of Java

our crunch example). In Java, the name of the application being invoked is the same as the name of the
initial class executed where the main method is defined. (It is possible for several classes to contain a
main method.) As a result, Java already knows the name of the program being executed and doesn’t
need to be told this explicitly, as it does with C/C++. The Java runtime environment just passes along the
commandline arguments, and that’s enough.

Strings

In C/C++, strings are really nothing more than a null-terminated (/n) array of characters. But in Java,
they are first-class objects. Actually, two classes exist for strings, String and StringBuffer. Java strings
offer four main advantages over C/C++ strings:

• Consistency: As objects, the manner in which strings are obtained and their elements accessed
is consistent across all strings and all systems.
• Predictability: Java strings function predictably every time, thanks to well-defined
programming interfaces for both the String and StringBuffer classes.
• Reliability: String and StringBuffer classes perform extensive testing for boundary conditions at
runtime, catching errors before they become a real problem.
• Localization of text: Strings consist of Unicode characters, which makes localization of text
transparent.

Java strings are covered in more detail in Chapter 14, but for now it’s worth noting that strings have
always caused difficulty for C/C++ programmers. Because strings are such an important part of any
programming language, Java makes it possible to use them to their fullest extent without the difficulties
often encountered with C/C++.

The Java String class is used to represent strings that will not change. StringBuffer, on the other
hand, is specifically for strings that will change during the course of program execution.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch01/01-09.html (3 of 3)6/26/2005 7:54:38 PM


Java Bible:An Overview of Java

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Comments

Java supports both C and C++ style comments, in addition to an altogether new comment syntax. Here’s
a brief example of the three types of comments you can use in Java:

int i ; /* this is the ANSI-C style comment */


int i ; // and this is the C++ style, limited to one line of text
int i ; /** And here’s a completely new comment syntax! Notice
that this comment begins with a slash and two asterisk characters
and can span many lines, just as with ANSI-C comments. But
what’s the difference, besides the extra asterisk at the
beginning of this comment? */

Although Java supports both C and C++ comments, it also introduces a special type of comment that
does just what any comment does. It tells the compiler (or interpreter) to ignore everything inside the
comment, since it’s only there to help people make sense of the code.

Besides functioning as a regular comment, this new comment serves a special purpose—automatic
documentation generation. That’s right—documentation generated automatically from comments. This
documentation is created as a series of HTML files that not only help document your programs, but also
show the hierarchy of your code in relation to the larger system of Java classes! (See Figure 1-5.) And
since it’s in the HTML format, you can hypertext-jump through this documentation just as you would
any other Web page. All thanks to an odd-looking comment.

This special type of comment, formally known as a Doc Comment, is often found at the beginning of
class and method definitions to assist in the creation of code documentation. In addition, Doc Comments
can be applied to variables.

file:///F|/books/java%20books/Java%20Bible/ch01/01-10.html (1 of 4)6/26/2005 7:54:38 PM


Java Bible:An Overview of Java

Figure 1-5: Documentation automatically generated from a Doc Comment, showing this class in
relation to others in the system

With Doc Comments, you use /** to indicate that what comes between it and the closing */ should be
treated as documentation when encountered by the javadoc tool. (javadoc is one of the many tools that
come with Sun’s Java Development Toolkit.) You can embed special documentation tags (Doc Tags),
which begin with the @ character, within Doc Comments to further extend the automatic document
generation performed by javadoc:

/* A bogus class definition whose only purpose is to show


* the format of Doc Comments and Doc Tags in action:
* @version 1.0 6 Nov 1997
* @author Aaron E. Walsh
*/
class BogusClass {
. . . }

When run through the javadoc tool, the above comment would generate documentation with an associated
version and author entries. Doc Comments and Doc Tags can be a great help when you’re documenting
software developed with Java. For details on using Doc Comments, point your browser to http://java.sun.
com/docs/codeconv/CodeConventions.doc4.html.

Odds ‘n’ ends

Although we’ve discussed the most obvious areas where Java differs from C and C++, there are a few
other things you’ll want to be aware of when making the transition to Java:

• Through a mechanism known as varargs, C and C++ provide for a variable number of
arguments to be passed to a function. This is not supported with Java.
• Although goto is a reserved word in Java, it is not implemented or supported.
• Boolean data types are true literals in Java, not a representation of the integers 0 and 1, as they
are in C and C++. Java boolean data types, therefore, cannot be typecast into integers.
• #define and #include (preprocessor mechanisms) are not available in Java, although they are
available in C and C++.
• Java does not provide enumerated types.

file:///F|/books/java%20books/Java%20Bible/ch01/01-10.html (2 of 4)6/26/2005 7:54:38 PM


Java Bible:An Overview of Java

These odds and ends, and those detailed previously, sum up the differences between the Java and the C/C
++ languages. However, there are a number of areas where Java and these languages are similar.

To make the transition from either C or C++ relatively easy, Java maintains a lot of the look and feel of
those languages. For instance, the style of Java programs (such as the use of whitespace, comments, and
grouping of code) is much the same as in C and C++. Just as with C/C++, whitespace and comments
(with the exception of Doc Comments) are ignored by Java altogether and are only used to make code
more readable to human beings. For instance, the example Book class we created earlier could just have
easily been written without whitespace and comments:

class Book {String title;int pubCode;String authLast;long


isbnCode;int quantity;private double msrp;double calc_price
(double discount) {return (msrp-(msrp*discount) );} Book(String
a_title, int a_code, String a_auth, long a_isbn, int a_quant,
double
a_msrp) {title=a_title;pubCode=a_code;authLast=a_auth;isbnCode =
a_isbn; quantity=a_quant; msrp=a_msrp;}}

Although this makes for ugly reading to you and me, Java doesn’t care. For that matter, neither does C
or C++. White space and comments simply make the code more understandable and prettier to look at
for our sake.

Another thing you’ll notice immediately about Java, which it shares with C/C++, is case sensitivity. Case
matters, so you have to pay special attention to exactly how you mix and match upper- and lowercase
letters in class, method, and variable names. For instance, the variable myJavaThing is not the same as
MyJavaThing.

And while we’re on the subject, it’s worth noting that classes are typically capitalized, but methods and
objects are not. This is merely a convention of Java (one also seen in C++), so you can in fact do
whatever you want when it comes to capitalization. However, in the interest of code readability and
maintenance, it’s better to stick to the conventional way of doing things.

C/C++ programmers will also find comfort in the way Java code is arranged. As with C/C++, you usually
indent statements to reflect their hierarchy within a block of code, and you balance curly braces ({ }) to
show the nesting of functions.

With Java, you make your code more readable by using curly braces to separate blocks of code and
semicolons to separate statements. These conventions should be familiar to C/C++ programmers.

These factors, taken together, make the Java language enough like C++ in both syntax and the
implementation of object-oriented devices (such as classes, methods, objects, and inheritance) that C++
programmers will have little problem leaping feet first into it.

file:///F|/books/java%20books/Java%20Bible/ch01/01-10.html (3 of 4)6/26/2005 7:54:38 PM


Java Bible:An Overview of Java

C programmers, on the other hand, must first become comfortable with the entire object-oriented
approach to software development—which we discuss in detail in Chapter 2.

Summary

Java technology consists of the Java language, a runtime environment, and a set of tools. The language
is simple, object-oriented, distributed, interpreted, robust, secure, architecture-neutral, portable,
multithreaded, dynamic, and capable of high performance.

• Java, like C++, is object-oriented, and it is similar to C++ in syntax and style. However, it also
offers significant improvements. It replaces pointers, unions, and structs with code that prevents
unauthorized use of instance variables. It uses operators, significantly improved command-line
arguments, and more consistent, predictable, and reliable strings. It also supports an entirely new
type of comment.
• C++ and Java are similar in a number of significant ways, such as case sensitivity, the
arrangement of code, and ways of implementing OOP devices such as classes and methods.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch01/01-10.html (4 of 4)6/26/2005 7:54:38 PM


Java Bible:Object-Oriented Programming and Terminology

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

CHAPTER 2
Object-Oriented Programming and Terminology
In This Chapter

An introduction to object-oriented programming

Understanding abstraction, states, behavior, variables, methods, and encapsulation

How to communicate with objects through interfaces

How to get the most mileage from your code with inheritance

An introduction to object-oriented analysis and design

Because Java is an object-oriented programming (OOP) language, it only makes sense for us to take
time to find out what that means. Programmers experienced with object-oriented concepts and
terminology may choose to skim this chapter and refresh their memories, or to skip it altogether,
depending on their comfort level with the topic. Others will want to devote some serious time to the
following material. In it are the keys to fully unlocking Java’s potential, for without a solid
understanding of object-oriented programming, making sense of this new language is next to impossible.

If you are new to object-oriented programming, you may become overwhelmed by the end of this
chapter. Hyperventilation is understandable, if not expected, because so many of the concepts found in
the object-oriented world run counter to the way you’re normally taught to program. If you’re new to
OOP, I’d suggest taking a moment to search the Web for Java-related information, such as is available at
Sun’s JavaSoft site, Gamelan, or JARS, followed by a quick trip to your local library or bookstore. By
all means, proceed with this book, but while you’re at it, take the time to learn more about object-
oriented programming. This type of programming is a very different approach to software development
than most of us have experienced before. We’ve probably spent a great amount of time learning
procedural programming languages such as Pascal and C, which are not object-oriented, and that makes
it extremely difficult for us to think of software development from this new perspective.

file:///F|/books/java%20books/Java%20Bible/ch02/02-01.html (1 of 3)6/26/2005 7:54:39 PM


Java Bible:Object-Oriented Programming and Terminology

Despite the fact that object-oriented programming is nearly 30 years old, originating with the Simula67
language introduced in 1967, the term object-oriented programming has been misused and
misunderstood since it was first coined, and it continues to be a source of confusion even today.

Several schools of thought exist regarding what OOP is and what constitutes a “real” object-oriented
programming language—these are the result of programmers trying to make sense of and establish a
standard way of defining such things. In fact, in professional software engineering circles the term
object-oriented programming represents only one portion of a much larger software development
process. In this sense, OOP refers to the actual implementation in code that comes after the processes of
object-oriented analysis (OOA) and object-oriented design (OOD) have been completed.

Although object-oriented concepts and terminology aren’t very difficult to learn on a superficial level, it
takes time for the principles to sink in, to settle, to become a natural part of our thinking. Because of
this, some observers claim that learning the object-oriented approach is overly difficult and not worth
the effort. Such thinking is a shame, because the potential benefits are tremendous. Anything worth
learning usually takes a bit of effort, and OOP is no exception.

But fear not—I won’t attempt to turn you into a master of the art of object-oriented programming, nor
will I introduce highly technical concepts and terminology here. And I only briefly discuss OOP as a
part of object-oriented analysis and object-oriented design; a number of books dedicate themselves
entirely to these subjects. Instead, I attempt to give you a clear understanding of OOP as it relates to the
task at hand—learning Java. As you’ll soon see, the rewards are great and the effort is relatively small,
once you understand the basic concepts we’re about to explore.

So What Shall We Look at in This Chapter?

How are objects created? How are messages sent? How does encapsulation work? These are some of the
questions this chapter answers. Objects, messages, and encapsulation are just a few of the terms covered
here. As we proceed from term to term, concept to concept, I’ll try to maintain a vein of continuity—a
theme of learning:

1. After talking about objects, I’ll plunge directly into abstraction, a way of thinking that’s
crucial to our ability to properly define objects.
2. Abstraction is followed by a look at the state and behavior of an object, known in Java
terminology as variables and methods.
3. After exploring the internal workings of objects, I take a closer look at encapsulation, the
interface each object has, and the messages objects send to each other.
4. Next, I’ll ease into modularity, which lets us change the internal variables of an object, and
classification, which lets us define the external properties of objects.
5. Finally, I’ll take a look at inheritance—a powerful OOP capability that lets you use existing
objects to construct new ones.

file:///F|/books/java%20books/Java%20Bible/ch02/02-01.html (2 of 3)6/26/2005 7:54:39 PM


Java Bible:Object-Oriented Programming and Terminology

Keep in mind that the concepts we’ll cover are not unique to Java; they are fundamental to the practice
of object-oriented software development. However, although the concepts are the same, the actual terms
vary among languages. For instance, in Java, the behavior of an object is implemented using methods,
while C++ calls them member functions.

Because this book focuses on Java, I present all object-oriented terms and concepts to you as they are
formally known in the Java language. And because I suspect that the majority of people reading this
have had experience with C and/or C++, I point out similarities between Java’s object-oriented
implementation and those languages as much as possible.

Object-Oriented Terminology

Superficially, object-oriented means nothing more than looking at the world in terms of objects. In life,
we are surrounded by objects: clothes, dishes, appliances, pets, cars, bikes, computers, friends,
neighbors, and so on (see Figure 2-1).

Figure 2-1: In life, we are surrounded by objects.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch02/02-01.html (3 of 3)6/26/2005 7:54:39 PM


file:///F|/books/java%20books/Java%20Bible/ch01/images/01-05.jpg

file:///F|/books/java%20books/Java%20Bible/ch01/images/01-05.jpg6/26/2005 7:54:40 PM
Java Bible:Object-Oriented Programming and Terminology

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Each of these objects has traits that we use to identify them. For instance, my cat is a black short hair
with a white crest on his chest. Harley can further be identified by his green eyes and the extra two toes
he has on each paw (that’s right, seven toes per paw—it looks a little funny, but doesn’t seem to bother
him).

Harley is also incessantly hungry, no matter how often I feed the little fellow. The fact that he’s hungry
helps identify him. When a friend drops by for lunch, it’s not uncommon for me to say, “Keep your eyes
on your sandwich, or the hungry one will get to it.” By saying “the hungry one,” I’ve identified Harley
as opposed to Bennett, the other cat likely to be rubbing up against my guest’s leg.

While I’m at it, allow me to identify the Bennett object as well. Bennett is the yin to Harley’s yang:
She’s pure white, has blue eyes and the softest fur l’ve ever known a cat to have. She’s sweet and gentle,
whereas Harley’s a holy terror. Bennett prefers to snuggle up and sleep on my chest while the hungry
one holds the rest of the house hostage in search of food.

Interesting, perhaps, but what do my cats have to do with object-oriented programming?

What I’ve done is identify two objects according to what they look like and how they act. How about
another rousing example?

I live in a city, so two more objects I deal with every day are the subway train and/or taxicab I take to
work. The subway train object is underground, about 200 feet long, and holds about 100 people in each
of its four sections. It is slow, noisy, and not very comfortable, but is relatively inexpensive to ride to
work. A taxicab, on the other hand, is about 12 feet long, runs above ground on four wheels, holds only
me and the driver, and is fast, quiet, and comfortable by comparison. Unfortunately, the cost of a taxi
ride to the office is about ten times that of the train.

Fascinating, huh? Well, not really, but the point is that I’m able to easily identify objects by their traits.
In object-oriented programming, the object is essential. It is the focus of the entire process, and the cause
for much confusion among procedural programmers. Procedural programmers are accustomed to writing
procedures that act upon data. They write functions that manipulate and produce data. They do not think
in terms of objects because they don’t need to. But in object-oriented programming, the object is at the
heart of everything.

file:///F|/books/java%20books/Java%20Bible/ch02/02-02.html (1 of 4)6/26/2005 7:54:40 PM


Java Bible:Object-Oriented Programming and Terminology

Object-oriented programmers look at the world in terms of objects. They see how objects look, how they
act, and how they interact with other objects. When developing software, they create entities in code
known as objects. These code objects contain traits, just as their real-world counterparts do.

As with real-life objects, programming objects contain details that list their characteristics. The object
Harley, for instance, could contain the following details:

• Black, short hair


• White crest on his chest
• Green eyes
• Four legs
• Seven toes per paw
• Always hungry
• Eats Whiskas Seaside Supper
• Sleeps on the bed
• Jumps from couch to table
• Scratches the curtains...

Clearly, this list could go on forever—the number of his whiskers, his length, shape, medical history,
and so on. What we have to do is abstract the data we think will be relevant.

Just as the preceding list enables us to identify the object Harley, software objects contain details that
define how they appear, what knowledge they contain, and how they behave. The purpose of software
objects is to combine data (regarding appearance and knowledge) and behavior into a nifty package, just
as objects in the real world do.

Software objects have special names for these traits: state and behavior. We will consider this
distinction in a moment, but let’s first turn to the need for abstraction.

Abstraction

“Everything essential and nothing more” is about the cleanest definition of abstraction I can think of.
Consider Harley. His essential functions are eating, sleeping, and creating chaos; everything else is
merely a detail that gets those functions done.

Humans are great at abstraction; as Figure 2-2 illustrates, it’s something we do naturally. When I hop in
the driver’s seat of my car, I don’t think about the power train, axle, tires, radiator, engine, fan belt, and
all the other things that make it possible for me to drive. Heck no, I think about the essential function of
the car—to get me from A to B—as I whip down the back streets and open roads of Boston.

Not having to consider the finer details of its inner workings enables me to concentrate on the tasks at

file:///F|/books/java%20books/Java%20Bible/ch02/02-02.html (2 of 4)6/26/2005 7:54:40 PM


Java Bible:Object-Oriented Programming and Terminology

hand—driving and keeping my eyes peeled for traffic cops. Abstraction enables me to focus on the
essential and ignore the nonessential. It frees me to think of the bigger picture.

Figure 2-2: Abstraction is part of human nature.

When creating software objects, we must apply this principle of abstraction. We must consider what the
essence of each object is and not think at all about the details of implementation or other elements that
distract from the process.

Even though we do it in the course of our everyday lives, abstraction can be difficult to do consciously if
we’re accustomed to thinking in terms of procedural programming. But without abstraction, our objects
will be stuffed full of data and behavior that doesn’t really belong there. Ideally, during the process of
abstraction, we don’t even consider implementation. We focus on the objects involved in solving a
problem and their relation to one another long before the details of coding become important. Indeed,
software objects enable us to more closely model problems, because problems are made up of either real
or conceptual objects.

We must first identify the essential functions of the object, and then select only the data relevant to those
functions. In Harley’s case, he has three distinct functions: eating, sleeping, and creating mayhem.
Accordingly, I can abstract details essential to those functions and reject the rest:

• Always hungry
• Eats Whiskas Seaside Supper
• Sleeps on the bed
• Jumps from couch to table
• Scratches the curtains

In this way, we can easily identify objects by their traits, as illustrated in Figure 2-3.

Figure 2-3: Identifying objects by their traits

file:///F|/books/java%20books/Java%20Bible/ch02/02-02.html (3 of 4)6/26/2005 7:54:40 PM


Java Bible:Object-Oriented Programming and Terminology

Combining state and behavior

A key concept of object-oriented programming is the capability to represent both data and the functions
that operate on that data in one software bundle known as an object. By placing all data and the
functions that operate on it inside a bundle of code, we create something unique. The data and functions
that make up a software object are known as state and behavior.

Looking at the essential details of Harley, for example, both state and behavior emerge. But it’s not just
Harley we need to consider; every object contains state and behavior:

• State is what the object knows or looks like. In the case of a cat object, the state is its fur color
and texture, eye color, breed, personality, and so on.
• Behavior, on the other hand, is how the object acts. Meowing, scratching, rubbing, begging for
food, and the like are examples of behavior.

Although an object’s state and behavior change over time, together they form the identity of that object,
as you can see in Figure 2-4.

Figure 2-4: Together, an object’s state and behavior identify it.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch02/02-02.html (4 of 4)6/26/2005 7:54:40 PM


file:///F|/books/java%20books/Java%20Bible/ch02/images/02-01.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-01.jpg6/26/2005 7:54:41 PM
Java Bible:Object-Oriented Programming and Terminology

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Objects contain only state and behavior that are appropriate for them. For instance, a cat object doesn’t
have any need to understand how much to charge for every mile it travels, as a taxicab object does. The
cat object contains only those things that apply to a cat, while the taxicab object contains only those
things that apply to a taxicab. They are self-contained.

Figure 2-5 shows a generic way to illustrate objects. This representation is intentionally amorphous—a
blob of information containing state on the inside surrounded by behavior. Although a number of
techniques are possible for illustrating objects, I chose this one because it is clean, simple, and easy to
understand. The idea is that state is hidden from the outside world, something only the object itself can
change. An object’s behavior, in fact, is the only thing that can alter that object’s state. In this sense,
state is protected.

Figure 2-5: State is hidden from the rest of the world; only the behavior of the object can change it.

For instance, if Harley is hungry, only when he eats will the feeling of hunger subside. Yes, his ability to
get food depends on other factors too, but in the final analysis, it’s his behavior that changes his state. If
he doesn’t eat, he’ll stay hungry. If he eats, the state of hunger is changed into a state of comfort. From
an OOP perspective, only Harley can change his state.

Variables and methods

In Java, an object’s state consists of variables, while behavior is implemented as functions called
methods (see Figure 26). The combination of variables and methods together maintains state and
behavior. The idea of variables and methods is nothing new, although you’re probably accustomed to
referring to functions rather than methods. The only thing new here is how the two are combined into a
single object.

file:///F|/books/java%20books/Java%20Bible/ch02/02-03.html (1 of 4)6/26/2005 7:54:41 PM


Java Bible:Object-Oriented Programming and Terminology

Procedural programmers are used to writing functions that sit out in the open, to be called upon
whenever needed, whereas object-oriented programmers embed those functions inside objects. Say, for
example, you were to write a procedural program in any language that modeled the behavior of Harley.
After you got over the shock of being asked to write a program simulating my cat, you’d probably start
by spending a few moments thinking about him.

You know he has fur and that it’s of a specific color. You also know he has four legs, each having a paw
with seven toes. (Some of you may think this is the mark of the devil, and after living with this little
monster for the past few years, so do I—but that’s another story.)

Figure 2-6: An object consists of variables and methods.

After thinking about it for a while, you’d realize that only some of the possible variables really apply to
the simulation. Variables such as hungry, thirsty, awake, asleep, and the like are more closely related to
Harley’s behavior than are the purely physical ones. You might write them down on a piece of paper or
type them into your computer.

In fact, you’d probably start coding right off the bat, perhaps beginning with the global variables that
apply to Harley. Maybe you’d combine them into a structure for the sake of convenience, maybe not.
You’d then consider the things in Harley’s life that affect this data. For instance, when he’s hungry, he
eats. After he eats, he becomes sleepy and eventually finds a warm spot to snooze while his food digests.
Upon waking, he has a burst of energy and burns up the food by running around the house, leaping from
chair to couch to kitchen table like a lunatic—at which point he becomes hungry again. Come to think of
it, that’s all Harley ever does....

In a procedural world, you would write a bunch of functions (the equivalent of object methods) that
could be called from anywhere as needed, including Eat(), Seep(), and GoCrazy(), each capable of altering
the global data or data passed in when called. In effect, you would be creating each procedure in
Harley’s life that applies to this simulation. In the end, you would have a bunch of data (either globals,
structures, or a combination of the two) and a bunch of functions. You’d also have an event loop of
some sort that runs continually, calling functions such as Eat() as specific events are encountered or when
conditions such as Hungry=TRUE trigger such actions.

In an object-oriented approach, we spend a whole lot less time writing code and a whole lot more time
defining the objects themselves. We think about Harley in terms of an object, attempting to model our
code after him as closely as possible. In this sense, he isn’t a collection of data and routines residing in

file:///F|/books/java%20books/Java%20Bible/ch02/02-03.html (2 of 4)6/26/2005 7:54:41 PM


Java Bible:Object-Oriented Programming and Terminology

different files. As Figure 2-7 demonstrates, we create an object containing all variables and methods
having to do with him.

Figure 2-7: We define the object’s variables and methods.

OOP is therefore unlike procedural programming, where data can be accessed and modified by any
function. Instead, data residing inside an object is surrounded by the methods of that object, protected
from direct manipulation.

In Java, methods consist of three parts:

• The name of the object to receive the message


• The name of the method to execute
• Optional parameters required by the method

In the case of my troublesome feline, the name of the object is

Harley

the name of the method to execute is

eat

and the parameter required by the method is

catfood

Taken all together, Harley’s method would be invoked as follows:

Harley.eat(catfood):

The preceding is known as dot notation, and it is similar to how a C programmer would access an
element in a struct. A period, or dot, is used to separate the object (appearing to the left) from the
method and any parameters it may require. Here, when the object Harley receives the message eat
catfood, his eat method is invoked with catfood as a parameter. In Java, as with other object-oriented

file:///F|/books/java%20books/Java%20Bible/ch02/02-03.html (3 of 4)6/26/2005 7:54:41 PM


Java Bible:Object-Oriented Programming and Terminology

languages, dot notation is the standard mechanism for executing methods inside objects.

As mentioned previously, only the methods of an object can change that object’s data. This powerful
concept is called encapsulation, and it is central to object-oriented programming.

Encapsulation (information hiding)

The idea of hiding data inside an object, making it unavailable to anything but that object’s methods, is
known as encapsulation (also called information hiding). Encapsulation extends to the implementation
of methods themselves, meaning that the details of an object’s inner workings are never available to
anything but the object itself.

Encapsulation is very powerful because it permits objects to operate completely independently of each
other as discrete, self-contained bundles of data and code. The only way to access information in an
object is through its methods; these form an interface (see the next section) that remains consistent to the
world outside of the object.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch02/02-03.html (4 of 4)6/26/2005 7:54:41 PM


file:///F|/books/java%20books/Java%20Bible/ch02/images/02-02.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-02.jpg6/26/2005 7:54:42 PM
file:///F|/books/java%20books/Java%20Bible/ch02/images/02-03.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-03.jpg6/26/2005 7:54:42 PM
file:///F|/books/java%20books/Java%20Bible/ch02/images/02-04.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-04.jpg6/26/2005 7:54:43 PM
Java Bible:Object-Oriented Programming and Terminology

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

But encapsulation doesn’t apply only to data; it also pertains to the implementation details of the
methods themselves, without concern for other objects (and frequently comes into play as such routines
are optimized, updated to fix bugs, or rewritten altogether). Because objects have an interface through
which they communicate, the underlying data and implementation details are hidden and protected.
Thanks to encapsulation, both data and implementation can change without breaking the system. In fact,
entire objects can be replaced with new objects, assuming the interface is the same.

Encapsulation prevents objects from becoming dependent on each other’s inner details, because
otherwise small changes could cause tremendous damage to the overall system. Bug fixes, code
optimization, and entire code rewrites are possible because of encapsulation.

Think of encapsulation in terms of your computer. When you upgrade the hard drive, RAM, or the CPU,
you don’t have to worry about how upgrading affects your ability to interact with your system. Sure, it
will have more storage capacity, be able to run more programs at the same time, and be faster; that’s
why you upgraded. But you don’t depend on the internals of your computer to interact with it. You can
swap these out as needed without disturbing other parts of the system and causing your computer to
come to a grinding halt. This is the power of encapsulation; the internal details of objects are hidden so
that their underlying implementation can change without breaking the system.

Encapsulation makes it possible for you to treat objects like discrete “black boxes.” Each object
performs a specific function, and you don’t have to be concerned about internal implementation.
Conceptually, information goes in one end of a black box and comes out the other. We don’t know or
care what’s going on inside; we only know what we can put into the box and what it will give back. You
can see this process in Figure 2-8.

Figure 2-8: Encapsulation enables objects to be treated like discrete “black boxes.”

We can string together any number of black boxes, each performing a specific task, to build as large and
complex a system as we need. And, thanks to encapsulation, we can even tinker with the internals of any
black box without crashing the works. Better yet, we can replace whole black boxes with better black
boxes as they are developed. The entire system is modular, much like the internals of the computer

file:///F|/books/java%20books/Java%20Bible/ch02/02-04.html (1 of 4)6/26/2005 7:54:44 PM


Java Bible:Object-Oriented Programming and Terminology

itself, as illustrated in Figure 2-9.

Figure 2-9: Encapsulation enables us to change and string together individual objects with a great deal
of freedom.

Interfaces

Software objects are complex on the inside, just as their real-world counterparts are. On the outside,
however, software objects are uncomplicated. They provide a simple interface to their data and behavior,
through which other objects can interact with them. Think for a moment of a television set. Inside, it’s a
mess of electrical components: a picture tube, one or more speakers, and all kinds of stuff I have no idea
how to deal with. But thanks to my remote control, I don’t need to know anything about the complex
innards to enjoy using it.

My remote control is the interface to my television, enabling me to communicate with it. l can turn it off
or on, change channels, turn the volume up or down, and even adjust the picture’s horizontal and vertical
holds, tint, and hue (fancy remote, huh?). With the remote control, which is itself an object (for which
the buttons are the interface), I am able to get functionality from my television without messing around
with the guts of the system.

Objects interact with each other through similar interfaces all the time. One object produces a response
in reaction to the messages it gets from another object. This is just like my cat. Opening a can of cat food
and putting it in front of Harley’s face triggers specific behavior. Objects send messages to each other,
setting off behavior, as shown in Figure 2-10. Using dot notation, as explained in the “Variables and
methods” section earlier in this chapter, a good deal of the Java code you write involves sending
messages to objects.

Figure 2-10: Objects trigger behavior between each other by sending messages.

Messages: Objects communicating with objects

With a software program full of objects, each only able to access and modify its own data through its
own methods, how does anything ever get done? After all, it does begin to sound as if we have a bunch
of well-defined entities that are very lonely in the world, capable of interacting only with themselves. A

file:///F|/books/java%20books/Java%20Bible/ch02/02-04.html (2 of 4)6/26/2005 7:54:44 PM


Java Bible:Object-Oriented Programming and Terminology

highly introspective, if not entirely isolated, group of software objects, yes?

No. Objects aren’t ships lost at sea, out of radio contact. They have the ability to send messages to each
other, thereby triggering the execution of methods inside each other, as Figure 2-11 demonstrates.

Figure 2-11: A message sent from one object to another triggers a method inside the target object.

Think of a microwave oven. In and of itself, your microwave doesn’t do much but sit there waiting to be
called into action. When you want to heat up some food, you put the food inside and close the door. You
then send the microwave a message, such as “Heat for two minutes at full power,” by pressing the
appropriate buttons on the front. Because you’re using the interface provided with the microwave—the
buttons on the front—your message is understood and carried out.

You must send messages in accordance with the interface of an object or your message won’t be
understood. For instance, you might try using your television’s remote control on the microwave and
send the message “Change to Channel 25 and turn up the volume,” but you’ll wait an awfully long time
before Homer Simpson appears!

In object-oriented programming, objects are constantly communicating with each other through a
complex web of messages, as illustrated in Figure 2-12. Not only are the messages sent by objects able
to trigger the execution of methods inside other objects, they can also contain parameters that those
methods require.

Figure 2-12: Objects weave a complex web of messages to communicate with each other.

Following our television analogy, sending the message “Change station to Channel 25” to the television
object might look something like this in Java code:

Television.changeStation(25);

The television object, Television, receives the message changeStation with 25 as a parameter. The period, or
dot, separating the object and message is intentional. In most object-oriented languages, as with Java, the
object receiving the message is on the left and the message is on the right. The dot sits between the
object and the message, with no spaces, and in effect says, “Send the message on my right to the object

file:///F|/books/java%20books/Java%20Bible/ch02/02-04.html (3 of 4)6/26/2005 7:54:44 PM


Java Bible:Object-Oriented Programming and Terminology

on my left.”

In our example, keep in mind that messages contain the name of the method to execute. When the object
Television receives a message such as the one illustrated, it looks inside itself for a method named
changeStation. If such a method exists, it is executed, with a value of 25 as the parameter.

The beautiful thing about messages is that they are generic, in the sense that any object can send a
message to any other object, even if they exist in different programs or on entirely different computer
systems. Objects existing on the Internet halfway around the world can send and receive messages to or
from any other objects over the Internet. This is the capability that makes distributed objects possible,
and you will see it more and more as software programs begin to “live” on networks.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch02/02-04.html (4 of 4)6/26/2005 7:54:44 PM


file:///F|/books/java%20books/Java%20Bible/ch02/images/02-05.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-05.jpg6/26/2005 7:54:44 PM
file:///F|/books/java%20books/Java%20Bible/ch02/images/02-06.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-06.jpg6/26/2005 7:54:44 PM
file:///F|/books/java%20books/Java%20Bible/ch02/images/02-07.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-07.jpg6/26/2005 7:54:45 PM
Java Bible:Object-Oriented Programming and Terminology

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Modularity

We have seen that objects contain both variables and methods, that they are encapsulated, and that they
can send messages to each other through interfaces. Because data and behavior are neatly packaged
inside objects, and because the only way to access data is through the interface defined by the methods,
you can change the internal workings of an object without breaking the rest of the system. The result is a
major benefit to the software developer: modularity.

Modularity is based on discrete programming objects, which you can change without affecting the
system as a whole, and it is greatly enhanced by encapsulation. You develop and maintain each object’s
source code independently of other objects, and the only way to access and change information inside an
object is through methods. This represents true code modularity.

Not only can you change the implementation details of an object without affecting any other part of the
system, but you can replace or rewrite entire objects from the ground up, as long as the interface doesn’t
change or inheritance isn’t abused in the method.

Think of it in terms of electrical wiring. Each wire in an electrical system is connected to the others in a
predefined way: It has an interface. These interfaces differ (wall sockets, adapters, surge protectors, and
so on), but each piece of wiring has one. Additionally, each wire is designed to fit perfectly within the
context of the system as a whole. It is created with a special purpose in mind, reflected in its length,
material, and type of interface.

When a wire breaks or begins to corrode and to perish, an electrician comes to the rescue. He or she
locates the piece of the system causing the problem and replaces it with another. No muss, no fuss.
Assuming our electrician has the wire needed, it’s replaced then and there. One wire is removed and
another put in its place. Because the interface for the wires is consistent, the process is simple and
painless.

Our electrician doesn’t have to worry about creating a wire from scratch; he or she can rely on one
having been created specifically for the job. This is the beauty of modularity, be it in electrical wiring or
software development: You can yank out one part and put in another without bringing down the whole
system (see Figure 2-13).

file:///F|/books/java%20books/Java%20Bible/ch02/02-05.html (1 of 4)6/26/2005 7:54:45 PM


Java Bible:Object-Oriented Programming and Terminology

Figure 2-13: An object-oriented software system is as modular as an electrical system in a house.

Classification

Classification, grouping things according to how they look and act, is another key concept in object-
oriented programming. In the real world, everything is classified. We put things into classes to help us
better understand and remember what their general properties are. Cadillacs are in the automobile class,
ferns are in the Filicales class, trout are in the Salmonidae class, and we are in the Homo sapiens class.

In object-oriented programming we classify things as well, specifically objects. We group them into
classes according to their characteristics. Classes and objects go hand in hand and are so similar that
programmers often use the two terms interchangeably. You’ll find a distinct difference between them,
however.

Classes are the blueprints, the source-code templates from which objects are created. You can see this in
Figure 2-14. These blueprints contain all of the programming code describing state and behavior. They
contain all the variables and methods an object will possess.

When we think of objects, we tend to think of conceptual entities that contain both state and behavior
and are able to communicate by way of messages. In fact, an object cannot exist without a class that first
defines the variables, methods, and interfaces that the object will have. Each and every object is created,
or instantiated, from a class.

It might help to think of objects and classes in terms of C structs and variables derived from those
structs. A struct defines a group of data types, from which a programmer can create any number of
variables (memory permitting, of course). For example, the following C struct defines a basic Point
structure:

struct Point {
int h; /* horizontal coordinate */
int v; /* vertical coordinate */
};

file:///F|/books/java%20books/Java%20Bible/ch02/02-05.html (2 of 4)6/26/2005 7:54:45 PM


Java Bible:Object-Oriented Programming and Terminology

This struct could be regarded as a class; it’s the template from which new Point variables are created:

Point myPt, anotherPoint, yetAnother; /* just making my Points!


*/

In this example, we’ve created three different variables, all having the same structure. We have, in
essence, created objects from a template. This is exactly the purpose that classes serve; they are
templates from which objects are created.

Figure 2-14: Classes are the code templates from which objects are created.

Classes, however, don’t just define data types. They also define methods, giving the object its behavior
and an interface through which that object communicates with other objects. In Java, a class definition
has the following form:

class name {
. . . instance variables . . .
. . . method declarations . . .
}

Although you can declare your methods first and the instance variables last, it’s good coding practice to
follow the preceding model. The Java keyword class begins the definition for a class. You provide the
class with a name (such as Point). The variables and methods of the class are enclosed in the curly braces
({}) that begin and end the class definition block.

Let’s take a look at the structure of Point, this time written as a Java class. The variables representing
horizontal and vertical would be the same, but we might also want to include a method for setting these
variables and one each for retrieving the value of these variables:

file:///F|/books/java%20books/Java%20Bible/ch02/02-05.html (3 of 4)6/26/2005 7:54:45 PM


Java Bible:Object-Oriented Programming and Terminology

class Point {
private int h; /* horizontal coordinate */
private int v; /* vertical coordinate */
public void setPoint (int newH, iht newV) {
h = newH;
v = newV;
}
public int getH() {
return (h);
}
public int getV() {
return (v);
}
}

Now, this certainly has a lot more meat than the C struct we created, and for good reason. The Point class
contains three methods: setPoint() to set the horizontal and vertical integer variables; getH() to retrieve the
horizontal variable; and getV() to retrieve the vertical variable. Fair enough, but what’s going on with the
keywords private and public?

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch02/02-05.html (4 of 4)6/26/2005 7:54:45 PM


file:///F|/books/java%20books/Java%20Bible/ch02/images/02-08.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-08.jpg6/26/2005 7:54:45 PM
file:///F|/books/java%20books/Java%20Bible/ch02/images/02-09.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-09.jpg (1 of 2)6/26/2005 7:54:46 PM


file:///F|/books/java%20books/Java%20Bible/ch02/images/02-09.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-09.jpg (2 of 2)6/26/2005 7:54:46 PM


file:///F|/books/java%20books/Java%20Bible/ch02/images/02-10.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-10.jpg6/26/2005 7:54:46 PM
file:///F|/books/java%20books/Java%20Bible/ch02/images/02-11.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-11.jpg6/26/2005 7:54:46 PM
file:///F|/books/java%20books/Java%20Bible/ch02/images/02-12.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-12.jpg (1 of 2)6/26/2005 7:54:47 PM


file:///F|/books/java%20books/Java%20Bible/ch02/images/02-12.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-12.jpg (2 of 2)6/26/2005 7:54:47 PM


Java Bible:Object-Oriented Programming and Terminology

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Private versus public

Remember that objects have the capability to encapsulate, or hide, their data. No need exists for other
objects to access the variables of a Point object directly, thus they are both declared as private when we
create our class. The only way to set or retrieve this data is through a Point object’s public methods,
which any other object can do by simply sending a message. Which leads me to the issue of
instantiation, the act of creating an object from a class.

Java provides four levels of access control: public, protected, private, and friendly. Each of
these is discussed in Chapter 7, “Getting Started: HelloWorld Application and HelloWorld
Applet,” and Chapter 13, “Classes, Interfaces, and Packages.”

Instantiation

Until we create an object from our new class, nothing is really going on. Before we can work with an
object, we must instantiate one:

Point myPt = new Point(); /* instantiate myPoint object */

The preceding line of code creates an object named myPt from the Point class we created earlier; in other
words, it creates an instance of the Point object. The new operator followed by Point() creates an object of
class Point in memory, to which the myPt variable now refers. The new Point() part is necessary because
the new operator is required to instantiate an object from a class. Following new is what’s known as a
constructor, a special method that initializes an object (gives value to it at the beginning of its lifetime).
The combination of the new operator and the Point() constructor effectively creates (in memory) and
initializes the object to which myPt now refers.

Now, let’s suppose we want to do something with the object we’ve just created. How about setting the
horizontal and vertical coordinates, and then, just for fun, we can retrieve and copy them into local
variables:

myPt.setPoint(145,124); /* set the h and v variables */

file:///F|/books/java%20books/Java%20Bible/ch02/02-06.html (1 of 4)6/26/2005 7:54:48 PM


Java Bible:Object-Oriented Programming and Terminology

int theHorizontal = myPt.getH(); /* get myPt h value, and assign


to a variable */
int theVertical = myPt.getV(); /* get myPt v value, and assign to
a variable */

So, what we have done in this set of examples should be pretty clear by now:

1. We created a class named Point, which had instance variables h and v and three methods: one
to set the variables; the other two to retrieve them.
2. We then instantiated an object, myPt, of class Point.

3. We set the instance variables of our new object, and then retrieved each and assigned it to a
local variable (theHorizontal was set to 145 while theVertical was set to 124).

Although this is a relatively simple example of creating and using a class in Java, it should help to put
the concepts of objects and classes into the proper perspective. Later in this book you’ll create much
more substantial classes, from which sophisticated objects will be brought to life. And thanks to another
powerful OOP concept, inheritance, you’ll be able to draw life from existing classes. If this sounds like a
trailer for the movie Dawn of the Living Dead, read on.

Inheritance

It’s time we got to the real meat of the matter of OOP: inheritance. Inheritance is arguably the most
powerful feature of any object-oriented language, as it makes it possible to reuse code as never before.

When we speak of classes and classification, we mean things that can be grouped together in accordance
with specific traits. Harley is a member of the Fells class, you and I are members of the Homo sapiens
class, and so on. But what’s the real advantage to classification in software programming?

Inheritance, my Homo sapiens friend.

Once a class has been created, the general, all-purpose state and behavior for ali objects to be derived
from that class are defined. For example, suppose I create a class called TimePiece.TimePiece is an
abstraction of the concept of keeping track of time. In it, I have a variable called Time (surprise,
surprise). I also have two methods, one to set the time (SetTime), and one to display it (Display Time).
These are set out in Figure 2-15.

file:///F|/books/java%20books/Java%20Bible/ch02/02-06.html (2 of 4)6/26/2005 7:54:48 PM


Java Bible:Object-Oriented Programming and Terminology

Figure 2-15: Class Time Piece, showing its variable and methods

This is all well and good, but what’s important to understand is that all objects I create using TimePiece
will have a Time variable and SetTime/DisplayTime methods. This means I can create a bunch of different
TimePiece objects, such as a wristwatch, alarm clock, or grandfather clock, and each inherits the traits of
the TimePiece class. This means I don’t have to write new methods for each type of clock I create, as
shown in Figure 2-16.

Figure 2-16: All objects of the class Time Piece inherit its variables and methods.

Suppose that I recognize the need for an alarm as well. I could add an alarm method to the TimePiece
class, and each new object created using TimePiece would then come with an alarm. Or, I could simply
use TimePiece as the basis for an entirely new class, which I’il call TimeAlarm Piece.

While this new class automatically inherits the variables and methods of TimePiece, I can add entirely
new variables and methods to it as I wish. Thanks to inheritance, I can create an entirely new subclass of
TimePiece that has all the traits of its superclass, plus whatever capabilities I add. You can see the
relationship between subclass and superclass in Figure 2-17.

Figure 2-17: Creating a subclass makes Time Piece a superclass.

Reusable code

This capability to reuse existing code to create new objects is a profound feature of OOP; the only new
code I have to write is that needed for the alarm. The TimePiece code comes for free; I’m reusing it to
create an entirely new class that understands alarms.

file:///F|/books/java%20books/Java%20Bible/ch02/02-06.html (3 of 4)6/26/2005 7:54:48 PM


Java Bible:Object-Oriented Programming and Terminology

The result is a dramatic increase in proficiency; the new class is up and running in a fraction of the time
it would take to write it from scratch. And, to further dramatize the power of inheritance, I can use the
new TimeAalarmPiece class to create any number of objects that require both time and an alarm. Any
object instantiated from the TimeAlarmPiece class automatically knows how to deal with both time and
alarms.

To add even more drama to the concept of inheritance, we’ll take it one step further and extend the
TimeAlarmPiece class to create an entirely new class capable of dealing with time, alarms, and
mathematical calculations. That’s right, we can create a subclass of the TimeAlarmPiece subclass and get
all the time and alarm traits for free. We need only add code to handle calculations, and voilà, we have a
class from which we can create a wristwatch that tells the time, sets and sounds an alarm, and calculates
the excessive cost of our electricity bill.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch02/02-06.html (4 of 4)6/26/2005 7:54:48 PM


file:///F|/books/java%20books/Java%20Bible/ch02/images/02-13.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-13.jpg (1 of 2)6/26/2005 7:54:48 PM


file:///F|/books/java%20books/Java%20Bible/ch02/images/02-13.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-13.jpg (2 of 2)6/26/2005 7:54:48 PM


file:///F|/books/java%20books/Java%20Bible/ch02/images/02-14.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-14.jpg (1 of 2)6/26/2005 7:54:49 PM


file:///F|/books/java%20books/Java%20Bible/ch02/images/02-14.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-14.jpg (2 of 2)6/26/2005 7:54:49 PM


Java Bible:Object-Oriented Programming and Terminology

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Class hierarchy/inheritance tree

As a class is extended through subclassing, the resulting objects become more and more specialized.

A class hierarchy, or inheritance tree, refers to the family of classes that result from the act of
subclassing. At the top level, the class is generic; it becomes more specialized as it goes down. A class
hierarchy often resembles the roots of a tree, with offshoots at many levels, as shown in Figure 2-18.

Warning!

Because object-oriented programming lends itself so beautifully to the concept of inheritance, things can
quickly grow out of control if you give subclasses to a class without considerable thought. It is very
difficult to determine precisely which aspects of state and behavior the class should have, and which
should be added only into subclasses.

Without foresight and proper design considerations, object-oriented systems can run rampant, like
multiplying bacteria in a warm petri dish. It’s for these reasons that the practice of object-oriented
analysis (OOA) and object-oriented design (OOD) have become as important to serious software
development as object-oriented programming itself.

Figure 2-18: A class hierarchy

Object-Oriented Analysis and Object-Oriented Design

file:///F|/books/java%20books/Java%20Bible/ch02/02-07.html (1 of 3)6/26/2005 7:54:50 PM


Java Bible:Object-Oriented Programming and Terminology

“In OOA, we seek to model the world by identifying the classes and objects that form the vocabulary of
the problem domain,’ and in OOD, we invent the abstractions and mechanisms that provide the
behavior that this model requires. “—Grady Booch

It is very easy to become entangled in object-oriented programming because of the technology’s flexible
nature. For this reason, professional software engineers such as Grady Booch and James Rumbaugh are
attempting to establish a standard way of applying object-oriented techniques to software development.

Object-oriented analysis (OOA) and object-oriented design (OOD) ensure that object-oriented
programming is done with foresight and in the best way possible for each problem we attempt to
resolve. Programming comes only after a thorough analysis of the problem and the careful design of a
solution.

Notation method

One aspect of OOA/OOD is having a notation method. A notation method provides a way for us to map
out a program on paper, whiteboard, or other media before committing it to code. It serves much the
same purpose as flowcharts do for procedural programming—it gives us a visual idea of how everything
works without the need for actual code.

Once we have decided how we want to subdivide our classes and objects (variables, methods, and
interfaces), a notation method lets us represent them and their often complex relationships with other
objects. The Booch Method is one popular notation method, although it is only one of many.

I won’t assert that you need to adopt object-oriented analysis and object-oriented design methodologies
in order to learn OOP. That’s simply not the case. In fact, you can begin programming in Java without
even learning object-oriented programming, if you really want to. But in reality, you’re much better off
learning about object-oriented analysis and object-oriented design while learning the language. You may
find them of no use to you at this point, or exceptionally helpful. It depends on what you want to do with
Java and how you plan to use the language. Either way, it’s worth checking out as you get deeper into
Java programming. A great place to learn more about object-oriented programming is at Ricardo Devis’s
Object-Oriented Page at http://www.well.com/user/ritchi/oo.html. It contains a number of links to sites
all over the Web that focus on object-oriented programming and methodologies.

Summary

Object-oriented programming (OOP) is the foundation of the Java programming language. You need to
understand the concepts of OOP before you jump into Java.

• OOP is based on a few key concepts: abstraction, states, behavior, variables, methods, and
encapsulation (information hiding).
• OOP uses object interfaces to communicate with the outside world.

file:///F|/books/java%20books/Java%20Bible/ch02/02-07.html (2 of 3)6/26/2005 7:54:50 PM


Java Bible:Object-Oriented Programming and Terminology

• Inheritance is one of the most powerful features of object-oriented programming—because it


enables you to reuse your code.
• Object-oriented programming is just the tip of the iceberg—object-oriented analysis (OOA)
and object-oriented design (OOD) techniques help you create and manage your object-oriented
development projects.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch02/02-07.html (3 of 3)6/26/2005 7:54:50 PM


file:///F|/books/java%20books/Java%20Bible/ch02/images/02-15.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-15.jpg (1 of 2)6/26/2005 7:54:50 PM


file:///F|/books/java%20books/Java%20Bible/ch02/images/02-15.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-15.jpg (2 of 2)6/26/2005 7:54:50 PM


file:///F|/books/java%20books/Java%20Bible/ch02/images/02-16.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-16.jpg6/26/2005 7:54:50 PM
file:///F|/books/java%20books/Java%20Bible/ch02/images/02-17.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-17.jpg6/26/2005 7:54:51 PM
Java Bible:Applet Design Basics

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

CHAPTER 3
Applet Design Basics
In This Chapter

Designing Java applications for the Web — applets

Designing applets and their interfaces

Integrating images and sound into your Java applets

Taking system considerations into account before coding your application

Accessing files and network resources from your applets

Managing your Java applet source code

Before diving in and writing your first Java applet, it’s important to first consider the design of applets.
By “design,” I not only mean the overall design — how it looks, what it does, how it interacts with the
webber, and so forth — but also the internal organization of the source code needed to create the applet
in the first place.

Although discussing design concepts before covering the language may seem akin to putting the cart
before the horse, in truth it’s not as off-the-wall as you might at first think. Since many programmers are
likely to be up and running with Java in no time, there’s no telling whether they’ll bother to read the
various chapters in this book before cranking out functional applets and putting them on the Web for the
world to see and use.

So, I’m discussing design issues here rather than at the end of the book, with the hope that if you take
the time to skim this chapter before reading on, much of it will sink in and stick with you along the way.
If you’re whipping out applets within 24 hours of picking up this book, as many experienced C and C++

file:///F|/books/java%20books/Java%20Bible/ch03/03-01.html (1 of 4)6/26/2005 7:54:51 PM


Java Bible:Applet Design Basics

programmers will be doing, be sure to consider the design guidelines presented here, even if you don’t
need to read every chapter that follows.

And, aside from the practical issue of catching you before you surf off into the sunset with Java and
browser in tow, there’s another reason for discussing design basics here: Because I won’t discuss
implementation details at all, I can paint an overall portrait — in broad strokes — of the things you’ll
learn by reading the rest of this book.

In the coming chapters, you’ll read in detail about the various features of the Java language and learn
how to create your own executable Web content. By covering each major topic in a separate chapter, I
hope to get right to the meat (artichoke heart, if you’re a vegetarian) of each feature. I’ve laid out the
book in a linear fashion, proceeding from topic to topic as you might encounter them were you to
explore the language on your own with little more than a vague idea of what it held in store.

If you didn’t get an overview in this chapter first, a significant and unreasonable burden would land
squarely on your shoulders: To understand each of the basic design issues before releasing an applet
upon our global village, you’d have to read the entire book from front to back!

To ease this burden, this chapter gives you a “sneak peek” at topics and issues well in advance of
actually exploring them. You’ll gain a better understanding of what applets can and cannot do, what they
should and shouldn’t do, and what you can expect as challenges to your programming prowess. By
taking the time here and now to consider applet design, you might save your forehead the pain of being
beaten against the keyboard out of frustration later on.

Get Started by Walking Away from the Computer

Today, with midnight hacking in vogue, sleepless nights at the keyboard an honorable living, and cutting
every conceivable corner to get products to market on schedule being the mantra of many software
companies, taking time to put ideas on paper may seem a bit old-fashioned. But no matter how you slice
it, sketching out your programs in advance will save you a great deal of time in the long run (see Figure
3-1).

And I’m not talking flowcharts here. I am merely suggesting that the time you take to step away from
the keyboard and place your ideas on that flat white stuff you had consigned to the garbage can of
history will more than pay for itself when it comes to implementation. If you’re an experienced
programmer, chances are you already follow a design process for projects before even beginning to
code. And if you’re new to programming, it’s a good habit to get into.

Since Java is an object-oriented programming (OOP) language, your programs will consist of objects
that interact with each other. As you learned in Chapter 2, objects can be easily represented on paper as
“amorphous blobs that do something.”

file:///F|/books/java%20books/Java%20Bible/ch03/03-01.html (2 of 4)6/26/2005 7:54:51 PM


Java Bible:Applet Design Basics

By taking the time to work out the “blobs” and how they interact with one another on paper, you’ll save
yourself a good deal of wasted implementation effort. Much like the master artist who sketches
renditions of a masterpiece before — and even during its creation — you’ll have an opportunity to refine
your programs on an abstract level before committing to a single line of code.

Figure 3-1: Taking the time to sketch out the design of your applet and the relationships of its objects
can save time down the road.

Once you begin to code, you’re essentially strapping yourself into a straitjacket; your initial attempt may
not turn out to be the best solution after all, and it might even strangle your good intentions in the end.
Without sketching the program in advance, you’ll barrel ahead and almost certainly make a mess of the
code, since you won’t give adequate time to considering the various classes you’ll be coding and the
objects they give birth to. Certainly, the most simple of programs won’t be an issue, but try and
implement larger applets off the cuff, and you’ll find yourself looking at a mighty unattractive spaghetti
dinner of code, when all is said and done.

Sketching a user interface

Aside from sketching your applet objects and their relationship with each other, it’s also crucial to put
on paper the user interface (UI) your applet will require. Notice I didn’t say graphical user interface
(GUI), which tends to be limited to windowing elements (buttons, scroll bars, windows, dialogs, and the
like). Instead, I’m referring to the interface at large: Precisely what will the webber experience when he
or she encounters your applet?

This is all-encompassing, and not limited to windowing elements. Everything a person will see or hear
when using your applet is part of the UI. And yes, I do mean hear. Since applets can play sound with as
little as one line of code, you must consider what audio yours will support (if any) and how that fits in
with the rest of the program.

Again, there’s no need to whip out a slide rule and sweat out the exact details. You need only sketch the
UI your applet will support to get a better idea of how it will look and sound to those who use it. Rather
than waste time coding elements that you might later reorganize or omit altogether, you should work
through the UI of an applet before committing to a single line of code.

As a general rule, I prefer to sketch the UI before anything else is done. Typically, I let an idea for a
program rattle around for a while, thinking through the details of what it should look like and how it
should act. Once I’ve roughed it out in my head for a few days, or longer, I then begin to sketch out the
user interface.

file:///F|/books/java%20books/Java%20Bible/ch03/03-01.html (3 of 4)6/26/2005 7:54:51 PM


Java Bible:Applet Design Basics

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch03/03-01.html (4 of 4)6/26/2005 7:54:51 PM


file:///F|/books/java%20books/Java%20Bible/ch02/images/02-18.jpg

file:///F|/books/java%20books/Java%20Bible/ch02/images/02-18.jpg6/26/2005 7:54:52 PM
Java Bible:Applet Design Basics

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Invariably, I discover things I’ve left out or want to drop that I would never have noticed in a purely
mental design. If you go straight to code relying only on loosely organized thoughts, you will likely start
in the wrong direction and waste a great deal of time. Instead, it pays to take the UI ideas you’re
considering out of your mind and place them on paper. Once there, you can tweak, massage, and rework
them as much as necessary, since this is an iterative process (and one that you might spend a lot of time
with if you’re anything like me).

Once I’m satisfied with the UI, I sketch out the various objects the program needs. This may take several
attempts or be a quick and surprisingly easy process. Whatever the case, before I begin so much as a line
of code, I know a great deal about what my program will ultimately look like and what code I have to
write to get it there.

Contrast this approach with diving into code head-first like a manic surfer on the beach at Maui who
can’t wait to get into the water (which, I admit, I sometimes do when overcome with excitement for a
particular project). Despite my best efforts and the most honest intentions, I’m almost never satisfied
with programs I develop in this manner, and I often spend a great deal of time trying to get them right.
The code may look and act as it’s supposed to on the surface, but under the covers is another matter
altogether.

The programs you create without taking the time to think things through will be much less elegant, and
even downright ugly, when compared to their well-considered counterparts. Worse still, they’re typically
inflexible and much more difficult to maintain than they should be. Except in cases where the program is
a “one-off” effort (made for a special purpose that won’t require an upgrade, and won’t find itself in the
hands of customers), you’ll eventually need to rewrite most, if not all, of the code to bring it up to snuff.

Unless you’re writing such disposable programs, do yourself a tremendous favor and spend the
necessary “up-front” time placing your ideas on paper and working through the overall design of your
projects before committing to code. You won’t be sorry.

Giving the Webber Control

When designing your applets, it’s a good idea to remember that every person who encounters them will
have a different opinion about what is and isn’t cool. Although a thumping background soundtrack and

file:///F|/books/java%20books/Java%20Bible/ch03/03-02.html (1 of 3)6/26/2005 7:54:52 PM


Java Bible:Applet Design Basics

spinning disco balls on a Web page may seem like the ultimate multimedia experience to you, not
everyone will agree.

Whenever you choose to add nifty features such as looping soundtracks (audio that plays continuously
by starting over when the end is reached), loud sounds, and animation, you need to give users a way to
turn off the ones they don’t like. For example, the webber might turn off an animation by clicking it,
stop a looping soundtrack by clicking a button, or mute all audio sources at once by clicking another
button.

Exactly how you give the user control is your business. Sometimes buttons aren’t possible, and so you
might consider a less obvious interface element, such as a check box or simply a mouse click. However
you do it, give visitors a choice and let them know how to control the various elements of your applet.
After all, webbers aren’t likely to come back if they’re annoyed by your creative use of Java.

Mouse control

There are two aspects to consider with regard to the mouse control: single or double clicks, and single or
multiple buttons.

Single clicks

For most applets, the mouse is the primary control mechanism. You can easily determine if it has been
clicked, released, moved, or even been clicked and dragged without first being released. In contrast, you
can’t easily determine if a double-click has occurred.

Java doesn’t support double-clicking, so you’ll have to write your own code to calculate the time
between each click and determine if such an event has occurred. Although writing such code isn’t
difficult, it’s a bad idea. The Web is, by design, a single-click navigation system. Not only will use of
double-clicking confuse the webber, but it breaks with the tradition of the Web.

As a result, you should design your applet around single clicks, and unless it’s absolutely necessary,
eliminate double clicks altogether.

If you must have support for double clicks in your applet, look in the JavaWorld Topical Index
in the JavaWorld archive provided on the accompanying CD-ROM, under Tips and Tricks.
There you’ll find information in double-click support.

Single button

Java originally supported only a one-button mouse. Since JDK 1.1, Java has supported up to three mouse
buttons, enabling more sophisticated mouse control. This might sound like a good feature to add to your

file:///F|/books/java%20books/Java%20Bible/ch03/03-02.html (2 of 3)6/26/2005 7:54:52 PM


Java Bible:Applet Design Basics

Java programs, but you’ll find it’s not always a good idea.

If you design your applet to understand and respond to specific mouse buttons, you’ll be cutting a large
population of Web users out of the loop. Instead, use the keyboard to modify a mouse click. For
example, when the mouse is clicked and no keys are pressed, treat it as a standard mouse event. When
the mouse is clicked and the Shift key is pressed, treat it as you would a special mouse button. Of
course, you’re not limited to the Shift key when it comes to modifying mouse clicks, but there are a few
things you should be aware of when incorporating keyboard control into your applet.

Keyboard control

Because Java doesn’t allow you to write applets that support a multibutton mouse, you may rely on the
keyboard to signal special webber input. In this way, you can react to different combinations of
keyboard and mouse down events.

When using the keyboard to modify a mouse click, it’s a good idea to limit the keys you support to the
Shift and Ctrl keys. These are available on almost every personal computer, and are used by standard
software programs to modify mouse clicks. The concept of Shift-clicking or Ctrl-clicking is familiar to
the majority of personal computer users, and these keyboard-mouse combinations can make your applet
easier to use.

Avoid obtuse keyboard modifiers, and only use those that might help the webber remember what key to
press when clicking the mouse. Suppose, for example, that you write a video game that uses the mouse
to control a submarine. Clicking the mouse alone might launch a torpedo, while clicking the mouse
while holding down the P key might activate the periscope.

Stop when stopped!

When a Web page is accessed with a Java-savvy browser, ali applets embedded in that page are told to
“start.” At this point, applets load the sounds and graphics they need (if any) and do their stuff.

When the Web page is left, either by the webber navigating to another page or the browser being quit
altogether, all applets in the page are told to “stop.” It is here that you’ll bring your applet activity to a
screeching halt. However, this process isn’t handled for you automatically.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch03/03-02.html (3 of 3)6/26/2005 7:54:52 PM


file:///F|/books/java%20books/Java%20Bible/ch03/images/03-01.jpg

file:///F|/books/java%20books/Java%20Bible/ch03/images/03-01.jpg6/26/2005 7:55:47 PM
Java Bible:Applet Design Basics

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

The programmer is responsible for stopping any sounds that are currently playing, for bringing
animation to a standstill, and halting all threads in their applet. Rarely, if ever, does an applet have a
good reason to continue along its merry way when the page it is embedded in has been exited. By
ceasing all activity upon receiving the “stop” message, your applets become well-behaved and courteous
inhabitants of the Web pages in which they are embedded.

Flexibility through applet parameters

If you’ve looked at the HTML code many applets are embedded in, you may have noticed the word
PARAM used inside the <APPLET> tag. The PARAM attribute lets applets receive data through HTML
code, which allows Web page authors to configure applets for their specific needs without actually
dealing with Java code (that’s our job!).

Applets that utilize parameters are much more flexible than those that don’t. Instead of creating several
slightly different versions of the same applet, you can use the PARAM attribute to customize a single
applet. By responding to parameters embedded in the HTML code, an applet can behave uniquely in
different pages.

Bandwidth Considerations

Because Java makes creating Web pages with sophisticated animation and sounds a snap, those new to
the language often tend to lose themselves in the excitement. Iceberg-sized images and audio clips
abound on the high seas of the Web. And while this may be just fine for the developer who has access to
the Web via a T1 line or cable connection, the equivalent of an ocean liner, the rest of the world isn’t so
fortunate; creaky wooden rafts and pontoon boats are the norm.

Since bandwidth is a major issue with the majority of webbers, you must consider the lowest-common
denominator. Although you might try to convince yourself that 28.8 Kbps is the norm, with ISDN and
cable modem access not far behind, many folks today surf the Web at speeds of 14.4 Kbps or less. Sure,
the technophiles are working with all the latest gadgets, but the masses . . . well, that’s a completely
different story. To offer your applets to everyone without penalizing those with slower access takes extra
effort and means you should assume the average access speed is no higher than 28.8 Kbps, with a large
percentage of folks on the Web still dog-paddling along at 14.4 Kbps and even 9600 bps!

file:///F|/books/java%20books/Java%20Bible/ch03/03-03.html (1 of 3)6/26/2005 7:55:47 PM


Java Bible:Applet Design Basics

Battling bandwidth bottlenecks

Although applets themselves are quite small, and come across the wire in no time, the graphics and
audio files they often utilize are tremendous by comparison. To prevent serious bottlenecks when
downloading these files over the network, there are several things you can do to decrease transmission
time.

Sound files

Java only supports Sun’s .au format for sound files, which uses µLaw (pronounced mu-law) encoding.
Thus, if you intend to use sound files, you’ll have to convert your existing audio files to this 8-bit, 8kHz,
single-channel (mono) format.

Sun users can create sounds in the .au format using the audiotool application. Windows users
can use the GoldWave utility supplied on the CD-ROM that comes with this book to create
and export sounds in this format.

Although the .au format creates files that are smaller in size than other formats, the sound quality isn’t
the best. As a result, you may find yourself fiddling with various sound editing functions in an attempt to
eliminate the hiss you’ll hear when converting higher-quality sounds to this format.

In order to reduce the size of sound files as much as possible, you’ll only want to keep the absolutely
essential portions of it around. Cut out any preceding or trailing silence, although you may be tempted to
keep it.

Since cutting out every second of preceding and trailing silences tends to make sounds begin and end
abruptly, many programmers figure keeping a second or two of “dead space” on either end of the sound
clip is worth the extra download time. However, you can achieve the same results by applying a “fade
in” effect to the beginning of the sound, and a “fade out” effect at the end. These two effects give nice,
smooth transitions instead of abrupt starts and stops. Not only is the sound more professional and
appealing, but you’ll trim off a bit of the download time in the process.

Sound loops

Sound is such an effective way to grab attention and add impact to an applet that many first-timers
overuse it. Rather than playing a large number of audio clips, consider whether looping would be a
reasonable alternative. When you loop a sound file, it will repeat itself continuously until you tell it to
stop.

The result can be quite powerful, especially if the sound clip you loop is subtle. Instead of bombarding

file:///F|/books/java%20books/Java%20Bible/ch03/03-03.html (2 of 3)6/26/2005 7:55:47 PM


Java Bible:Applet Design Basics

the visitor with sound after sound, sucking up valuable network bandwidth in the process, consider this
option. You’ll be happy to know that you can play any number of sounds at once, meaning you don’t
have to stop a sound loop in order to play another sound clip. All sounds you play at the same time will
be mixed together, allowing for a rich audio production with minimal effort on your part.

In order to accommodate the demands of media-hungry developers, JavaSoft has announced


an “extension” to the core Java API, and it should be available for download by the time you
read this. The Media API, discussed in more detail in Chapter 30, gives applets and
applications much more capability in terms of the sounds and images they may use. However,
the Media API isn’t built into the core Java API at the moment; it’s a separate library of Java
classes that you can’t guarantee will be available on every user’s system. Refer to Chapter 30
for more details regarding the Media API and other forthcoming APIs that will extend the core
capabilities of Java.

Images and colors

Java supports the use of GIF (graphics interchange format) and JPEG (Joint Photographic Experts
Group) images, meaning that it gives you a nice and easy mechanism for retrieving these images from
the Web and displaying them in your applet. Java also supports a 24-bit color model, which allows the
programmer to define and use more than 16 million different colors for use in drawing primitive
graphics (lines, rectangles, ovals, polygons, and so forth) and fonts.

Although the use of color applied to primitive graphics doesn’t negatively affect bandwidth, images do.
Since the JPEG format is supported, you can utilize 24-bit color images within your applets. With GIF
you’re currently limited to a palette of 256 colors. This is a limitation of the GIF file format, not Java,
although 24-bit GIF files will soon be possible through an enhancement of this popular type of graphic.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch03/03-03.html (3 of 3)6/26/2005 7:55:47 PM


Java Bible:Applet Design Basics

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Image palette reduction

Regardless of which format you use, graphic images suck up bandwidth. To reduce the amount of time it
takes an image to travel across the wire, you must cut down the amount of data used to represent it.
Luckily, the most popular graphics programs on the market (Adobe Photoshop, CorelDraw!, Fractal
Design Painter, and others such as the Paint Shop Pro shareware program) allow us to cut file sizes by
reducing the amount of colors used to display an image.

Rather than using a full palette of 256 colors, you may find that only a small number are necessary to
represent the image. By removing unused colors from the palette, you conserve storage space and
decrease download times. And you can further reduce the palette by forcing colors close to one another
to map to a certain value. For example, rather than having 16 different shades of gray in an image, you
might reduce the palette to support only three shades. This technique applies to all colors, meaning you
can reduce the entire palette of an image to significantly reduce its size.

Certainly, there is a trade-off between the quality of the image and overall storage size. However, you
(or the graphic artist responsible for Web artwork at your site) can typically reduce the palette
considerably without adversely affecting the image quality (see Figures 3-2 and 3-3).

Figure 3-2: Reducing the palette of colors can significantly reduce the storage size of an image. This
image contains several hundred colors, and requires 200KB of disk space.

file:///F|/books/java%20books/Java%20Bible/ch03/03-04.html (1 of 4)6/26/2005 7:55:48 PM


Java Bible:Applet Design Basics

Figure 3-3: After palette reduction, this image contains only 40 colors and takes up less than 100KB of
disk space. Can you tell the difference?

GIF versus JPEG

When using images, you’ll eventually need to decide upon a format to support. Java supports both
CompuServe GIF and JPEG formats in your applets, but there are a number of factors that may make
one preferable over the other. Start by taking a look at the GIF format.

You’ll find several benefits with GIF images. For starters, every graphics-based Web browser supports
inline GIF images; webbers won’t need an external helper application to view them. In addition, the GIF
format is highly efficient and has built-in compression that produces relatively small file sizes for
images that lend itself to this format. Finally, GIF images support transparency and interlacing, which
can greatly enhance the visual appeal of your applet.

JPEG images, on the other hand, can contain more than 256 colors, and can be compressed to a higher
degree than GIF when a large number of colors are involved. The JPEG format currently doesn’t support
transparency or interlacing.

Transparency

Transparency allows the graphic artist to specify any color in an image as “transparent.” When the
image is rendered on the screen, this color isn’t shown. Instead, whatever is underneath it shows through
(typically the background color, although other images may be drawn underneath, as well).

Without transparency, images are displayed using all colors in the palette, including the background
color of the image. As a result, they may appear quite unattractive under certain circumstances — unless
the color of these portions matches exactly the underlying background (see Figure 34). Therefore, the
GIF format is the only choice for images that must have a “see-through” portion.

file:///F|/books/java%20books/Java%20Bible/ch03/03-04.html (2 of 4)6/26/2005 7:55:48 PM


Java Bible:Applet Design Basics

Figure 3-4: Transparency allows us to specify a color in an image as “see-through.” The image at the
top of this figure uses transparency to appear as a natural part of this page, while the one underneath it
does not.

Interlacing

Interlacing, another feature supported by the GIF format, allows images to be incrementally drawn on
the screen as they come across the wire. Rather than appearing only after the entire image is transmitted,
interlaced images appear on the screen a little at a time as they are transmitted over the network.

The effect is similar to watching a Polaroid photograph develop before your eyes; you have an idea of
what the image is before it is completely downloaded, and see it materialize on the page over time. If
you give webbers something to watch as the image becomes clearer, they aren’t as likely to abort the
process and go elsewhere. Instead, many will stick around and watch these images appear.

GIF and JPEG: the bottom line

Since the GIF format supports both transparency and interlacing, in addition to being the default format
for Web graphics, you’ll more often than not find it a better choice for your applets than JPEG.

However, GIF images are currently limited to 256 (8-bit) colors. The JPEG format, on the other hand,
supports over 16 million (24-bit) different colors. In cases where you absolutely must have more than
256 colors in an image, you’ll have to use the JPEG format.

JPEG images are compressed using a lossy compression algorithm, allowing you to specify a trade-off
between image quality and storage size. When you use high levels of compression, these images lose
information (hence the term lossy). Future versions of the JPEG format may include support for
transparency and interlacing, although at the moment neither are available.

A new version of the JPEG format, called JPEG Progressive Download (fondly known as “Progressive
JPEG”), is similar in nature to an interlaced GIF. As these images come across the wire, they are
displayed incrementally. At first they look blurry, but become sharper and more defined as the image
data is downloaded, until finally the entire image is clearly visible. Unfortunately, this new JPEG format
is not yet supported by Java. However, future versions of Java are expected to support it.

file:///F|/books/java%20books/Java%20Bible/ch03/03-04.html (3 of 4)6/26/2005 7:55:48 PM


Java Bible:Applet Design Basics

Although you might think the choice of formats is clear — use GIF in most situations and turn to JPEG
only when you need more than 256 colors — you ought to take into consideration that some releases of
Java for Windows dither ALL graphics to 256 colors before displaying them! This is because supporting
more than 256 colors on Windows-based machines proved too time consuming for the first release of the
Java Developer’s Kit (JDK). So, even if you use JPEG images, their beauty will be lost on webbers who
have Windows systems, until the JDK is updated.

If you can do it, you’re better off using GIF images. Since a large number of webbers won’t be able to
see the difference anyway, there’s no sense wasting bandwidth with high-resolution JPEG images,
unless you have no choice.

As a general rule of thumb, you should keep the total amount of material that has to download for each
Web page (text, graphics, sound files, and so on) under 250K. If you have a large number of graphics
and are above 250K in total Web page material, you should consider using the JPEG format, simply to
gain the highest degree of compression possible. Since images with more than 100 colors tend to
compress more efficiently in the JPEG format than they do with GIF, first target images with the most
colors for JPEG compression.

If you still have too much data to download, consider reducing the overall amount of material on the
page. You can also reduce the dimensions of the images, cropping out excess material altogether. And,
of course, you can always use the JPEG format with the highest degree of compression for all your
images. Just be aware that you’ll lose both the transparency and interlacing features available with the
GIF format.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch03/03-04.html (4 of 4)6/26/2005 7:55:48 PM


Java Bible:Applet Design Basics

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Finally, there is the user’s equipment to consider. The majority of webbers can’t see more than 256
colors on their screen anyway. In fact, a large number of systems connected to the Web can’t even
display that many. For some, the upper limit is 16 colors or less!

Although I wouldn’t spend a great deal of time attempting to accommodate systems at the lowest end, I
highly recommend that you assume the majority of webbers can only see up to 256. And so, the choice
between JPEG and GIF becomes even easier.

Webber System Considerations

In addition to considering bandwidth, you must also consider the variety of systems your applets will run
on once they become available to a global population. Just as most webbers lack ultrafast connections to
the Web, they’re often surfing with systems that are remarkably less powerful than those we use to
develop applets. As a result, you must develop applets to run on a wide variety of systems, from entry-
level boxes to silicon-heavy hot rods.

In addition to raw computing horsepower, you must also consider the wide range of video displays your
applets will be viewed on. In short, you must design your applets to run on just about every system out
there, or risk alienating those whose systems aren’t up to your personal standards. This means
eliminating excessive processing and media consumed by your applets, and streamlining them in ways
that you might not consider necessary based on your own computer setup.

To do this, you have to think in terms of absolute efficiency from the get-go, cutting out every
unnecessary bit and byte of code and media (sounds and images) possible, and testing the results as you
go along on a variety of low-end computer systems.

Images and colors

When using colors for rendering primitive graphics (such as lines, rectangles, ovals, and polygons), stick
to the predefined colors supplied by Java. Although you can define your own colors, with over 16
million options, it’s a bad idea to assume the webber will ever see them. Because most webbers only
have 256 colors on their systems, and some only 16, a color you define will usually be converted to the

file:///F|/books/java%20books/Java%20Bible/ch03/03-05.html (1 of 3)6/26/2005 7:55:48 PM


Java Bible:Applet Design Basics

closest match or dithered down to accommodate their less capable monitors. Your efforts will be lost on
all but those who happen to use systems like yours. To be safe, use the built-in colors and only define
others when absolutely necessary.

Color matching

To complicate matters, you can’t guarantee that an image or color will be consistent across multiple
platforms. Colors on a Windows machine won’t necessarily look the same as those on a Sun machine,
and will look different once again on a Macintosh. As more platforms become Java-savvy, the disparity
will grow.

To combat this problem, stick to minimal palettes and built-in colors. Don’t spend too much time trying
to get an image or color “just right” until you’ve had a chance to view it on a variety of platforms. The
time you spend tweaking an image or color may well be wasted, since few webbers will have exactly the
same system and display setup as you.

Instead, go for attractive and clean images. Avoid subtle hue shifts, fine lines in special colors, custom
palettes, and the like. Before you spend too much time refining an image or creating custom colors for
your primitives, take a look at it from a different perspective: Put what you have on the Web, and view it
with as many different systems and browsers as possible. If you don’t have access to a particular
platform, ask a friend who does to give his or her opinion. The earlier in the development process you do
this, the better off you’ll be.

Animation

The most eye-catching thing an applet can do is animate images and graphics. When things move around
the screen, you can’t help but look at them. Unfortunately, you must also be aware of the diversity of
systems your animations will be run on.

Animation takes horsepower, and if you’ve spent time honing an animation to look ideal on your
system, you can guarantee it won’t appear that way to everyone else. What happens when an animation
created on a high-end workstation is run on an entry-level personal computer? Digital roadkill, that’s
what.

In such cases, the animation may be considerably slower than you’d expect. As a result, it loses its
appeal to those with less capable systems; low-end webbers won’t find it nearly as fascinating or slick as
those using high-performance systems.

Interestingly enough, the exact opposite can happen when an animation is developed specifically for low-
end systems. The developer might have spent considerable time and effort making the animation as fast
as possible on a low-end development system, but when it’s executed on a much faster machine it runs
the risk of being so fast that it can’t be appreciated — or even seen!

file:///F|/books/java%20books/Java%20Bible/ch03/03-05.html (2 of 3)6/26/2005 7:55:48 PM


Java Bible:Applet Design Basics

To reduce the risk on both fronts, you must assume that your applets will be run on a wide range of
systems. Some will be blazing fast, perhaps souped up with multiple processors, while others will be
painfully slow by comparison.

Don’t despair! There’s no need to throw yourself over the nearest cliff. Just hang on for a few more
minutes; as you’ll soon see, there are a few things you can do to create animations that execute smoothly
in all cases.

Frame rate support

First, always assume your applets will run on machines that are considerably faster than yours. Although
you may have a top-of-the-line system today, tomorrow it will be old news. In particular, if you are to
prepare for tomorrow’s fastest machines, you need to exercise control over how fast the individual
frames in an animation are drawn. Although you might think that no delay between frames is ideal,
nothing could be further from the truth.

With no delay between frames, the animation will run at breakneck speed. It might seem perfect on your
machine, but on faster computers it may become a blur roughly equivalent to the Hale-Bopp Comet seen
through the windshield of a moving car on a foggy night. Inserting a delay between each frame,
however, gives our eyes a moment to actually see the various stages of animation; you effectively apply
the breaks a wee bit between frames, giving our feeble eyeballs just enough time to focus on the current
frame before advancing to the next one in the series.

Unfortunately, a problem arises when you control the frame rate with only faster systems in mind.
Suppose, for example, that you’ve inserted a half-second delay between every frame in an animation.
This is fine when running on fast machines, preventing blur, but when run on low-end systems, it could
be a tremendous detriment to the animation.

The problem is that on slower machines, the frame rate is already slow enough for the frames to be
painfully visible, so why add another half-second delay? In practice, you might need to eliminate the
artificial delay altogether to compensate for this.

Rather than inserting a delay between every frame, you need only ensure that a specific amount of time
has passed between the previous frame and the one about to be drawn. If the machine is incredibly fast,
you’ll want to delay the process a bit, but if the machine is incredibly slow, you’ll want to draw the next
frame as quickly as possible.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch03/03-05.html (3 of 3)6/26/2005 7:55:48 PM


Java Bible:Applet Design Basics

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Although this may sound like a lot of work, you’ll be happy to know that it’s pretty easy to do. You
simply enter a loop that does nothing but check to see if it’s time to draw, and exit the loop when enough
time has passed between the last frame being drawn and the current one. Following is pseudo-code (not
the real McCoy, merely a rough idea having no direct relationship to a specific programming language)
for just such a timing device, which would take place just before each frame is drawn:

while (timepassed < framerate) {


update timepassed variable
. . . do nothing else but loop while waiting . . .
}
. . . draw the current frame . . .
timepassed = 0; // reset timer

Reduce overhead

The technique of controlling frame rate should only be coupled with a serious effort to reduce any
overhead that might occur within your animations. The easiest way to do this when animating a series of
images is to reduce the storage size of each image, as discussed in “Bandwidth Considerations” earlier in
this chapter.

If the images in an animation are massive in size, low-end machines will barely be able to keep up with
it. Likewise, low-end machines might not be up to the task if the calculations required to derive the next
frame in a computer-generated animation (in other words, not animating a series of images, but
generating each frame on the fly) require a great degree of computational power. Although high-end
systems won’t have a problem keeping up with each frame of the animation, and may even require an
artificial delay between each, many low-end systems will be left in the dust.

In order to allow low-end machines in on the fun, it’s a good idea to streamline all parts of your
animations. When animating images, you can reduce the storage size of each one by reducing the color
palettes, as described earlier, and by restricting the overall dimensions of each image. When generating
animation frames on the fly, you should give considerable attention to making the frame generation
algorithm as tight and efficient as possible. And in both cases, you should use threads to prevent
processing bottlenecks from monopolizing the central processing unit (CPU).

file:///F|/books/java%20books/Java%20Bible/ch03/03-06.html (1 of 3)6/26/2005 7:55:49 PM


Java Bible:Applet Design Basics

Threads are a powerful, complex feature of many modern operating systems, and Java allows
us to tap into them with relative ease. Threads give us the capability to run many different
tasks concurrently, without forcing us to keep track of the state of each task (that is, we can set
up threaded objects that run independent of our main program, without our having to write
terribly complicated code to manage everything that’s going on). For details on using threads
in your Java programs, see Chapter 14.

To further reduce overhead, you can decrease the download time of individual images used in an
animation by placing all of them in one image file. If you do this, the user downloads a single
“animation strip” containing all of the images instead of a number of different images, each of which
requires a separate HTTP network connection. The images are transmitted across the wire more
efficiently and without the overhead of multiple connections. To use this method, you draw the
appropriate portion of the animation strip on the screen rather than drawing a number of different images
one after another. And instead of loading each individual image into memory, the single file is loaded
into memory.

Processing bottlenecks

Depending on what your applets do, they may or may not suck up a considerable amount of system
resources. For those that are computationally intensive or manage a large number of images, it’s
important to reduce potential bottlenecks. Any time one task blocks others, such as when your applet
uses input/output streams or performs complex computations, you should implement the tasks as
threads.

Threads are dealt with fully in Chapter 14, but suffice it to say here that they allow multiple tasks to
occur at once when multiple central processing units (CPUs) are available, or are so interwoven with one
another that they appear to be happening at the same time even on systems that have only one processor.
And, since a time-consuming task running in a thread can yield to other threads, you can eliminate
processing bottlenecks; each task gets a crack at the CPU without requiring the current task to be
completed in entirety.

“Processing . . . please wait”

At times when your applet is immersed in a particularly time-consuming activity (such as retrieving
large chunks of data from a file, or performing complex calculations), it’s a good idea to let the webber
know what’s going on. If too much time passes before the applet somehow informs the Web surfer that
things are going along as planned, they may assume the program isn’t working properly, or simply
become impatient and abandon your Web page altogether.

There are a number of ways to indicate to the webber that your applet is involved in a time-consuming
task. You can display a message, such as “Processing. . . Please Wait,” either in the applet itself or on

file:///F|/books/java%20books/Java%20Bible/ch03/03-06.html (2 of 3)6/26/2005 7:55:49 PM


Java Bible:Applet Design Basics

the status bar portion of the browser. (If you want to display a message in the status bar, however, keep
in mind that not every browser on the market may have one, and, for those that do, remember that
webbers are free to hide them from view entirely!)

A more subtle approach is to change some aspect of the applet to visually indicate that activity is taking
place. A small animation showing sand pouring through an hourglass might be appropriate, or perhaps a
blinking “WORKING” image would do the trick. You might even consider a subtle sound loop or play a
sound clip of a voice saying, “please wait.” Whichever way you do it, it’s a good idea to let users know
they’ll have to be patient.

If the process is particularly long, you should consider altering the message occasionally. If the same
message appears for a long period of time, webbers might think the system is hung or not working
properly. If the message alternates, the frame rate changes, or the rate of an animation alters as time
passes, they’ll be less likely to think something is wrong and abandon ship.

Fonts

When using fonts to display text, you’ll need to be careful about which ones you choose. Since you can’t
be sure what fonts are installed on the various machines your applet will be executed on, it’s important
to determine if a font you want to use is available to all systems before attempting to use it. If you try to
use a font that isn’t installed on everyone’s computer, a font substitution will take place that might ruin
the visual effect you had planned.

It’s simple, and recommended, to find out what fonts are installed. However, you don’t have to bother if
you’re using the widely installed Times Roman and Courier fonts.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch03/03-06.html (3 of 3)6/26/2005 7:55:49 PM


Java Bible:Applet Design Basics

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

File Access and Network Connections

The majority of applets you create will require external data stored in a file (such as images, audio clips,
and so on), which must be located on the Web. Because of the security restrictions imposed by current
browser implementations, applets fetched from the Net can’t access local files, so any files an applet
accesses must be stored on the same Web server that the applet itself resides on.

Save yourself the frustration of trying to access local files, or files located anywhere hut on the server
where the applet itself resides, as it would be an exercise in futility. Since applets simply aren’t allowed
to touch files residing anywhere outside of the server on which they themselves come from, it’s hopeless
to even try to access files on the user’s machine or other Web servers.

Although future versions of Java/browser combinations are expected to support local and remote file
access, for now you’ll have to design your applets to retrieve files from their own server. However, the
same isn’t true for uniform resource locator (URL) connections. Your applets can open any valid URL
and have the browser automatically load the page (see Chapter 15 for details).

These restrictions on Java applets do not apply to Java applications. Applications can access files on the
user’s local system, or from anywhere on the Web (assuming, of course, that they can make a
connection to the Web server on which such files are located).

Testing locally, releasing globally

Although your applets can’t load files located on the webber’s own computer, or on a server other than
the one they come from, you can do the majority of development and testing on your local system.

Rather than going through the process of uploading each revision of your applet to the Web and testing
it from afar, you can write and test your applets locally, assuming the data files they require are also
local. If an applet’s directory layout on your local computer system is the same as the one on the server
the applet will be uploaded onto, and if all of the files the applet requires are present and in the same
relative directories, you can greatly streamline the development process.

file:///F|/books/java%20books/Java%20Bible/ch03/03-07.html (1 of 3)6/26/2005 7:55:49 PM


Java Bible:Applet Design Basics

In this case, you can write and test applets locally and merely upload them to the server when you are
ready to test them in a networked environment. Of course, you’ll want to test them extensively after
you’ve placed them on the Web. However, developing and testing locally can still save you a great deal
of time.

Other Considerations

There are a number of other design issues to consider when developing applets. For starters, you must
assume that your programs will be accessed by a global community.

A universal language

Since not everyone in the world speaks your language (except, perhaps, the language of love — but
that’s another story altogether), try to minimize the amount of text you use. If possible, use images and
icons to convey meaning rather than words. In many cases, of course, text is required and you’ll have no
choice. But when you do have a choice, opt for images rather than words.

You should also consider the concept your images convey. Even though images are often more easily
understood than words, just because you’re using them doesn’t mean the concept they convey is
universal. In cases where your applet must be understood by a diverse audience, it’s a good idea to have
the graphic artist creating the artwork used in your applet consult with a multilingual specialist or
agency beforehand.

Avoid language and images that could be construed as racist, sexist, or culturally insensitive.
What may be appropriate to you might be offensive to others.

Layout managers

Because applets can be run on a variety of platforms, it can be a bit difficult to ensure that your graphical
elements will always appear in the proper positions on the screen. If you attempt to explicitly position
elements (buttons, scroll bars, popup menus, drawing and painting areas, for example) at exact locations
on the screen, you’re flirting with disaster. The system of coordinates on your computer won’t map
exactly to others, so your neat and tidy layout may become an ugly mess (or even impossible to use) on
other platforms.

To overcome this difficulty, Java utilizes layout managers, which are dealt with in detail in Chapter 21.
With layout managers, you don’t place elements on the screen using explicit coordinates. Instead, the
order in which you add them, and the layout manager associated with such elements, dictates where
they’ll be placed. When your applet is displayed, the layout manager positions the elements in their
proper places, regardless of what platform the applet is executed on. Furthermore, when the webber
resizes the applet, the layout manager takes care of repositioning each element accordingly. By using

file:///F|/books/java%20books/Java%20Bible/ch03/03-07.html (2 of 3)6/26/2005 7:55:49 PM


Java Bible:Applet Design Basics

Java’s layout managers, you can ensure your applet’s user interface will look and act as it should across
a wide array of platforms.

Inter-applet communications

In many cases, a single applet won’t be appropriate for your needs. For example, you might require
applet activity in one part of a Web page to he coordinated with activity in another part of the page. You
might also need to have standard Web content appear between the two areas, preventing you from
creating one big applet that spans the entire page.

Rather than creating one giant applet, it may be easier and more appropriate to create two. Since applets
in a Web page can send each other messages, they can effectively “talk” to each other. In fact, you can
have any number of applets in a Web page, all communicating with one another (see Chapter 15).

Dual-purpose programs

At times, you’ll develop Java programs that will be deployed both in applet and application form. There
may be differences between the two, hut portions may be exactly the same. When this is the case, you
don’t have to develop both programs separately. Instead, you can write one body of code that can be
executed as both an applet and an application, as illustrated in Chapter 18. Doing so saves the time and
effort of managing two different versions of essentially the same program, and ensures that consistency
and code integrity exists between the two.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch03/03-07.html (3 of 3)6/26/2005 7:55:49 PM


Java Bible:Applet Design Basics

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Managing Source Code

When it comes time to implement your applet, you’ll have to carefully consider the code you will write
in addition to the design issues discussed earlier in this chapter. Although much of the time and effort
you spend will go into the overall design of the applet and the objects that will make it possible,
eventually you’ll have to get clown to the nitty-gritty and write the actual source code. When
programming in Java, there are number of things you can do to make the process go as smoothly as
possible.

Only one class to a source file

As you learned in Chapter 2, objects are created using code templates known as classes. When creating a
large number of classes, you should consider placing each in its own source code file.

By separating classes into their own source files, the concept of programming in terms of objects is
strongly reinforced. Classes in separate files can only interact with others in a well-defined manner,
meaning you won’t be tempted to take shortcuts that might compromise the integrity of your code.

When you compile an applet or application whose classes exist in multiple source files, each is
automatically compiled in turn. You don’t have to worry about compiling every source file on your own,
making the separation that much easier.

For many smaller applets and applications, saving each class in a separate source code file may be more
hassle than it’s worth. When you are beginning to program in Java, as with any language, it helps to start
out with small programs and work your way to more complex ones as your understanding grows.

When you place all classes in the same source file, be sure to remember that each class should be written
as its own island and have no knowledge of the innards of other classes. Even if classes aren’t physically
separate, their implementation should be independent from that of others. Later, when your programs
become more complex, you may choose to separate classes into their own files.

file:///F|/books/java%20books/Java%20Bible/ch03/03-08.html (1 of 3)6/26/2005 7:55:49 PM


Java Bible:Applet Design Basics

Keep in mind as you set forth on your Java programming adventure that each source code file
can only contain one public class. If you attempt to place more than one public class inside a
single source code file, the Java compiler will refuse to compile the file!

Document, document, document

As with most programming languages, it’s highly recommended that you document your programs as
they are written, using code comments. Document? Comments?! Yep. But before you jam that index
finger down your throat in an attempt to clear your now queasy stomach, hear me out.

Although many programmers tend to gloss over source code documentation, or avoid it altogether, it’s
an important part of the process. So important, in fact, that Java provides a special comment that is used
to generate documentation files in HTML format — complete with hyperlinks — directly from source
code. By making the process of documentation so easy, Java encourages even the most hasty
programmers to properly comment their code.

Thanks to Java’s special Doc Comments, which look almost exactly like the standard C comments (with
exception of an added asterisk), creating code documentation is a cinch. In addition to making your
source code easier to understand when it comes time to enhance or maintain the work you’ve done, you
can use Doc Comments to produce lovely HTML documentation that you would otherwise have had to
create by hand. Thanks to Doc Comments, a single effort on your part (and a simple one at that)
produces two extremely useful forms of code documentation. You can’t beat that, can you?

Variable names

When you’re using variables, it’s important to choose clear and understandable names for them. Just as
with source-level documentation using comments, some programmers tend to choose terse, if not
entirely cryptic, variable names.

Reading and maintaining such code is more difficult than it should be, and it can be especially
frustrating and time consuming for people other than the original programmer. Even in cases where
you’ll be the only one to see the code, it’s a wise idea to use descriptive variable names. As time passes,
you’ll find reading the code a pleasure because it remains readily understandable.

In Java, variable names can be any length, so you’re not restricted in how many characters you can use.
Employ as many as you feel necessary to ensure that the names make sense.

Of course, some variables don’t merit distinguished names. Take, for example, variables used to control
the iteration of loops and other control-flow structures. Typically, single-character names (such as i or x)
are just fine, since experienced programmers recognize such variables as being specific to the loop. In
these cases, using a descriptive variable name (such as loopCounter or iterationCount) buys little, if any,
value and may even make the code more difficult to read by cluttering an otherwise clean

file:///F|/books/java%20books/Java%20Bible/ch03/03-08.html (2 of 3)6/26/2005 7:55:49 PM


Java Bible:Applet Design Basics

implementation.

Since different types of variables serve different purposes in your programs, be sure to follow
the recommended naming conventions when it comes to actually giving your variables
identifying names. Chapter 9 describes the conventions for identifiers (names given to
variables, classes, and methods).

Altering variables

In Java, there is no such thing as a “global” variable. Instead, objects contain variables, which other
objects may or may not be able to directly alter depending on how access to the variable is specified.
(You specify access using access specifiers, which are known formally as field modifiers. Access
specifiers are discussed in detail in Chapter 9.)

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch03/03-08.html (3 of 3)6/26/2005 7:55:49 PM


Java Bible:Applet Design Basics

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

As a general rule, however, objects should assume no knowledge whatsoever of the details of other
objects in a program. This means that an object shouldn’t be able to directly access another object’s
variables, regardless of how access to such variables is specified. Instead, the object should politely
request that the other object access its own variables and return the result or modify the value it holds.

For example, if object A wants to retrieve a variable inside object B, it should ask B for the variable.
Likewise, if object A wants to change the value of a variable in object B, it should ask object B to alter
its own variable. This way, your objects won’t have intimate knowledge of one another, and you can
easily replace or update one without affecting the others. You accomplish such behavior by using
accessor methods, which are nothing more than methods used to retrieve and/or alter the value of an
object’s variable. Thanks to accessor methods, the objects in your Java programs are much more
modular in nature, letting you easily update or alter them in the future without worrying about
“breaking” hard-coded dependencies among objects. You’ll learn more about accessor methods in
Chapter 9.

Avoiding native code

Although Java allows programmers to use non-Java, or native, source code (such as C code), you should
always rewrite the code in standard Java if possible.

In order to make a clean transition to Java, you shouldn’t try to use your existing non-Java source code
unless absolutely necessary. Instead, you should take the time to rewrite that code in Java to avoid
potentially compromising the objectoriented nature of your programs.

Aside from the fact that it’s good practice to use pure Java code in your programs, only C may be
integrated at this time (unless you use the Java Native Interface-JNI). And so you shouldn’t even
consider using code in other languages. If however, you rely on existing C code that simply can’t be
rewritten in Java, you can integrate this native code into your Java programs. If you do so, however, be
forewarned — you’ll likely spend the majority of your bug-fixing time inside the native code you
introduce into your programs!

Peeking under the covers

file:///F|/books/java%20books/Java%20Bible/ch03/03-09.html (1 of 3)6/26/2005 7:55:50 PM


Java Bible:Applet Design Basics

One of the best ways to learn how to program in Java is to look at the work of others. That’s why we’ve
included a CD-ROM full of applets and their source code with this book.

In addition to looking at the source code for these applets, you should spend some time looking at the
source code provided with Java itself. The JDK, which provides all the tools you’ll need to write your
own Java programs, gives us a great deal of code to examine.

Along with the JDK’s own applets, which are also available on the enclosed CD-ROM, thousands of
lines of Java code are used to implement the standard class libraries you’ll use to write your own
programs. In particular, the JDK class source files provide an excellent insight into the Java language.
They illustrate every aspect of the Java language, and are documented with source code comments.
Don’t be afraid to peek under the covers; you’ll see how the Java team at Sun writes Java code, and
learn a great deal in the process.

Packages

Once you’ve written a fair amount of Java code, you’ll be faced with the challenge of managing it.
You’ll eventually want to reuse classes you’ve written, and organize your growing base of code for
future reuse.

In Java you can easily organize classes into packages (discussed in Chapter 11). You can think of
packages as collections of classes that allow you to efficiently organize and reuse existing Java code.

The Java system comes with a number of packages ali ready for you to use. These packages contain a
large number of pre-built classes written by the JavaSoft team at Sun, many of which you’ll use in your
own programs.

Summary

Before diving in and writing your first Java applet, it’s important to first consider the design of applets.
By “design,” I mean not only the overall design — how it looks, what it does, how it interacts with the
webber, and so forth — but also the internal organization of the source code needed to create the applet
in the first place.

• Remember that every person who encounters your applets will have a different opinion as to
what is and isn’t cool.
• Because Java makes creating Web pages with sophisticated animation and sounds a snap,
people who are new to the language often tend to lose themselves in the excitement. Iceberg-
sized images and audio clips abound on the high seas of the Web. And while this may be just fine
for the developer who has access to the Web via a T1 line or cable connection, the equivalent of
an ocean liner, the rest of the world isn’t so fortunate; creaky wooden rafts and pontoon boats are
the norm.

file:///F|/books/java%20books/Java%20Bible/ch03/03-09.html (2 of 3)6/26/2005 7:55:50 PM


Java Bible:Applet Design Basics

• Along with bandwidth concerns, you must consider the variety of systems your applets will run
on once they become available to a global population. Just as most webbers lack ultrafast
connections to the Web, they’re often surfing with systems that are remarkably less powerful
than those we use to develop applets. As a result, you must develop applets to run on a wide
variety of systems, from entry-level boxes to silicon-heavy hot rods.
• The majority of applets you create will require external data stored in a file (such as images,
audio clips, and so on), which must be located on the Web. Because of the security restrictions
imposed by current browser implementations, applets fetched from the Net can’t access local
files, so any files an applet accesses must be stored on the same Web server that the applet itself
resides on.
• When designing your Java applications you should have only one class to a source file; add as
much documentation as possible; use understandable variable names; provide methods to
manipulate object variables; and avoid using any native code.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch03/03-09.html (3 of 3)6/26/2005 7:55:50 PM


Java Bible:Installing and Configuring the Java Development Kit

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

CHAPTER 4
Installing and Configuring the Java Development Kit
In This Chapter

Obtaining the latest and greatest Java Development Kit

Installing the Java Development Kit

Configuring the Java Development Kit for your particular operating system

Verifying your installation of the Java Development Kit

Troubleshooting your Java Development Kit installation

A review of the tools provided in the Java Development Kit

To develop applets and applications in Java, you must first install Sun’s Java Development Kit (JDK) on
your computer. The JDK contains everything you need to begin creating Java programs. This chapter
explains how to get, install, and configure the most recent release of the JDK for Solaris, Windows 95,
Windows NT, and Macintosh computer systems. In addition, this chapter briefly looks at each of the
tools in the JDK.

Getting the JDK

JDK 1.2 was unavailable as this book went to press, but can be downloaded directly from Sun’s JavaSoft
Web site—the official Java support site—at http://java.sun.com. In both cases, you’ll find JDK 1.2 for
the Solaris and Windows 95/NT development machines, as well as older versions of the JDK for these
systems and Apple Macintosh computers (at the time this book was written, only JDK 1.02 was
available for the Mac!). Sun’s JavaSoft division (a Sun-owned company focused entirely on Java
development) regularly releases new versions of Java and Java development tools at this site. Other third-

file:///F|/books/java%20books/Java%20Bible/ch04/04-01.html (1 of 4)6/26/2005 7:55:50 PM


Java Bible:Installing and Configuring the Java Development Kit

party ports are also available through Sun’s JavaSoft support site.

JDK release 1.1.5 is included on the CD-ROM that comes with this book. Unless a more
current version is now available, you can save the time and effort of downloading JDK by
installing it directly from the CD-ROM (see Appendix B).

The Java Developer Connection (JDC)

One of the most important Web sites Java developers should get into the habit of visiting is the Java
Developer Connection (JDC), located at http://java.sun.com/nav/developer/index.html.

According to Sun, the company ultimately responsible for Java, the JDC is for individual developers.
Sun states, “JDC is a free service offering online training, a searchable bug database, product discounts,
feature articles, and more. JDC also features online discussion forums with industry luminaries like
James Gosling, among others.”

Personally, I try to spend as much time as I can at the JDC. At the time this book was being written, the
JDC was just getting started, but already offered tons of useful information and source code. One of my
favorite JDC areas to visit is the “DukeDollars” page, which allows members to post Java-related
technical questions and annoyer those already posted.

To ask a question in this area, you must decide how many “DukeDollars” it’s worth to you (every
member gets 10 free DukeDollars to start), and then be willing to give away that amount when someone
supplies a satisfying answer. Conversely, you can make off like a bandit by answering questions posted
to this forum, which has allowed some developers to amass a staggering number of DukeDollars over
time. The online trading of DukeDollars here is fast and furious, and you’ll walk away a winner by
simply drinking in the technical questions and answers that fuel this mini economy on the JDC

Of course, you have to register to become a member of the JDC site, but once you do, you’ll find links
to early releases of Java software, online training courses, source code, and technology briefings. If
you’re serious about programming in Java, this is one site you should immediately visit and then
bookmark in your browser.

Once you’ve located the JDK for your platform, download it to your local computer (or copy it from the
enclosed CD-ROM if you don’t want to waste time and money online). This may take some time,
depending on the speed of your Internet connection, so you might seriously consider using the JDK
provided on the CD-ROM instead. In fact, the only reason you should bother downloading the JDK from

file:///F|/books/java%20books/Java%20Bible/ch04/04-01.html (2 of 4)6/26/2005 7:55:50 PM


Java Bible:Installing and Configuring the Java Development Kit

the Web is if the version online is significantly more current than the one provided on disc.

Chances are pretty high that you’ve already got your hands on the most current JDK. The CD-
ROM contains JDK version 1.1.5. To find out more about the versions of JDK, version 1.1.5,
go to the JavaSoft Website at either http://java.sun.com or http://www.javasoft.com (either
URL gets you there).

Regardless of whether you download the JDK from the Web, you can always download the full-blown
JDK documentation supplied online, since that’s not part of the JDK. JDK documentation is provided in
several popular formats, including Adobe’s Portable Document Format (PDF), Adobe Postscript (PS),
plain old-fashioned HTML (my personal favorite), and even WinHelp format (for Windows users), all of
which you can find at http://java.sun.com/products/jdk/1.1/, or at the Documentation Web site, http://
java.sun.com/products/jdk/1.1/docs/index.html.

Expanding the JDK Archive

Whether you download the JDK from the Web or simply copy it to your computer from the enclosed
CD-ROM, you’ll first have to decompress the archive it comes in before you can actually use it. Both
the Solaris and Windows 95/NT versions of the JDK are self-extracting archives, making them relatively
easy to decompress and install.

Subsequent discussions assume you’re working with JDK 1.2; if you’ve got 1.1.5, simply
adjust for the differences in file and directory names.

You expand the Windows 95/NT self-extracting archive with a double-click:

1. Ensure that the JDK archive file is at the root level of your primary drive (usually C: \).
2. Double-click the JDK archive file to start the extraction process.

You expand the Solaris self-extracting archive from the command line. This is also a straightforward
process, and one you’re likely familiar with if you’ve dealt with self-extracting archives before:

1. First this command to change the JDK archive file into an executable file:

chmod a+x jdk1.2-solaris2-sparc.bin

2. Then type this command to extract the JDK files:

./jdk1.2-solaris2-sparc.bin

file:///F|/books/java%20books/Java%20Bible/ch04/04-01.html (3 of 4)6/26/2005 7:55:50 PM


Java Bible:Installing and Configuring the Java Development Kit

You can expand the Solaris JDK archive anywhere on your Solaris machine.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch04/04-01.html (4 of 4)6/26/2005 7:55:50 PM


Java Bible:Installing and Configuring the Java Development Kit

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Once the JDK archive has been expanded, a Java directory similar to the one shown in Figure 4-1 is
created. This directory contains a number of subdirectories, tools, and files, which together make up the
Java Development Kit. Each of the Java tools (see Table 4-1) are actually executable programs. (To
learn more about the tools supplied with the JDK, see “Using Java Tools” later in this chapter).

Figure 4-1: Upon installing the JDK, a java directory is created on your computer containing the
various tools and files necessary to develop Java programs.

Table 4-1
Java Tools

Tool Description

appletviewer The standalone Applet Viewer, which allows applets to execute without the
use of a Java-savvy browser.
Jar The Java archive tool, which combines multiple files into a single, Java
Archive format (JAR) file.
Java The interpreter, which executes Java bytecode.
Javac The compiler, which converts Java source code into bytecode.
Javadoc The documentation generator, which can create files from source code.
Javah The native method C file generator, which creates C-header and source files
for native methods.
Javakey The Java digital key tool, which generates a digital signature tar JAR files.
Javap The disassembler, which disassembles Java bytecode and outputs the result
in a human-readable form.

file:///F|/books/java%20books/Java%20Bible/ch04/04-02.html (1 of 3)6/26/2005 7:55:51 PM


Java Bible:Installing and Configuring the Java Development Kit

Jdb The debugger, a text-based tool for debugging Java programs on the
command line.
Jre The rutime interpreter, which you can use to run Java applications. This tool
is similar to the Java tool, but it is intended primarily for end users who do
not require all the development-related options available with the java tool.
Native2ascii The native code page tool, which converts nonUnicode Latin-1 (source code
or property) files to Unicode Latin-1.
Rmic The remote method invocation compiler, which generates stub and skeleton
class files for Java objects implementing the java.rmi.Remote interface.
Rmiregistry The remote object registry tool, which starts a remote object registry on a
specified port. The remote object registry is a bootstrap naming service used
by RMI servers.
Serialver The serial version tool, which returns the serialVersionUID for one or more
classes.

Once you’ve installed the JDK, all of Java’s own class libraries are placed inside the JDK lib
directory (a subdirectory of the main directory into which the JDK is extracted), and are
compressed into an archive named classes.zip. Whatever you do, never decompress the classes.
zip archive! This archive is used to keep the suite of Java class files well organized and easily
accessible, meaning you should leave the archive intact; if you decompress it, the Java tools
won’t have a clue where to find the class files, and so will give you serious grief in return

While the classes.zip archive is strictly hands-off, the class source code archive, src.zip, is another matter
altogether. You can unzip (decompress) these Java source code files to take a look at how their
corresponding class files in classes.zip were created, and then place them wherever you like. While the
source code files aren’t necessary since the classes.zip archive has everything you’ll need, they’re nice to
keep around if only to take an occasional peek at how Sun’s own engineers created the library of classes
you’ll use regularly from within your own Java programs.

A Windows ZIP utility, WinZip 6.3, is provided on the enclosed CD-ROM. You can use this
wonderfully powerful piece of shareware to create your own ZIP archives, or to decompress
those you come across in your travels (such as the scr.zip archive described here). See
Appendix B, “What’s on the CD-ROM,” to find out more about WinZip 6.3 and the other
useful utilities provided on disc.

Setting Up Your Java Environment

After you’ve installed the JDK, you must ensure that two environment variables, PATH and CLASSPATH,
are set properly. The correct settings for both variables hinge on where you install the JDK onto your

file:///F|/books/java%20books/Java%20Bible/ch04/04-02.html (2 of 3)6/26/2005 7:55:51 PM


Java Bible:Installing and Configuring the Java Development Kit

computer.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch04/04-02.html (3 of 3)6/26/2005 7:55:51 PM


Java Bible:Installing and Configuring the Java Development Kit

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

The PATH environment variable specifies where the operating system looks for executable files when
you don’t supply the full directory path leading to the file you’d like to execute. To use the JDK, you
must either change an existing PATH environment variable or specify a brand new PATH environment
variable, both of which you do differently under Solaris, Windows 95, and Windows NT.

The CLASSPATH environment variable specifies where the Java tools look for class files when you don’t
supply a full directory path manually. (The class files could be the suite of class files contained in the
classes.zip archive discussed earlier, or even your own library of class files if you happen to create enough
classes to merit placing them in a library package of your own making.) Since the process of setting the
CLASSPATH environment variable varies from platform to platform, I’ll explain how to go about setting
CLASSPATH for Solaris, Windows 95, and Windows NT at the same time that you set the PATH
environment variable.

Solaris

Solaris users typically set environment variables in the startup file for the shell you use. Since most
Solaris users do this through either a variation of the s h shell or the csh shell, I’ll include a brief
description of each here. In both cases, assume that the JDK has been installed into a directory called
jdk1.2. If this isn’t the case, you’ll have to substitute the actual directory name you placed the JDK into
anytime a directory named jdk1.2 appears below.

If you install the JDK in the default location the installer provides, /usr/local/jdk1.2/bin, you don’t
need to set the CLASSPATH environment variable at all! The JDK tools automatically append .:/
usr/local/jdk1.2/classes:/usr/local/jdk1.2/lib/classes.zip to the CLASSPATH setting each time a tool is
run. If you create your own library of class files, however, you should create an appropriate
CLASSPATH setting to allow the JDK tools to find them.

To modify the setting of your PATH environment variable and to set the CLASSPATH environment
variable in your .cshrc file (for csh shell variants), insert these lines:

set path=(/usr/local/jdk.l.2/bin $path)


set CLASSPATH=(/usr/local/jdk1.2/classes:

file:///F|/books/java%20books/Java%20Bible/ch04/04-03.html (1 of 3)6/26/2005 7:55:51 PM


Java Bible:Installing and Configuring the Java Development Kit

/usr/local/jdk1.2/lib/classes.zip)

Once you’ve made these changes, you should force the operating system to reread your . cshrc file by
entering this command:

sourcE ~/.cshrc

To modify the setting of your PATH environment variable and to set the CLASSPATH environment
variable in your .profile file (for sh shell variants), insert these lines:

PATH=($path:/usr/local/jdk1.2/bin) export PATH


CLASSPATH:(/usr/local/jdk1.2/classes:
/usr/local/jdk1.2/lib/classes.zip) export CLASSPATH

Once you’ve made these changes, you should force the operating system to reread your .profile file by
entering this command:

. ~/. profile

Windows 95

Windows 95 users set environment variables in the autoexec.bat file, which is typically found on the root
level of the primary hard drive (such as C: \). Since many Windows 95 users don’t have an autoexec.bat
file, you might have to create one manually using a text editor (autoexec.bat is simply a text file with the .
bat extension). If this is the case, be sure that you name the file exactly, and be certain to place it on the
root level of your hard drive. If you don’t, Windows won’t bother loading this file at startup, and the
environment variables you specify here won’t have a chance to become “active.”

To modify the setting of your PATH environment variable and to set the CLASSPATH environment
variable in your a autoexec.bat file, append these lines:

set PATH=%PATH%;C:\jdk1.2\bin
set CLASSPATH=C:\jdk1.2\classes;C:\jdk1.2\lib\classes.zip

As with the Solaris instructions above, I’m assuming that the JDK has been installed into a directory
called jdk1.2. If this isn’t the case, you’ll have to substitute the actual directory name you placed the JDK
into where the directory name jdk1.2 appears above.

Once you’ve made these changes, you must either restart your computer or manually force the operating
system to reread your autoexec.bat file by entering this command:

file:///F|/books/java%20books/Java%20Bible/ch04/04-03.html (2 of 3)6/26/2005 7:55:51 PM


Java Bible:Installing and Configuring the Java Development Kit

\autoexec

Windows NT

Unlike Windows 95 users, who access environment variables by way of editing the autoexec.bat file,
Windows NT users have the luxury of using the System program in the Control Panel. Simply open the
Control Panel, double-click the System program, and then enter the following lines:

set path=%path%;C:\jdk1.2\bin
set CLASSPATH:C:\jdk1.2\classes;C:\jdk1.2\lib\classes.zip

You might notice that these two lines of text are exactly the same as those used for Windows 95, and for
good reason: Windows NT and Windows 95 are similar in how they deal with environment variables.
Perhaps the most significant difference lies in how you enter them. While Windows NT uses the System
program, Windows 95 users have to edit an autoexec.bat file. Either way, the environment variables are
loaded at startup time.

Once you’ve made these changes in the System program, you can either click the Done button, at which
point you must restart you computer for the changes to take effect, or you can force Windows NT to
reload your environment variables on the spot by clicking the Apply button. (If you click Done, you
must reboot before Windows NT will recognize your changes—clicking Apply is a faster, more
convenient way to accomplish the same thing.)

Testing the JDK Installation

After you’ve installed the JDK, you should test the installation. To do this, simply change to one of the
demo subdirectories in your new java directory (which is named jdk1.2 by default, although you may
have specified a different name at installation) and run the Applet Viewer program on an associated
HTML file.

For instance, to run the Tic-Tac-Toe demonstration applet from a Windows installation, start by
changing to that directory:

cd C:\jdk1.2\demo\TicTacToe

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch04/04-03.html (3 of 3)6/26/2005 7:55:51 PM


file:///F|/books/java%20books/Java%20Bible/ch04/images/04-01.jpg

file:///F|/books/java%20books/Java%20Bible/ch04/images/04-01.jpg6/26/2005 7:55:51 PM
Java Bible:Installing and Configuring the Java Development Kit

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Note that JDK files on Sun installations have the same path as on Windows installations, although
Windows uses backslashes (\) to separate directories, whereas Sun systems use slashes (/). To move to
the same directory on a Sun system, type this line:

cd jdk1.2/demo/TicTacToe

Inside each demo directory, such as TicTacToe, there is an HTML file that contains the <APPLET> tag to
execute that demonstration applet. In this case, as with most of the demos included with the JDK, the
HTML file is named examplel.html. Once you’re in the TicTacToe directory, run the Applet Viewer
program (appletviewer) with that HTML file:

appletviewer examplel.html

If everything was installed properly, you should now be playing a game of tic-tac-toe, as illustrated in
Figure 4-2. If not, see the “Installation Troubleshooting for Solaris” or “Installation Troubleshooting for
Windows 95 and Windows NT” sidebar for help.

Figure 4-2: Java Tic-Tac-Toe, one of the many demo applets supplied with the JDK.

file:///F|/books/java%20books/Java%20Bible/ch04/04-04.html (1 of 3)6/26/2005 7:55:52 PM


Java Bible:Installing and Configuring the Java Development Kit

If you’ve installed the most current version of the JDK (version 1.2.x at the time of this
writing), you will likely notice that many of the demo directories provided with the toolkit
contain additional directories named 1.0.2 and 1.1.5. This allows us to see how the same applet
is written using different versions of the JDK. Remember, JDK 1.0 was first out of the gate,
and eventually matured to 1.0.2 before a new “major” version of the language arrived. That
first major upgrade, version 1.1, itself matured to version 1.1.x before yet another “major”
upgrade came along: 1.2. Today, JDK version 1.2 has matured to version 1.2.x, and will soon
be outdated by an even newer version—JDK 2.0. Since each major version of the language
brings with it major changes in how Java programs are written, the good folks at Sun decided
to include all past versions of the demos they’ve written that are included with the JDK. As a
result, you can execute each of the earlier “major” versions of these demos, and also take a
look at the source code to see how that version of the language was used to create the program.

Installation Troubleshootin for Solaris

The following troubleshooting information is taken from Sun’s most current JDK installation
documentation.

• If you get the error message “The download file appears to be corrupted” when you attempt to
extract the JDK, delete the file and download a new copy. The JDK installation script does a
checksum to ensure that the archive was not corrupted during the download.
• If you get the fatal error message “Exception in thread NULL” when running java javac, or
appletviewer, check the CLASSPATH environment variable. It may list the classes directory from an
older JDK release. You can either unset the CLASSPATH variable, or set it to include only the
latest version of the JDK class library.
If this suggestion does not resolve the problem, consult the installation documentation that came
with the JDK release. You can also refer to the Java “Frequently Asked Questions”
documentation available at the JDC.
• If you get the error message “Could not read properties file” or “Invalid JAVA_HOME” when
running one of the JDK tools, such as appletiviewer, it may mean that your JAVA_HOME
environment variable is not set properly. Normally, you need not worry about setting
JAVA_HOME. However, some Java IDEs set the JAVA_HOME variable to a value that won’t allow
you to run the JDK tools. Use the echo command to see if your JAVA_HOME value has been set:

echo $JAVA_HOME

If the echo command returns a value for JAVA_HOME, make a note of the setting (in case you
want to restore it later), and then try unsetting it and see if you can run the JDK tools. Use the
unsetenv command to unset the JAVA_HOME environment variable:

file:///F|/books/java%20books/Java%20Bible/ch04/04-04.html (2 of 3)6/26/2005 7:55:52 PM


Java Bible:Installing and Configuring the Java Development Kit

unsetenv JAVA_HOME

If you still cannot run the JDK tools after unsetting JAVA_HOME, try setting JAVA_HOME to the
absolute path of the jdk1.2 directory that was created when you installed the JDK. For example, if
you install JDK 1.2, and the directory jdk1.2 has the path /usr/local/jdk1.2, try setting JAVA_HOME
as follows:

setenv JAVA_HOME/usr/local/jdk1.2

As long as you have not disturbed the bin and lib directories that are immediately below the jdk1.2
directory, you should be able to run the JDK tools.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch04/04-04.html (3 of 3)6/26/2005 7:55:52 PM


Java Bible:Installing and Configuring the Java Development Kit

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Installation Troubleshooting for Windows 95 and Windows NT

The following troubleshooting information is taken from Sun’s most current JDK installation
documentation.

• If you see either the error message “net.socketException: errno = 10047” or “Unsupported
version of Windows Socket API,” check which TCP/IP drivers you have installed. The Applet
Viewer tool supports only the Microsoft TCP/IP drivers included with Windows 95. If you are
using third-party drivers, such as Trumpet Winsock, you’ll need to change over to the native
Microsoft TCP/IP drivers if you want to load applets over the network.
If the Applet Viewer tool does not load applets, dismiss it and enter the following set commands
in the same DOS command window as you invoked Applet Viewer:

set HOMEDRIVE=c:
set HOMEPATH=\

Restart the Applet Viewer tool in the same DOS command window. If you still cannot load
applets, enter the following set command in the DOS command window:

set HOME=c:\

Again, restart the Applet Viewer tool in the same DOS command window. If you still cannot load
applets, enter the following java tool command tine in the DOS command window:

java-verbose sun.applet.AppletViewer

The java tool lists the classes that are being loaded. From this output, you can determine which
class the Applet Viewer is trying to load and where it’s trying to load it from. Check to make sure

file:///F|/books/java%20books/Java%20Bible/ch04/04-05.html (1 of 4)6/26/2005 7:55:52 PM


Java Bible:Installing and Configuring the Java Development Kit

that the class exists and is not corrupted.


• If you get the fatal error message “Exception in thread NULL” when running java, javac, or
appetviewer, check the CLASSPATH environment variable. It may list the classes directory from an
older JDK release. You can either unset the CLASSPATH variable, or set it to include only the
latest version of the JDK class library.
If this suggestion does not resolve the problem, consult the installation documentation that came
with the JDK release. You can also refer to the Java “Frequently Asked Questions”
documentation available at the JDC.
• If you cannot close the Applet Viewer tool’s copyright window, move the launch bar to the
side of the desktop to allow access to the copyright window’s Accept and Reject buttons.
• If you get the error message “Could not read properties file” when running one of the JDK
tools, such as appletviewer, or “Invalid JAVA_HOME” it may mean that your JAVA_HOME
environment variable is not set properly. Normally, you need not worry about setting
JAVA_HOME. However, some Java IDEs set the JAVA_HOME variable to a value that won’t allow
you to run the JDK tools. Use the echo command to see if your JAVA_HOME value has been set:

% echo %JAVA_HOME%

If the echo command returns “ECHO is on” or “ECHO is off”, the JAVA_HOME environment
variable has not been set. If the echo command returns a value for JAVA_HOME, make a note of
the setting (in case you want to restore it later), then try/unsetting it and see if you can run the
JDK tools. Use the following set command to unset the JAVA_HOME environment variable:

set JAVA_HOME:

If you still cannot run the JDK tools after unsetting JAVA_HOME, try setting JAVA_HOME to the
absolute path of the jdk1.2 directory that was created when you installed the JDK. For example, if
you install JDK 1.2, and the directory jdk1.2 has the path /usr/local/jdkt.2, try/setting JAVA_HOME
as follows:

set JAVA_HOME=C:\jdk1.2

As long as you have not disturbed the bin and lib directories that are immediately below the jdk1.2
directory/, you should be able to run the JDK tools.

Using Java Tools

Using the Java environment means you’ll have to learn each of the tools outlined in Table 4-1 earlier in
this chapter. Perhaps the three most common tools are the compiler (javac), the interpreter (java), and the

file:///F|/books/java%20books/Java%20Bible/ch04/04-05.html (2 of 4)6/26/2005 7:55:52 PM


Java Bible:Installing and Configuring the Java Development Kit

Applet Viewer (appletviewer). With these three tools and a source code editor, you’ll be able to write, test,
and debug Java applications and applets.

Java source-code files contain, not surprisingly, the actual Java code you write. These are text files, and
you can create them with any text editor or word processor capable of saving files in ASCII text format.
As long as you save your source files in ASCII text format with a .java extension, you’ll be fine. The
following are examples of valid Java source filenames: HelloWorld.java; MyProgram.java;CoolGame.java.

If you omit the .java extension, or if the file is in any format other than ASCII text, the compiler will
generate an error message.

Table 4-2 lists the tools with their proper usage syntax. To help make sense of these, we’ll step through
the process of writing a small application called HelloWorld. Although the details of HelloWorld (both
application and applet versions of the program) are covered in Chapter 7, we’ll use it here to illustrate
the use of the Java tools.

Table 4-2
Using Java Tools

1
Tool Syntax

2
appletviewer appletviewer [-debug] html_file
java java [options] class (see Table 4-4 for options)
javac javac [-option] file.java (see Table 4-3 for options)
javadoc javadoc [-classpath path][-d directory][-verbose] file.java | packagename
javah javah [-classpath path][-verbose][-stubs][-o outputfilename] [-d directory] classes
javap javap [-v][-c][-p][-h][-verify][-classpath path][-l] class
jdb jdb [java options] [ host hostname] [-password password] classname

1
Bracketed [] items are optional.
2
Italicized items are used as parameter placeholders.

file:///F|/books/java%20books/Java%20Bible/ch04/04-05.html (3 of 4)6/26/2005 7:55:52 PM


Java Bible:Installing and Configuring the Java Development Kit

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch04/04-05.html (4 of 4)6/26/2005 7:55:52 PM


Java Bible:Installing and Configuring the Java Development Kit

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Since the actual source code isn’t important for the following examples, assume that you have already
entered the entire program in a text editor. You would save what you’ve written in ASCII text format
(just plain text) in a file with the .java extension:

HelloWorldTest.java

Ignoring the issue of how your development environment directories should be structured (more on that
later), assume that you have saved your HelloWorldTest.java program in an appropriate directory on your
hard drive. Because the source code needs to be compiled before it can be executed, the next step is to
do just that.

Compiling

You can run the Java compiler, javac, with a wide array of options (see Table 4-3). This is the basic
syntax of javac:

javac [option] file.java

Table 4-3
javac Compiler Options

Option Description

file:///F|/books/java%20books/Java%20Bible/ch04/04-06.html (1 of 3)6/26/2005 7:55:53 PM


Java Bible:Installing and Configuring the Java Development Kit

-classpath path Specifies where javac looks for classes that are referenced in the source code
being compiled. Classes can be located in directories in the path, or inside
ZIP archives in the path.
This option overrides the path specified in the CLASSPATH environment
variable. You can specify more than one directory in the path. (On UNIX
systems, use a colon to separate the lists of directories; on Windows systems,
use a semicolon.)
The basic form for path, in UNIX format, is:
.:path1:path2:path3
You should always include the default class directory and ZIP file in your
classpath option, as in the following Windows example:
javac -classpath C:\myclasses;C:\jdkt.2\
classes;C:\jdk1.2\lib\class.zip HelloWorld.java
A period in the path specifies the current working directory, as in the
following Solaris example, which searches the current directory for a class
before any other directory:
javac -classpath .:/home/classes:/export/
classes HelloWorld.java
-d directory Specifies the root directory where javac places the compiled class files. By
default, javac places compiled class files in the same directory as the source
files.
Use this option when you want a class file to be saved into a directory other
than the one containing the source code file. For example:
javac -d/home/javaapps/stuff HelloWorld.java
Here, the resulting HelloWorld.class is not saved in the same directory as the
source code file HelloWorld.java. Instead, javac saves HelloWorld.class in the /
home/javaapps/stuff directory.
-depend Recursively compiles any class files on which the currently compiling file
depends. The compiler does not recursively descend to every leaf. Once it
encounters an up-to-date file on a branch, it ceases descending that branch.
For example:
javac -depend HelloWorld.java
-encoding name Specifies the source file encoding name. If this option is not specified, then
the platform default converter is used. The encodings are used by the
native2ascii native code page tool.Java can support multiple character sets,
making internationalization of your Java applications complete. Using the
encoding flag, you can specify the native character encoding used in your
application.
-g Adds debugging information to the class files that javac generates, Debugging
tables contain information about variables, methods, and line numbers. By
default, only line numbers are generated, unless you specify the - 0
(optimize) option. For example:
Javac -g HelloWorld.java

file:///F|/books/java%20books/Java%20Bible/ch04/04-06.html (2 of 3)6/26/2005 7:55:53 PM


Java Bible:Installing and Configuring the Java Development Kit

-J java_option Passes the string java_option to java, the Java interpreter. The string cannot
contain any spaces. If you want to send multiple strings, use multiple -J
options. This option is particularly useful for adjusting the compiler’s
execution environment or memory usage. For example, the following javac
command has java fire up jdb to initiate a debugging session:
Javac -Jdebug HelloWorld.java
-nowarn Suppresses the generation and display of warnings errors. For example:
Javac -nowarn HelloWorld.java
-0 Optimizes the code by inlining static, final, and private methods when
possible. As a result, code often executes faster. The resulting class files,
however, are often larger. If you use this option and the - g (debug) option at
the same time, javac does not add line numbers to the resulting class files. For
example:
Javac -0 HelloWorld.java
-verbose Displays additional information about the source files being complied and
about any classes being loaded. For example:
Javac -verbose HelloWorld.java

We just want to compile the source file without any options, so you could simply execute the compiler
with the name of our source code file. The following example shows how to compile your program
without any options (the > indicates a command line prompt):

> javac HelloWorldTest.java

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch04/04-06.html (3 of 3)6/26/2005 7:55:53 PM


Java Bible:Installing and Configuring the Java Development Kit

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Any syntax errors or bugs caught by the compiler would immediately follow, although you can assume
there are none in this example. If all goes well, the compiler will convert the human-readable source
code into machine-readable bytecode. The compiler creates a bytecode file for each class declared in our
program. This is in the same directory as our source file, since you didn’t specify a different one using
the -d option. Since your HelloWorld.java source file declares only one class, HelloWorld, the compiler
creates the following file:

HelloWorld.class

In this binary file is the bytecode generated by the compiler for the class HelloWorld declared in your
program. If there were other classes declared in your program, the compiler would create a new file to
contain the bytecode of each. For instance, supposing your program declared three classes (HelloWorld,
GoodbyeWorld, and SpinWorld), a bytecode file for each would have been created by the compiler
(HelloWorld.class, GoodbyeWorld.class, and SpinWorld.class).

At this point, the source code has been converted to bytecode and can be executed by the interpreter
(java, see the next section). You’ve simply used the compiler “as is,” without specifying any of the
options it understands. For a description of each option, see Table 4-3.

Executing applications with the interpreter

Once the bytecode for your application has been generated by the compiler, it can be executed. This is
simple enough in the case of actual applications, since all you have to do is run the java interpreter and
provide it with the bytecode file:

> java HelloWorld

Notice that you didn’t supply the .class extension for the HelloWorld bytecode file. Although the
interpreter requires the file to have such an extension, you don’t need to provide it. In fact, an error
would be reported if you did. For instance, suppose you did this:

> java HelloWorld.class

file:///F|/books/java%20books/Java%20Bible/ch04/04-07.html (1 of 4)6/26/2005 7:55:54 PM


Java Bible:Installing and Configuring the Java Development Kit

Since each bytecode file contains one class having the same name as the file itself (the only difference
being the .class extension of the bytecode file), the interpreter would attempt to locate and execute a class
named HelloWorld.class instead of HelloWorld. In this case, the interpreter would report the following error:

> Can’t find class HelloWorld/class

Note that there are actually four ways to run your Java programs:

• The java command invokes the interpreter with a console window.


• The java_g command is the same as java but includes extra debugging information.
• The javaw command invokes the interpreter without a console window.
• The javaw_g command is the same as javaw but includes extra debugging information.

Don’t forget that the compiler, javac, requires you to include the filename with its .java extension, while
the interpreter, java, wants only the base name of the bytecode file, without the .class extension.

You can use the interpreter with a number of options, many the same as those the compiler supports.
These options are listed in Table 4-4.

Table 4-4
java Interpreter Options

Options Description

CLASSPATH This is not a command-line option; it is an environment variable that you can
set to tell Java where to find classes (or classes in ZIP archives). Having the
same parameters as the - classpath option, you only have to set this
environment variable once.
The following is the basic form, in UNIX format:
.:path[:optional paths]
Windows users should use semicolons to separate path listings. Once set, the
CLASSPATH environment variable can be overridden with the - classpath
option (see - classpath).

file:///F|/books/java%20books/Java%20Bible/ch04/04-07.html (2 of 4)6/26/2005 7:55:54 PM


Java Bible:Installing and Configuring the Java Development Kit

-classpath path Specifies where java looks for class files to execute. Classes can be located in
directories in the path, or inside ZIP archives in the path.
This option overrides the path specified in the CLASSPATH environment
variable. You can specify more than one directory in the path. (On UNIX
systems, use a colon to separate the lists of directories; on Windows systems,
use a semicolon.)
The basic form for path, in UNIX format, is:,
.:path1:path2:path3
You should always include the default class directory and ZIP file in your
classpath option, as in the following Windows example:
Java -classpath C:\myclasses;C:\jdk1.2\
classes;C:\jdk1.2\lib\class.zip HelloWorld
A period in the path specifies the current working directory, as in the
following Solaris example, which searches the current directory for a class
before any other directory:
Java -classpath .:/home/classes:/export/ classes HelloWorld
-CS, -checksource Compares the modification time of the class bytecode files to their
corresponding source code files. When a source code file has been modified
more recently than its bytecode file, the source is recompiled and the new
bytecode file is used.
-debug Attaches jdb, the Java debugger, to the java session. When this option is used,
java displays a password on the command line that you must use when the
debugging session starts.
-Dpropertyname =newValue Defines a property value, where propertyName is the name of the property to
change and newValue is the new value for that property. You can specify any
number of -D options on the command line.
-help Displays information on how to use java.
-ms size [k | m] Specifies the initial size, in bytes, of the memory allocation pool (the garbage
collection heap). The minimum value for size is 1000, which is the default
size.
You can specify a value in kilobytes (K) or megabytes (MB) rather than
bytes by appending a k or m character, respectively.
-mx size[k | m] The maximum size, in bytes, of the memory allocation pool (the garbage
collection heap). The minimum value for size is 1000. The default value is
16MB.
You can specify a value in kilobytes or megabytes rather than bytes by
appending a k or m character, respectively.
-noasyncgc Turns off the asynchronous garbage collector, prohibiting garbage collection
unless it is explicitly invoked or the program runs out of memory. By
default, the garbage collector runs as an asynchronous thread, in parallel with
other threads in your program.

file:///F|/books/java%20books/Java%20Bible/ch04/04-07.html (3 of 4)6/26/2005 7:55:54 PM


Java Bible:Installing and Configuring the Java Development Kit

-noclassgc Turns off garbage collection of classes. By default, java reclaims the space of
unused classes.
-noverify Bypasses the bytecode-verification phase of the classes it loads. Use this
option only when running code you know is safe (in other words, virus-free
and having no malicious behavior).
-oss size The maximum size, in bytes, of the stack for Java code in threads. (Java
threads maintain two stacks, one for Java code and the other for C code.) The
minimum value for size is 1000. The default value is 40OK.
Threads that are spawned during the execution of the program have the same
stack size for Java code.
You can specify a value in kilobytes or megabytes rather than bytes by
appending a k or m character, respectively.
-prof [file] Starts with profiling turned on and saves the profiling information in file. By
default, the information is stored in java.prof in the current directory.
-ss size The maximum size, in bytes, of the stack for C code in threads. (Java threads
maintain two stacks, one for Java code and the other for C code.) The
minimum value for size is 1000. The default value is 128K.
Threads that are spawned during the execution of the program have the same
stack size for C code.
You can specify a value in kilobytes or megabytes rather than bytes by
appending a k or m character, respectively.
-t Turns on tracing of instructions. This option is valid only with java_g.
-v, -verbose Displays a message every time a class is loaded.
-verbosegc Displays a message anytime the automatic garbage collector frees memory.
-verify Runs the bytecode verifier on all classes that are loaded into the interpreter.
-verifyremote Runs the bytecode verifier on all classes that are loaded by a class loader.
This is the default, so you don’t have to explicitly turn this option on.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch04/04-07.html (4 of 4)6/26/2005 7:55:54 PM


Java Bible:Installing and Configuring the Java Development Kit

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Eecuting applets with the Applet Viewer

Java applications are full-blown applications that are executed outside a Java-savvy browser. Unlike
applets, which run inside a browser environment, applications need only the runtime environment to
execute. Applets, on the other hand, require the help of a browser.

Since firing up a browser each time you want to test an applet can be timeconsuming—and even
impossible on some systems, because of memory constraints—you may prefer to use the Applet Viewer
tool included with the JDK. This tool, shown running a demo applet in Figure 4-3, executes your applets
without the aid of a browser, ameliorating the time and memory issues that come with launching a
browser or keeping one running while developing your programs.

Figure 4-3: Applet Viewer, one of the many JDK tools, provides a fast, effective way to test your Java
applets.

Keep in mind that applets are called into action through the <APPLET> tag in an HTML file, regardless
of whether you use the Applet Viewer or a browser to execute them. This means you’ll need to write a
small HTML file for each applet in order to run them.

While not difficult, the details of doing this are covered in Chapter 7, so I won’t bother going through
the steps here. Assume you’ve written an HTML file for your HelloWorld program. Furthermore, assume
you’ve rewritten the application in the form of an applet (also detailed in the Chapter 7) and have
already compiled it.

Assuming you have your applet bytecode file and HTML file already prepared, you can test it with the
Applet Viewer:

> appletviewer HelloWorldTest.html

file:///F|/books/java%20books/Java%20Bible/ch04/04-08.html (1 of 2)6/26/2005 7:55:54 PM


Java Bible:Installing and Configuring the Java Development Kit

The Applet Viewer opens the supplied HTML file, which can be named anything you wish; it looks for
the <APPLET> tag specifying your program and executes it. This process is quite speedy when compared
with launching a Java-savvy browser, so I’d recommend using the Applet Viewer during development
instead of a browser.

If you followed the instructions in “Testing the JDK Installation” earlier in this chapter, you’ve actually
used the Applet Viewer program already to execute the Tic-Tac-Toe applet. The syntax is about as
simple as you can get, although you may wish to use the debug option:

> appletviewer -debug HelloWorldTest.html

Summary

In order to develop applets and applications in Java, you must first install the Java Development Kit on
your computer.

• If you don’t use the JDK provided on the CD-ROM, you must get the most recent release of
Sun’s JDK from its Web site (http://java.sun.com). You can also download the documentation
and complete source code of the JDK libraries from this site.
• You will find that the JDK includes a number of Java tools, including an Applet Viewer
(appletviewer), an interpreter (java), a compiler (javac), and a debugger (jdb). There are also a
number of Java environment variables that need to be set before you can properly run your Java
applications.
• Once installed, you’ll need to set your path environment variable to include the JDK tools
directory and the CLASSPATH environment variable to include the default class directory and
classes.zip file.
• You can then test the JDK by running various demo applets, with the help of several
troubleshooting hints.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch04/04-08.html (2 of 2)6/26/2005 7:55:54 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

PART II
Getting Up to Speed
In This Part

Chapter 5:

Getting Started: HelloWorld Application and HelloWorld Apptet

Chapter 6:

Extending, Enhancing, Debugging, and Uploading

Chapter 7:

Command-Line Arguments and Applet Tag Attributes

Chapter 8:

Surfing the Web for java Source Code

Now that you have an understanding of Java and its understanding place in application development,
you’re ready to start developing your own applications. In this part, you walk through the process of
designing, developing, testing, and debugging your first Java application. You learn how to design your
applications to function as both standalone applications and Web-based applets.

It’s almost impossible to develop a bug-free application from scratch—so to help with the development
of your application, these chapters show you how to use the debugging tools provided with the Java
Development Toolkit. You learn how to use the Java debugger to stomp out those annoying bugs.

Adding flexibility to your Java applications can really enhance their use. This part will show you how to

file:///F|/books/java%20books/Java%20Bible/ch05/05-01.html (1 of 4)6/26/2005 7:55:55 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

modify your Java applications and applets to accept and use the parameters specified by command-line
arguments. Command-line arguments can supply dynamic information that can change each time your
application is run.

Finally, you’ll learn how to use the Web as your greatest application-development tool. You’ve
undoubtedly heard others ask Why reinvent the wheel? and you need not reinvent the Web, either. By the
time you finish this part, you’ll know how to use the Web to find and borrow Java applications and
objects that can get your applications up and running even faster!

CHAPTER 5
Getting Started: HelloWorld Application and HelloWorld Applet
In This Chapter

Understanding applications and applets

Creating the HelloWorld application

Creating the HelloWorld applet

In this take closer look at the difference chapter, we a between Java applications and Java applets by
writing the infamous HelloWorld program. Here, you examine the source code for both the application
and applet version of HelloWorld as you get to know the structure and purpose of both types of Java
programs. You also execute each to better understand how they differ from a runtime standpoint.

Application Versus Applet

The two fundamental forms of Java programs are the application and the applet. We refer to Java
programs that are capable of being executed outside the context of a browser as applications. The
primary difference between applications and applets is their purpose. Java applications are just like
others we’re familiar with, although they require the presence of the Java runtime environment to be
executed, as do applets. Unlike applets, however, Java applications aren’t meant to exist on the lnternet
and be executed as World Wide Web content. They are, instead, full-blown applications that exist and
are executed on users’ local computer systems, as would a spreadsheet or word processor.

Applets, on the other hand, are designed to live on the network and be executed as part of a Web page.
That’s why they’re referred to as executable contend although they are imbedded in Web pages, just as
standard content is, they are really software programs and can be executed as such.

Applets require a Java-savvy browser such as Netscape Navigator (version 2.0 or later) or Microsoft’s
Internet Explorer (version 3.0 or later) because they must be downloaded from the network and, in

file:///F|/books/java%20books/Java%20Bible/ch05/05-01.html (2 of 4)6/26/2005 7:55:55 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

essence, be given to the Java runtime environment to be executed.

Because of their different purposes, applications and applets are structured differently, both in terms of
their code and in how they are ultimately executed. To examine these differences, we’ll walk step-by-
step through the process of creating a HelloWorld application and applet.

HelloWorld is a simple program, with little practical purpose other than to illustrate the structure and
syntax of real Java code and the process of compiling and executing such code. When executed, the
program does nothing more than output Hello World! to the screen. Because the application version is a
little less complex in terms of code and execution than the applet version, let’s start with that.

HelloWorld Application

Before we get into the nitty-gritty, be aware that Java programs, both applications and applets, are
executed by the interpreter. They are not standalone, because they require the presence of the Java
runtime environment.

In setting up the HelloWorld application, we shall go through the following steps:

1. Set up a directory structure to store our code, including a master directory and subdirectories.
2. Enter and saving the source code.
3. Compile the source code.
4. Execute the application, passing the bytecode file created during the compilation process to
the Java interpreter to output to our screen.

Application directory structure

Before you begin writing a Java program, it’s a good idea to set up a directory structure to store your
code. In most instances, you’ll create a new directory for each program, so I recommend a master
directory in which all these subdirectories will reside. The location and name you choose for your master
directory is up to you. I chose to name my master directory aewcode, and created it inside the main java
directory for the sake of convenience.

Inside my master aewcode directory, I created a subdirectory called Hello, in which the source code and
compiled classes for my HelloWorld program are kept, as can be seen in Figure 5-l. For the following
example, I assume you have also created a Hello directory inside your master directory.

Figure 5-1: Creating a hierarchy of directories for your HelloWorld program

file:///F|/books/java%20books/Java%20Bible/ch05/05-01.html (3 of 4)6/26/2005 7:55:55 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

How you create a directory depends entirely on the platform you use. Windows users can create
directories in the Windows environment using their mouse, or by issuing the mkdir command at the DOS
prompt. Sun users can also use the mkdir command. Macintosh users, however, don’t have a command
line at which to enter such commands. They must select the New Folder item (using their mouse or the
keyboard equivalent for this item) located under the File menu while inside the Finder.

Entering and saving the source

Using a text editor, enter the following source code and save it as a plain ASCII text file named
HelloWorldApp. java inside your Hello directory. Don’t forget to include the .java extension, or the compiler
won’t be able to see it!

class HelloWorld {
public static void main (String args[])
System.out.println(“Hello World! ”);
}
}

Did you notice that the name of the class, HelloWorld, isn’t exactly the same as the name of the file in
which it is saved? This is because we didn’t specify the class as being a public class. If we had, the name
of the source code file would have to be the same as the public class it contains. In this case, the source
code file would be named HelloWorld .java to reflect the public HelloWorld class it defines. However,
because our class isn’t public, the filename can be anything we like. For details on public classes, see the
section “Access modifiers” in this chapter or refer to Chapter 11.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch05/05-01.html (4 of 4)6/26/2005 7:55:55 PM


file:///F|/books/java%20books/Java%20Bible/ch04/images/04-03.jpg

file:///F|/books/java%20books/Java%20Bible/ch04/images/04-03.jpg6/26/2005 7:55:55 PM
Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Class declaration

Before actually compiling the program, we’ll walk through each line of code to get a better feel for the
Java language—beginning with the first line:

class HelloWorld {

This line declares a new class, HelloWorld, the body of which begins following the opening curly brace
({). The closing brace (}) on the last line of our source code signifies the end of the class, which is the
blueprint from which HelloWorld objects will be instantiated.

Keep in mind that Java is an object-oriented language, where the fundamental building blocks are
objects. In fact, everything in Java is an object; the language doesn’t support global functions or global
variables. This means that everything emanates from an object template, formally known as a class.
What we are doing here is creating a class, the blueprint for an object. The class includes all the code for
state (data) and behavior (methods), although in this example we only have methods and no explicitly
declared data.

All classes are derived from, or are subclassed, from existing classes. In the case of our HelloWorld class,
we do not explicitly state of which class it is a subclass. When no superclass (a class from which a class
is derived) is specified, the default is assumed to be class Object. Although we could have explicitly
specified that HelloWorld is a subclass of Object, as shown below, there’s no need to do so.

class HelloWorld extends Object {

In the above example, we use the keyword extends to specify HelloWorld as a subclass of Object, although
our original implementation does the same thing by default. When we rewrite HelloWorld as an applet,
we’ll actually subclass the Applet class. In this case, we must explicitly extend the Applet class, as you’ll
see later. Let’s move on with our application for now.

Method declaration

file:///F|/books/java%20books/Java%20Bible/ch05/05-02.html (1 of 3)6/26/2005 7:55:55 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

The second line declares the main() method, and takes a string parameter, which will contain any
command-line arguments provided when the application is executed. Let’s take a look at the
implementation of the first line of code, or method signature, for the main() method:

public static void main (String args[])

Just as with C and C++, a main() function must be included in a Java application; without it, the
interpreter would have no idea where to begin executing. And just as with C/C++, Java applications can
be executed with command-line arguments. The arguments for Java are passed to the program through
the string parameter, args[].

Although you must include the string args[ ] parameter in your main() method signature, you are under no
obligation to use it. We ignore the args[ ] parameter in this example, because we have no need to use
command-line arguments. While comman-line arguments are covered in more detail in Chapter 7, it’s
worth noting here that the args[ ] parameter is itself an object. It’s an object of type String, a class defined
to handle storage and manipulation of strings. However, we do nothing with the args[ ] object in
HelloWorld, and so let’s press on and take a closer look at the main() method itself.

Of most interest are the keywords preceding main(), specifically public, static, and void. As with C/C++,
void simply means this method does not return any data. If it did, the data type it returned would be
written in place of it. Straightforward enough, but what about the keywords public and static?

Access modifiers

The keyword public is an access modifier. It specifies that the main() method can be called by any object.
This means the main() method is openly available to other objects and is not in any way restricted.

Java supports four access modifiers (public, private, protected, and the implicit “friendly”) that can be
applied to both methods and variables, giving the programmer control over method and variable
accessibility to other objects.

Access modifiers are used to control the visibility (accessibility) of variables and objects by other
objects in a program. By applying one of the three access modifier keywords (public,, private, or protected)
to classes, variables, or methods, you can control the capability of other objects to use them. To apply an
access modifier, include the appropriate keyword when declaring the variable, class, or method:

private int miles; // specifies a private variable


public void main (String args[]) { } // public main() method
protected class HelloWorld { } // protected HelloWorld class

Although access control is discussed in more detail in Chapters 9 and 11, you should always consider to
what extent the variables, classes, and methods in your programs will be accessible to other parts of your

file:///F|/books/java%20books/Java%20Bible/ch05/05-02.html (2 of 3)6/26/2005 7:55:55 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

program. With this in mind, consider the various level of controls provided through access specifiers.

public

Methods and variables specified as public are accessible from any method, regardless of the package to
which the method’s class belongs. Packages are used to organize Java classes, and are described in detail
in Chapter 11. Classes can also be specified as public, making them available to other classes in other
packages. In fact, Java requires that every applet source file (in other words, any class that extends the
Applet class) contain a public class. However, only one public class is permitted in a source file.

private

Variables and methods specified as private are accessible only from inside their own class and aren’t
available to methods in any other class (including subclasses). Unlike the public specifier, private cannot
be applied to classes.

Because early versions of Java supported private classes, some of the older source code you may
encounter on the Web might actually specify classes as private. Attempting to compile such code using
the current release of the Java compiler, however, will result in an error. To remedy the problem, simply
remove the private keyword wherever it is applied to classes.

protected

Variables and methods specified as protected are accessible only from inside their class or subclasses of
their class (subclasses can even override protected methods and variables). As such, the protected
specifier is preferred to private in cases where you want subclasses to have access to variables and
methods, but require tighter access restrictions than the public specifier provides. It can’t, however, be
applied to classes.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch05/05-02.html (3 of 3)6/26/2005 7:55:55 PM


file:///F|/books/java%20books/Java%20Bible/ch05/images/05-01.jpg

file:///F|/books/java%20books/Java%20Bible/ch05/images/05-01.jpg6/26/2005 7:55:56 PM
Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

<blank>

If you don’t specify an access modifier for methods and variables, Java treats them as “friendly”
members, having limited public accessibility. Such methods and variables are accessible to other classes
in the same package, but not classes in other packages. If you don’t explicitly specify a class as being
public, it will (by default) be available only within the package it is declared in (see Chapter 11).

static

The keyword static specifies the main() method as a static method (more commonly known as a class
method). Just as with access modifiers, the static modifier can be applied to both variables and methods.
When applied, static indicates that the method or variable can be accessed without first requiring that an
object of the class they are part of be instantiated (see the sidebar “Class Versus Instance”). If the
keyword static is not explicitly applied to a method or variable, it is automatically considered to be an
instance method or variable.

Accessing an object’s variables and methods

The final line in our HelloWorld program is the one that does all the work, at least as far as displaying
the words “Hello World!” are concerned.

System.out.println(“Hello World!”);

What we’ve done is send the string “Hello World!” to the System class for output (in this case, standard
output [STDOUT], typically the terminal or monitor). Because ali variables and methods in the System
class are static, there is no need for us to instantiate an object of this class prior to referencing variables
and methods, as we have done (again, see the sidebar, “Class Versus Instance”). But what’s going on
with the two dots?

Periods, or dots, are used to access an object’s variables and methods. The syntax is similar to how
you’d access struct elements in C and C++. Suppose you wanted to directly access the horizontal variable
of the Point class we talked about earlier in Chapter 2. Although, in this example, we declared both the

file:///F|/books/java%20books/Java%20Bible/ch05/05-03.html (1 of 4)6/26/2005 7:55:56 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

horizontal and vertical variables as private, if they had been declared public the following would have
done the trick:

int x = myPoint.h; /* access and assign myPoint’s h variable


to x */

Class Versus Instance

In Java, class variables and methods can be either class or instance members of the class in which they
are declared, as indicated by the presence or absence of the static modifier. For example, the main()
method of HelloWorld is a static method. If the keyword static were not part of the method signature,
such as in the following example, main() would instead be considered an instance method of the class
HelloWorld:

public void main (String args [])

Static methods and variables are associated with the class rather than with an instance of the class and
are also known as class variables or class methods. This is a fitting name, because each class variable
and class method occurs once per class; instance methods and variables occur once per instance of a
class. The difference between class and instance members is significant, especially when it comes to
variables.

By occurring only once per instance of a class, class members are shared by all objects created from a
class. That is, all objects created from a given class share the class variables and class methods defined
in that class. Instance variables and instance methods, on the other hand, are created anew each time an
object is created.

Class members can therefore be considered global to a class, even though true global variables aren’t
supported in Java. When an object changes the value of a class variable, all objects instantiated from that
same class see Ge result. Because of this, class variables are often used to share data intended to be
common to all objects created from a particular class.

To refer to instance methods and variables, an object must first be instantiated from that class, after
which it can access the methods and variables from the instance. With static methods and variables,
however, there is no need to instantiate an object before referring to these class members.

The use of a static method is seen in HelloWorld, as we call upon the System class to output a string of
characters without first instantiating an object of that class.

System.out. println(“Hello World!”);

file:///F|/books/java%20books/Java%20Bible/ch05/05-03.html (2 of 4)6/26/2005 7:55:56 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

System. out refers to the out variable in the System class. We didn’t instantiate the System class, yet we are
able to directly refer to the out variable. Because the System class declares out as a static variable, we can
access it directly without the need for instantiation. If out were not declared as a static variable, we
would have to instantiate an object from the System class before accessing it.

When the System class is loaded into an application, the Java interpreter automatically creates out and all
other static variables in that class. Because out has been created, the instance method println() can be sent
to it, as we have done-println() is an instance method of out. Java enables the programmer to cascade
together references to static and instance methods and variables, as we have done in HelloWorld.

In the System class, discussed in detail in Chapter 12, one of the variables is out. The out variable is itself
an object, of which println() is a method. So, what we’ve done in the last line of HelloWorld code is
access the System class’s out variable, executing its println() method, passing our “Hello World!” string as
a parameter.

Compiling the source code

You’re now ready to compile the source code, assuming you have typed it in and saved it as an ASCII
text file with the name HelloWorldApp. java. Going on that assumption, and also that the directory in
which you’ve saved the source file is named Hello, you would now run the javac compiler:

Hello> javac HelloWorldApp.java

Assuming your file didn’t contain typing errors, it should compile just fine. If not, the compiler will spit
out a line or more showing you where the error was found (see Figure 5-2).

If this is the case, open your file and compare it carefully to the following source code:

class HelloWorld {
public static void main (String args[])
System. out. println( “Hello World!”);
}
}

file:///F|/books/java%20books/Java%20Bible/ch05/05-03.html (3 of 4)6/26/2005 7:55:56 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

Figure 5-2: If your file contains errors, the compiler will spit out a line or more showing you where
they were found.

Be sure all the curly brackets ({ }) are included and check your spelling. Fix any problems, save the file,
and try again. When the contents of your text file exactly matches the HelloWorld source code shown
here, you should have no problem compiling.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch05/05-03.html (4 of 4)6/26/2005 7:55:56 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

You’ll know the compiler is successful when no error messages are reported. Assuming you’re in the
Hello directory, where your source file is also located, the following is typical of a successful
compilation (where Hello> is the prompt):

Hello> javac HelloWorldApp.java


Hello>

Because no errors were reported here, the compiler was able to convert the source file into a binary
bytecode file called HelloWorld. class. For every class the compiler comes across in a source file, it creates
a bytecode file of the same name. Check the directory to see if a bytecode file was indeed created. Your
Hello directory should now contain two files: HelloWorldApp.java and HelloWorld.class.

Once you have successfully compiled the source code, which results in a binary bytecode file being
generated in the same directory, it’s time to run the program.

Executing the application

When you execute a Java application, you’re executing bytecode. Therefore, you must pass the bytecode
file created during the compilation process to the Java interpreter:

Hello> java HelloWorld

Notice we do not include the .class extension. The interpreter assumes you passed it just the filename of
the class. If you give it the .class extension as well, it thinks it’s looking for a class named HelloWorld.
class and comes up empty-handed. If you make this mistake, or do it intentionally just for kicks, an error
message such as the following will be generated:

“Can’t find class HelloWorld/class”

Also, notice that we have provided the interpreter with exactly the same upper-and lowercase formatting
of the class name. This is no mistake, because Java is case-sensitive. The HelloWorld class is not the same
as a helloworld class, nor as a helloWorld version. Sure, you and I might recognize them as the same, but

file:///F|/books/java%20books/Java%20Bible/ch05/05-04.html (1 of 4)6/26/2005 7:55:57 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

Java sees each as different. Be sure to provide the interpreter with the precisely formatted name of the
bytecode file, which should also be an exact replica of the compiled HelloWorld class.

Assuming you enter the class name exactly, the bytecode file will be loaded by the interpreter and the
main() method will be executed. When the line of code containing System.out.println() is reached, “Hello
World!” is sent to STDOUT, which is the computer screen by default, as shown in Figure 5-3.

Figure 5-3: If you have successfully executed the bytecode, “Hello World!” is output.

Congratulations! You’ve just written, compiled, and executed your first Java application. Sure, it’s no
Microsoft killer, but that’ll come in time. In the meantime, let’s take a look at our HelloWorld program
written and executed as an applet.

HelloWorld Applet

Remember: while an application is executed using the Java interpreter and without any need whatsoever
for a Java-savvy browser, applets are executed from within a Java-savvy browser.

Because of this, applets are a little more complicated to get up and running than applications. Not much,
mind you, but a little. For starters, you have to create an HTML file (a Web page) that references the
applet. And you also have to add a few more lines of code to let the Java compiler and runtime system
know these programs are applets and not applications. But once you get the hang of it, you’ll find that
these are really easy steps. Let’s start by taking a look at the directory structure for our HelloWorld
applet.

Applet directory structure

Just as with an application, you’ll need to create a directory to hold the source code file, compiled
bytecode file, and HTML file for your applet. For this project, I created a HelloApplet directory right
alongside the Hello directory created for the application version. Now, directories for both the applet and
application version reside in my master aewcode directory, as can be seen in Figure 5-4. Of course, the
directory structure you choose is completely up to you.

Figure 5-4: Directories for both the applet and application version of HelloWorld should now reside in
your master directory.

file:///F|/books/java%20books/Java%20Bible/ch05/05-04.html (2 of 4)6/26/2005 7:55:57 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

Entering and saving the source

As you did with the application version of this program, you’ll need to type the following source code
and save it in your HelloApplet directory. Because the class we are defining here is called
HelloWorldApplet, you should name the source code file HelloWorldApplet. java. And, just as before, be sure
to include the .java extension when naming the file.

import java.applet.*;
import java.awt.Graphics;
public class HelloWorldApplet extends java.applet.Applet {
public void init() {
resize(200,150);
}
public void paint(Graphics g) i
g.drawString(“Hello World!”, 50,100);
}
}

Once you have entered this code, it must be saved in a plain ASCII text file named HelloWorldApplet. java.
If the class you are defining in an applet does not have the same name as the text file in which you save
it, the compiler spits out an error message. This is because the class for our applet is defined as being
public, meaning the source code tile in which it resides must have the same name.

Suppose, for example, you entered the above code exactly as shown but saved the file as HelloWorldStuff.
java instead. The compiler would abort the mission and give you the following error message:

“Warning: Public class HelloWorldApplet must be defined in a file


called ”HelloWorldApplet.java“

However, if you enter the code exactly as shown and save it in an ASCII text file named HelloWorldApplet.
java you’ll be all set. At this point, the applet is ready to be compiled. But before we do that, let’s take a
look at the new code our applet requires.

Import

Right off the bat, our applet uses two lines of code not seen in the application version:

import java.applet.*;
import java.awt. Graphics;

These are very similar to the #include feature found in C/C++. Here, we are importing classes into our

file:///F|/books/java%20books/Java%20Bible/ch05/05-04.html (3 of 4)6/26/2005 7:55:57 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

applet, methods of which our applet will utilize. The classes are from two different packages supplied
with Java: the applet package and the Abstract Windowing Toolkit (AWT). For more information on
packages, see Chapter 11; for more information on the AWT, see Part IV.

Take another look at the first line of import code:

import java.applet.*;

This import statement tells the compiler to include all classes in the java. applet package. This is done with
the asterisk (*) character, or wildcard. Contrast this with the second line of code:

import java.awt. Graphics;

This line imports only the Graphics class from the AWT package. Here, the class we want to include —
Graphics—is explicitly stated. Together, these two lines will provide our applet with the functionality
every applet requires, as we’ll soon see.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch05/05-04.html (4 of 4)6/26/2005 7:55:57 PM


file:///F|/books/java%20books/Java%20Bible/ch05/images/05-02.jpg

file:///F|/books/java%20books/Java%20Bible/ch05/images/05-02.jpg6/26/2005 7:55:57 PM
Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Class declaration

Unlike the application, the class declaration for our applet is much more involved:

public class HelloWorldApplet extends java.applet.Applet {

We specify the HelloWorldApplet class as being public, an access modifier indicating this class is available
to all other objects regardless of the packages of which they may he part. We also explicitly state that
this applet subclasses another. By extending the class Applet (java. applet. Applet) found in the applet
package, the HelloWorldApplet class inherits the data and behavior in Applet. Because it is a subclass of
the Applet class, HelloWorldApplet can be considered a more specialized version of it.

Contrast this with the application, which does not explicitly extend an existing class. By not specifying a
particular class, HelloWorld became, by default, a subclass of Object. Here, however, we need to inherit
the properties of the previously imported Applet class. All applets must extend this class, and so this code
is essential here and in any other applet you’ll create. The inheritance tree—also known as a class
hierarchy—for HelloWorldApplet is shown in Figure 5-5.

Figure 5-5: The inheritance tree for HelloWorldApplet

Method declaration/overriding

At a minimum, most applets will declare two methods: init() and paint(). These methods already exist in
the Applet class extended by all applets, including our HelloWorldApplet subclass. As a result,

file:///F|/books/java%20books/Java%20Bible/ch05/05-05.html (1 of 4)6/26/2005 7:55:58 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

HelloWorldApplet overrides them. By declaring a method in our class with the same name as one in a
superclass, we replace the superclass’s method with our own. Hence we override the init() and paint()
originally declared in the Applet class with our specialized version of these methods. Let’s take a closer
look at them.

The first method we override, init(), takes no parameters, returns nothing, and is declared public. In fact,
the only thing we do here is instruct the browser window to resize itself to 200 pixels wide and 150
pixels high. The method used to do this, resize(), is part of the Applet class. Because we have imported
this class, we can use its methods:

public void init() {


resize(200,150);
}

The second method we override is paint(), a method which is used by the applet to draw on the screen.
Similar to init(), the paint() method is public and returns nothing. It does, however, take one parameter: a
Graphics object. When called, paint() is passed an object of class Graphics. It uses this object, invoking the
drawString() method contained in it, to draw our ”Hello World!“ string in the browser window at the
location 50,100.

Unlike the System. out. println() code used in our application to output to STDOUT, applets use paint() to
output to the browser window:

public void paint(Graphics g) {


g.drawString(”Hello World!“,50,100);
}

The methods we’ve overridden are quite simple, as you can see, having only one line of executable code
each. And thanks to Java’s automatic garbage collection, we don’t have to worry about disposing of
memory or objects; we simply enter the code and let the Java runtime environment take care of these
memory-management issues.

Compiling

Java applets are compiled exactly as their application counterparts. If you’ve typed the code precisely as
shown and saved it in a file named HelloWorldApplet. java, you should have no problem compiling your
new applet. Enter the following at the command line (where HelloApplet> is the prompt indicating you’re
inside the directory containing the source file):

HelloApplet> javac HelloWorldApplet.java

If the compiler is successful, a binary bytecode file named HelloWorldApplet. class will be created in the

file:///F|/books/java%20books/Java%20Bible/ch05/05-05.html (2 of 4)6/26/2005 7:55:58 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

same directory as your source file. If not, double-check your source code against the listing above and
try again.

Executing the applet

Unlike applications, Java applets cannot be executed directly with the interpreter. If you try, the
interpreter will tell you it can’t find the main() method required for all applications. That’s no surprise,
because we never declared main():

HelloApplet> java HelloWorldApplet


”In class HelloWorldApplet: void main(String argv[]) is
undefined“

To execute an applet, we must first create an HTML file that explicitly references it, using the <APPLET>
tag, and then open that file with a Java-savvy browser. Luckily, this is fairly easy.

Creating an HTML file

Using the same text editor as you did to create your source code files, create a new file and enter the
following:

<HTML>
<HEAD>
<TITLE> Hello World Applet Test </TITLE>
</HEAD>
<BODY>
Here is our applet:
<APPLET CODE=“HelloWorldApplet.class” WIDTH=200 HEIGHT=150> </
APPLET>
</BODY>
</HTML>

When done, save this as a plain ASCII text file with the name TestApplet.html in the same directory as
your new source and bytecode files. You can choose any name you want, but I’ll use this name when
referring to the HTML file.

All the HTML code you see here is standard, plain, vanilla stuff, with the exception of the following line:

<APPLET CODE =”HelloWorldApplet.class“ WIDTH=200 HEIGHT:150>

This is the line of HTML that tells a Java-savvy browser about our applet. The bytecode file is listed in
quotes, as it’s the compiled code that the browser will load and execute. Notice that the entire class

file:///F|/books/java%20books/Java%20Bible/ch05/05-05.html (3 of 4)6/26/2005 7:55:58 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

name and the .class extension is required. If .class is omitted, the applet may not be found (depending on
how the browser you’re using deals with <APPLET> tags). To be safe, and ensure that every Java-savvy
browser out there can find your applet, be sure to include the .class extension. Also, the class name must
match that generated by the compiler exactly (see the section called “HTML case sensitivity” later in
this chapter).

Because our applet is being executed locally, and because it exists in the same directory as the HTML
file, there is no need to specify anything more than the name of the applet class file. However, if our
applet was in a different directory than the HTML file or on the Web, we would need to provide
additional information (see Chapter 7 for details).

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch05/05-05.html (4 of 4)6/26/2005 7:55:58 PM


file:///F|/books/java%20books/Java%20Bible/ch05/images/05-03.jpg

file:///F|/books/java%20books/Java%20Bible/ch05/images/05-03.jpg6/26/2005 7:55:58 PM
file:///F|/books/java%20books/Java%20Bible/ch05/images/05-04.jpg

file:///F|/books/java%20books/Java%20Bible/ch05/images/05-04.jpg6/26/2005 7:55:59 PM
Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

WIDTH and HEIGHT

These two attributes of the <APPLET> tag, both of which are required, instruct the browser to create a
display canvas of these dimensions when first loading the applet. The canvas is where your applet will
be displayed in the browser, and can be controlled from within the applet itself using the resize() method.

For our purposes, the WIDTH and HEIGHT attributes are the same as those used in our applet’s resize()
method, called in init(). We could have two different sets of values, although the resize() method is called
after the HTML file is parsed, effectively overriding the dimensions provided in HTML. By supplying
the same dimensions in HTML as we have in our source code, the canvas remains the same size when
the applet is loaded by the browser as when it was actually executed.

HTML case sensitivity

With the exception of the class name, which must be written exactly and in the same case format as the
bytecode file generated by the compiler, the <APPLET> tag is not case-sensitive. That means you can
write everything in this tag in upper, lower, or even mixed case. I’ve used uppercase for readability,
although you should feel free to do as you wish.

For instance, either of the following three lines of HTML code would be fine:

<APPLET CODE=“HelloWorldApplet.class” WIDTH=200 HEIGHT=150>


<applet code=“HelloWorldApplet.class” width=200 height=150>
<Applet Code:“HelloWorldApplet.class” Width=200 Height=150>

Executing the applet

Because an applet must be executed through a Java-savvy browser or similar environment, such as the
Applet Viewer tool supplied with the Java Developer’s Kit (JDK), we need only load our HTML file
with one to see the results. However, it may not be terribly convenient to repeatedly launch a full-blown
browser (or run it continuously) during the course of development. For this reason, I recommend using
the Applet Viewer program provided with the JDK.

file:///F|/books/java%20books/Java%20Bible/ch05/05-06.html (1 of 3)6/26/2005 7:55:59 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

In practice, Applet Viewer is just as effective, yet executes faster and uses much less memory. To
execute your program with this program, simply provide it with your HTML file:

HelloApplet> appletviewer TestApplet.html

Notice that the entire filename is included, even the .html extension. This is because Applet Viewer
expects the entire filename and will generate an error message if it can’t locate the file you give it.
However, if everything is in order, it will create a window and execute HelloWorldApplet in it. This is
demonstrated in Figure 5-6.

Figure 5-6: If everything is in order, Applet Viewer will create a window and execute
HelloWorldApplet.

Although the Applet Viewer will execute any applets it finds in an HTML file, it won’t display anything
else. If you want to see the page as it will look to the world when placed on the Web (with text, graphics,
hyperlinks, and anything else that’s part of the page, but isn’t generated by an applet) you need to use a
Java-savvy browser such as Netscape’s or Microsoft’s latest beauties.

Living on the Web

Of course, in reality, your applets will be on a World Wide Web server waiting to be executed when
visitors load your pages with a Java-savvy browser. In this case, the HTML file you create may specify
the URLs of remote applets it expects to execute (see the CODEBASE discussion in Chapter 7).

In Chapter 6 we’ll expand on the HelloWorld applet, adding sound and graphics. This new version of
HelloWorld will exist on the Web, and so we’ll also update our source code to better handle life in
cyberspace.

JAR Files

file:///F|/books/java%20books/Java%20Bible/ch05/05-06.html (2 of 3)6/26/2005 7:55:59 PM


Java Bible:Getting Started: HelloWorld Application and HelloWorld Applet

Just as you can use a glass jar to can your tomatoes and peaches, Java Archive ( JAR ) files
can be used to can your Java packages. JAR files store Java packages, classes, and resources in
a compressed form. Because it takes time to download information over the Internet, if you
can cram more information into less space, things will run faster. When adding applets to your
HTML files, the <ARCHIVE> tag is used to specify a JAR file. Chapter 11 reviews the process
of creating JAR files in detail.

Onward and upward

Although the HelloWorld application and applet aren’t much to look at, they have helped us better
understand the Java language and development environment. In fact, you’ve actually created two
platform-independent programs, one of which, the applet, is capable of living on the Web. Not bad,
considering it only took a handful of code.

In Chapter 6 we’ll build upon this to get a better understanding of how to debug Java programs. We’ll
also upload the final applet to the Web, accessing it from there, instead of from our hard drive. And so,
it’s onward and upward with HelloWorld, but it’s goodbye for now.

Summary

In this chapter we examined these topics:

• Creating Java applications and applets, using a basic HelloWorld example


• Executing Java applications
• Using the HTML <APPLET> tag to include a Java applet on your Web page
• Executing Java applets using your Web browser

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch05/05-06.html (3 of 3)6/26/2005 7:55:59 PM


file:///F|/books/java%20books/Java%20Bible/ch05/images/05-05.jpg

file:///F|/books/java%20books/Java%20Bible/ch05/images/05-05.jpg (1 of 2)6/26/2005 7:55:59 PM


file:///F|/books/java%20books/Java%20Bible/ch05/images/05-05.jpg

file:///F|/books/java%20books/Java%20Bible/ch05/images/05-05.jpg (2 of 2)6/26/2005 7:55:59 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

CHAPTER 6
Extending, Enhancing, Debugging, and Uploading
In This Chapter

Determining when to extend or enhance existing Java classes or develop your own

A step-by-step guide to extending the HHelloWorldApplet class

How to create and document your classes

Debugging and testing your Java applications and applets

Having completed simplistic examples, HelloWorld it’s time to improve on the work we’ve started. In
this chapter, we’ll add an image and soundtrack to the HelloWorld applet. In doing so, we’ll see how
classes are extended (subclassed) in Java and get to know the debugging process. Finally, we’ll learn
how to upload our new creations onto the Web, for the world to admire.

Let’s first consider a question you’ll ask yourself often when using Java: Enhance or extend?

To Enhance or Extend?

When you develop software in any object-oriented programming (OOP) language, you’ll often ask
yourself whether the task or program at hand should enhance existing classes or extend them to create
more specialized subclasses. In large programs, you’ll often do both.

To enhance an existing class means to add new variables or methods to that class. To extend a class
means you create a subclass that will contain new variables or methods while the superclass itself
remains untouched. That is, you add your variables and/or methods to the subclass (perhaps even
overriding methods in the superclass) to get the behavior you want, without changing a line of code in
the superclass.

file:///F|/books/java%20books/Java%20Bible/ch06/06-01.html (1 of 4)6/26/2005 7:56:00 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Whether to enhance or extend depends a great deal on what it is you want to do. To make this decision,
you need to have a clear understanding of the class itself. You need to ask yourself two basic questions:

1. Does the class have the essential data and behavior I need, and would it be easy to add to it?
2. Does the new functionality I want to add apply to all instances of the class, or just some?

If the functionality you want to add applies to the entire class (in other words, all instances require such
functionality) and is easy to fit in with the class’s existing data and behavior, then it’s a good candidate
for enhancing. If it lacks much of the data or functionality you require, or the new functionality only
applies to some of the instances of the class, it may be easier to extend it by creating a new subclass.

Be very cautious when attempting to enhance a class. What you are actually doing is rewriting it.
Therefore, you must take great care not to alter the interface it currently supports for interacting with
other objects, lest you “break” the class. If you change the way in which it interacts with other objects,
either by substantially changing its variables and/or methods, the integrity of the class will be
compromised and any programs or classes relying on it will suffer.

While the decision to enhance or extend is made on a case-by-case basis, you’d do well to consider
extending a class whenever possible. This, after all, is one of the key reasons OOP is so powerful. You
don’t have to go in and rewrite functions and data structures every time you need new functionality. You
can simply create a subclass, inheriting all the data and behavior of the superclass, and add any
specialized data and behavior without worry.

We can accomplish our task—adding sound and graphics to the HelloWorld applet we created in the
previous chapter—by either enhancing or extending the HelloWorldApplet class. However, to help us
become more comfortable with the concept of extending a superclass to inherit its state and behavior,
we’ll concentrate on extending HelloWorldApplet. As we go through the example, you’ll see the new code
that would have to be added to this class, were we not to extend it.

Extending the HelloWorldApplet class

Because we’re going to extend the class, we need to create a new ASCII text file for the source code in
Listing 6-l, which will then be compiled and executed. Create a new file using whatever text editor you
prefer, enter the source code, and then save it in the same directory as HelloWorldApplet.

Listing 6-1: MediaHelloWorld.java source code

import java.applet.*;
import java,awt.*;
/**

file:///F|/books/java%20books/Java%20Bible/ch06/06-01.html (2 of 4)6/26/2005 7:56:00 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

* MediaHelloWorld applet, an extension of the HelloWorld applet.


* Displays “Hello World!” string in applet canvas while a
* background audio track plays and an image follows the mouse *
around.
*
* @author Aaron E. Walsh
* @version l.o, l2 Jan 98
*/
public class MediaHelloWorld extends HelloWorldApplet (
Image myImage;
AudioClip myAudio;
int horizontal, vertical;
boolean SoundOn = true;

public void init() {


super. init();
myImage:getImage(getCodeBase(), “images/world.gif”);
myAudio=getAudioClip(getCodeBase(), “audio/hello.au”);
}
public void paint(Graphics g) {
if (myImage !=3D null) { /* only draw if the variable contains
data! */
g.drawImage(myImage, horizontal, vertical, this);
}
super.paint(g);
}

public void start() {


myAudio.loop();
}

public void stop() {


myAudio.stop();
}

public boolean mouseDown(java.awt. Event event, int x, int y)


{
if (SoundOn) {
myAudio.loop();
SoundOn = false;
}
else {
myAudio. stop();

file:///F|/books/java%20books/Java%20Bible/ch06/06-01.html (3 of 4)6/26/2005 7:56:00 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

SoundOn = true;
}
return true;
}

public boolean mouseMove(java.awt. Event event, int x, int y)


{
horizontal=x;
vertical:y;
repaint ();
return true;
}
}

Name your new file MediaHelloWorld.java. Be sure to include the .java extension or the compiler won’t be
able to find it.

Because MediaHelloWorld extends our HelloWorld applet, the javac compiler must be able to access the
HelloWorldApplet class in order to successfully compile MediaHelloWorld. This is why I’ve suggested
that you place your MediaHelloWorld.java source code file in the same directory as HelloWorldApplet.
However, as long as it’s in the class path (specified by the class path environment variable or using the
classpath compiler option), any applet you create can extend HelloWorldApplet. See Chapter 4 for details on
how to properly configure classpath for your system.

At this point, you should also create two new directories inside the same directory as your source code:
audio and images. The audio directory will contain the sound file, and images will hold the GIF file used in
this example. To make things easier, you can simply copy these directories and files from the CD-ROM
included with this book. Refer to Appendix C for the details about where these are located.

Java versions prior to version l.2 only support Sun’s AU (•law) audio format. If you’re using an earlier
version of Java, you have to save sound files as 8-bit •law, 8KHz, with only one channel. To convert
existing sound files to the AU format, use the audio tool application if you’re a Sun workstation user, or
the shareware program GoldWave on the enclosed CD-ROM if you’re a Windows user. To save a sound
file in the AU format using GoldWave, use the File-Export command.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch06/06-01.html (4 of 4)6/26/2005 7:56:00 PM


file:///F|/books/java%20books/Java%20Bible/ch05/images/05-06.jpg

file:///F|/books/java%20books/Java%20Bible/ch05/images/05-06.jpg6/26/2005 7:56:00 PM
Java Bible:Extending, Enhancing, Debugging, and Uploading

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

JDK 1.2 includes a number of audio enhancements, including a new sound engine and support
for audio in applications as well as applets. Java Sound now supports the AIFF, AU, and WAV
audio file formats. It also supports these MIDI-based song file formats: TYPE o MIDI, TYPE
1 MIDI, and RMF. Java sound can render 8-bit or l6-bit audio data in mono or stereo, with
sample rates from 8KHz to 48KHz.

The source code in Listing 6-1 is bug-free, meaning it should compile without a hitch, assuming it
resides in the same directory as the HelloWorldApplet class (HelloWorldApplet.class) or as the source file
(HelloWorldApplet.java). When the Java compiler is run on your new source file, it will look for
HelloWorldApplet.class, because that class is extended. If it can’t locate HelloWorldApplet.class, the compiler
will look for the HelloWorldApplet. java source file and compile it, if it’s available. If successful, the
compiler will create a new class named MediaHelloWorld.class.

If the compiler insists that it can’t find the HelloWorldApplet class, be sure that it (or the HelloWorldApplet.
java source code file) is inside the same directory as your new MediaHelloWorld. java file. If it’s not, or
isn’t in the class path at all, the compiler won’t be able to find it.

If you’re sure the file is in the correct place, and the compiler still can’t find it, double-check the
CLASSPATH environment variable to ensure that you set it properly.

Make sure that your CLASSPATH environment variable not only points to Java’s classes, zip
archive, which contains all the standard class files, but also includes the “current directory.” In
Windows, you do this by supplying a period and semicolon, followed by the full path leading
to the .zip archive (.; C: \java \ lib \ classes. zip). With UNIX systems, you use a period and colon
to specify the current directory (.: /java /lib/classes. zip).

If both HelloWorldApplet.class and its source, HelloWorldApplet.java, are missing, the compiler will tell you
so:

MediaHelloWorld.java:11: Superclass HelloWorldApplet of class


MediaHelloWorld not found.
public class MediaHelloWorld extends HelloWorldApplet {

file:///F|/books/java%20books/Java%20Bible/ch06/06-02.html (1 of 4)6/26/2005 7:56:01 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

^
1 error

A class, such as HelloWorldApplet.class, will be accessible to your Java programs if it resides in


the same directory as the program itself (or the source code you intend to compile). It will also
be accessible if it resides in the directory specified by the CLASSPATH environment variable. If
you develop a class that’s likely to be used by more than one program, make sure that you
place it in the directory specified by CLASSPATH, so that it’s universally accessible to all Java
programs that might need it.

Stepping Through the Code

In this section, we’ll step through each new part of the source code shown in Listing 6-l to give you a
better idea of what each new variable and method does. In the process, we’ll get a better feel for how
subclasses communicate with their superclass through use of the super object.

Importing classes

To begin with, let’s take a look at the classes our new program imports:

import java.applet,*;
import java.awt.*;

These two lines of code are very similar to those found in HelloWorldApplet.java. Because we’re creating
an applet, we need to import the base Applet class. This is accomplished with the first import statement,
which every applet must include.

In addition to the basic applet functionality our program requires, the Applet class also provides the
AudioClip interface we’ll use to load and play a sound track.

The second import statement, however, is slightly different from its HelloWorldApplet.java counterpart.
Here, we instruct the compiler to import classes in the awt package, not just the Graphics class imported in
HelloWorldApplet. Because this applet requires additional classes found in awt, specifically those that deal
with the Image object, we import all classes in the awt package.

With these two lines of code, all of the classes our applet relies on are imported into the program. If we
had required additional classes, we could have imported them in precisely the same way as we imported
the Applet and awt classes.

Documentation comments

file:///F|/books/java%20books/Java%20Bible/ch06/06-02.html (2 of 4)6/26/2005 7:56:01 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Following the import command is a special comment, created to help developers generate
documentation:

/**
* MediaHelloWorld applet, an extension of the HelloWorld applet.
* Displays “Hello World!” string in applet canvas while a
* background audio track plays and an image follows the mouse *
around.
*
* @author Aaron E. Walsh
* @version l.o, l Jan 98
*/

This comment looks and acts in a similar way to the standard C comment, although an extra asterisk (*)
is added to the beginning and special variables are included.

Inside a document comment, the @ character specifies special variables that are used when generating
documentation with the javadoc tool. In this example, the author and applet version have been specified.

You can place document comments before any class or method declaration to serve as standard human-
readable comments ignored by the compiler. In addition, you can use comments to help automate the
document-creation process and take some of this burden from the programmer.

Class declaration

The MediaHELLoWorld class declaration follows the documentation comment. Unlike our original
HelloWorld applet, which extended the Applet class, MediaHElloWorld extends the HelloWorldApplet class:

public class MediaHelloWorld extends HelloWorldApplet {..}

By extending the HelloWorldApplet class, MediaHelloWorld inherits all data and behavior in that class.
Although there isn’t much to inherit—only the capability to output “Hello World!”—you’ll soon see
how powerful this ability to subclass an existing class is. Prod because we’ve inherited all the traits of
HelloWorldapplet, we automatically get the functionality found in class Applet.

Variables

Next, the variables used in MediaHelloWorld are declared. Although these variables could have been
declared anywhere inside the body of our class (with the exception of inside a method declaration), as
long as they appeared before first being used, I’ve placed them here for easy reading:

Image myImage:

file:///F|/books/java%20books/Java%20Bible/ch06/06-02.html (3 of 4)6/26/2005 7:56:01 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

AudioClip myAudio;
int horizontal, vertical;
boolean SoundOn = true;

The most significant variables are those that will actually hold our graphic and sound data: my Image and
myAudio. The others aren’t nearly as interesting, but are every bit as necessary. The horizontal and vertical
integer objects will hold the mouse coordinates, because our image will be drawn wherever the mouse
moves. In addition, a boolean object Soundon is declared and set to true. This variable keeps track of
whether or not the sound clip should be played; it’s necessary because a mouse click in our applet
toggles the audio off and on.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch06/06-02.html (4 of 4)6/26/2005 7:56:01 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Methods

Six common methods are often overridden when you create your own applets. They are init(),getCodeBase
(), paint(),start(), stop(),mouseDown(), and mouseMove(). Let’s take a close look at the function of each of
these methods.

init()

MediaWorldApplet overrides six methods, beginning with init (), which all applets override:

public void init() {


super.init();
myImage:get Image(getCodeBase(), “images/world.gif” );
myAudio=getAudioClip(getCodeBase(), “audio/hello.au”);
}

However, this init () method is quite different than the one we created for HelloWorld Applet . In that one,
we simply resized the applet canvas in which our “Hello World!” string was to be drawn. Here, things
are quite different. Although MediaWorld Applet does, in fact, resize the applet canvas, it does so by
invoking the init () method in its superclass:

super.init();

By executing the init() method of MediaWorldApplet’s superclass, as this line of code does,
HelloWorldApplet’s init () is called! Sure, the only thing it does is resize the applet canvas, but the point is
that we were able to execute the init() method of the superclass without having to duplicate code. It’s not
a drastic saving in code in this example, but it could be tremendous in others.

file:///F|/books/java%20books/Java%20Bible/ch06/06-03.html (1 of 4)6/26/2005 7:56:01 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Although Sun’s Applet Viewer supports the resizing of the applet canvas, there’s no guarantee
that every Java-savvy Web browser will do the same. As a result, you shouldn’t rely on resize()
working correctly when it’s called. However, every <APPLET> tag is required to include both a
HEIGHT and WIDTH attribute. Every Java-savvy browser will use the values supplied through
these attributes to automatically set the size of an applet’s canvas when it is first executed.

It doesn’t matter how much or how little code we’re saving in this example i it could be millions of lines
or just one—the end result is that our new applet doesn’t have to duplicate effort. We inherit the
variables and methods we’ve already created in HelloWorldApplet, and we can access them from our new
class thanks to the super object. As you can see in the paint() method, we don’t even have to bother
rewriting the code that outputs “Hello World!.” (For an explanation of super, see the “Odds ’n’ Ends”
section at the end of this chapter.)

You should note that in Java, two special keywords, this and super, are used to refer to the current object
(this), and its superclass (super). Because you’ll make regular use of this and super in your Java programs,
they are described in the “Odds ’n’ Ends” section later in this chapter, and explained in detail in Chapter
11.

The next two lines in init() retrieve the image and audio data and place it in the appropriate objects.
Actually, the data isn’t loaded at this time! Only when an image is drawn, or a sound file played, does
the download take place. After all, why load the data if it never gets used?

getCodeBase()

The two methods get Image() and getAudioClip() are courtesy of classes imported into our program. They
both rely on another method, getCodeBase(), also made possible thanks to the imported Applet class (see
the “Getting to Base” sidebar).

Getting to Base

Many applets use external data (such as graphic images and audio files) that may be stored outside of the
directory in which the applet resides, so there must be a way to tell the applet where these files are. This
is quite easy, thanks to two methods implemented in the Applet class: getCodeBase() and getDocumentBase().
Both methods return a URL object, which is used to tell the applet where the external data files reside:

public URL getCodeBase() returns the “base” URL for the applet itself. Use this method if your external
data files are stored relative to the actual applet, not the HTML document it is embedded in.

public URL getDocumentBase() returns the URL for the actual document in which the applet is embedded.
Use this method if your external data files are stored relative to the HTML document

file:///F|/books/java%20books/Java%20Bible/ch06/06-03.html (2 of 4)6/26/2005 7:56:01 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

These methods are extremely useful because they enable your applet to locate files relative to itself or to
the HTML document in which it is embedded. They work in both local and networked environments, so
it doesn’t matter if-four applet is executed from your hard drive or the World Wide Web. Thanks to
getCodeBase () and getDocument Base(), your applet will be able to find the files it needs regardless of where
it is executed, assuming these files are located relative to the class when using getCOdeBase(), or to the
HTML document when using getDocumentBase().

Later in this chapter, you’ll upload the compiled MediaWorldApplet class and associated audio and image
files to your Web server. And because we use getCodeBase () to reference these files, Java will be able to
locate them as easily as when the applet is executed locally.

paint()

Next, we override the paint () method:

public void paint(Graphics g) {


if (myImage !=3D null) { // only draw if the variable
contains data!
g.drawImage(myImage, horizontal, vertical, this);
}
super.paint(g);
}

This implementation uses drawImage() to draw the graphic at the specified horizontal and vertical position
on the applet canvas. These variables set the location of the mouse and are set in the mouseMove() method
overridden later in the program. Of particular interest, however, is the parameter this, which refers to the
current object.

The drawlmage() method, described in detail in Chapter l7, takes as its last argument an Imageobserver
object. Image observers are responsible for keeping track of images as they are loaded, a process which
can take a long time when loading over a network. However, because applets themselves can act as
Imageobserver objects, you don’t have to instantiate them yourself in most cases.

Instead, you can pass a reference to the applet using the keyword this. Because this refers to the current
object, which is the applet itself, you can get by without bothering to instantiate an Imageobserver object.
(For a detailed explanation of this, see the “Odds ’n' Ends” section later in this chapter.)

After drawing the image, we call the paint() method of our superclass with the line:

file:///F|/books/java%20books/Java%20Bible/ch06/06-03.html (3 of 4)6/26/2005 7:56:01 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

super.paint(g);

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch06/06-03.html (4 of 4)6/26/2005 7:56:01 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

This outputs “Hello World!” to the applet canvas, just as it did in class Hello WorldApplet, where it was
declared. Because “Hello World!” is output after we draw the image, it appears over the image itself. If
you want the image to be drawn over the text, simply reverse the order of these two lines.

start() and stop()

Although the init() and paint() methods should be familiar to you by now, the remaining code overrides
several methods that HelloWorldApplet did not. The first two, start() and stop(), are used to begin and end
our audio sound track, which is referenced by myAudio after init() is called.

When the applet is begun, start() is called, it is here that we execute the loop() method declared in the
Audioclip class. When the applet is terminated (this occurs when the user unloads the Web page in which
the applet is embedded), stop() is invoked. It is here that we execute the stop() method for AudioClip,
which interrupts the looping sound track:

public void start()


myAudio.loop();
}

public void stop()


myAudio.stop();
}

These two methods are commonly overridden by applets, because they provide a mechanism for applets
to begin and end their activities in response to the user loading and unloading the Web page in which the
applet is embedded. For more information on start() and stop() and the three additional methods often
overridden by applets, see “Fundamental applet methods” in the “Odds ’n’ Ends” section at the end of
this chapter.

mouseDown() and mouseMove()

Until now, our program has only overridden methods that are called when the applet is first executed or

file:///F|/books/java%20books/Java%20Bible/ch06/06-04.html (1 of 4)6/26/2005 7:56:02 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

terminated. (The init(), paint(), and start() methods are called when the applet is executed; stop() is an
example of a method that is automatically called when the document containing the applet is unloaded.)
We haven’t, at this point, established a mechanism to interact with the user.

The final two methods we override do just that. By overriding mouse Down () and mouseMove(), declared
in the Component class (java. awt. Component, to be exact, imported as part of the entire awt package), we
give our applet the ability to respond to the user’s mouse activity:

public boolean mouseDown(java.awt. Event event, int x, int y) {


if (SoundOn) {
myAudio.loop();
SoundOn = false;
}
else {
myAudio, stop();
SoundOn = true;
}
return true;
}

public boolean mouseMove(java.awt. Event event, int x, iht y) {


horizontal=x;
vertical=y;
repaint();
return true;

Both methods have the same parameter list and return aboolean, sharing the same basic method signature:

public boolean methodname (Event evt, int x, int y) { ... }

Event is a class that encapsulates events from the local Graphical User Interface (GUI) platform, such as
mouse and keyboard characteristics. The x and y parameters of each method specify the horizontal and
vertical coordinates of the mouse at the time the method is invoked. Both methods must return true if the
event is handled appropriately, meaning it should not be passed along for further processing. Because
the buck stops with us, we return true in each case to prevent a parent component from also executing its
mouseDown () and mouseMove() methods.

In mouseDown (), we do nothing whatsoever with the parameters passed to us. Instead, we simply
determine whether the audio track should be started or stopped, based on the Soundon variable, and act
accordingly. It is here that we toggle the value of Soundon, allowing the user to start and stop the
soundtrack by clicking the mouse in the applet canvas.

file:///F|/books/java%20books/Java%20Bible/ch06/06-04.html (2 of 4)6/26/2005 7:56:02 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Our implementation of mouseMove(), however, does use a portion of the parameter list. Although we
ignore Event, x and y are used to set our horizontal and vertical variables. These two variables specify the
coordinates where our image is drawn. Because we want the image to “follow” the mouse around, we
immediately call repaint() to ensure our paint() method is called each time the mouse moves. The result is
shown, frozen in time, in Figure 6-l.

Figure 6-l: MediaHelloWorld, residing locally, as executed by Applet Viewer

And that’s MediaHelloWorld in its entirety. Before we begin the debugging process, you may want to
run the program and tinker with the code. Because the code we’ve stepped through here is bug-free, it
should compile and execute without a hitch. Of course, you’ll have to create a new HTML file to
execute first.

I strongly recommend developing and testing your applets using Applet Viewer initially,
moving on to a Java-savvy Web browser when you’ve worked out all the kinks. Applet Viewer
is fast, takes up less memory, and doesn’t cache applets as a Web browser might. As a result,
you can guarantee that Applet Viewer will load your applet class fresh every time it is
executed.

If you use a Web browser that happens to cache files by default, as Netscape Navigator does, you’ll have
to flush the cache or quit the browser and start anew each time you want to execute a freshly compiled
class. In fact, many programmers who use Netscape Navigator exclusively can’t understand why their
applet won’t work as expected, even after substantial changes to the source code. Most of the time it’s
because their particular Java-savvy browser is running an old, cached version of their applet instead of
the freshly compiled one!

Creating the HTML file

Just as you created an HTML document for the HelloWorld applet, you must create one for
MediaHelloWorld. Simply create a plain ASCII text file with the following contents, and save it inside
the directory in which your compiled MediaHelloWorld class resides:

<HTML>
<HEAD>
<TITLE> MediaHelloWorld Applet Test </TITLE>

file:///F|/books/java%20books/Java%20Bible/ch06/06-04.html (3 of 4)6/26/2005 7:56:02 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

</HEAD>
<BODY>
Here is our MediaHelloWorld applet:
<APPLET CODE=MediaHelloWorld.class height:l50 width=200> </APPLET>
</BODY>
</HTML>

After you’ve saved the above HTML code as a text file, you’re ready to execute the applet embedded in
it. For the purpose of this section and the next, I’ll assume you’ve named the HTML file TestMediariello.
html. If you use this name, you simply enter the following command line to execute the applet using the
Applet Viewer program:

appletviewer TestMediaHello.html

This, of course, assumes the HTML file is located locally. You can also use Applet Viewer to execute
applets on the Web by providing a URL to the HTML document, instead of its name:

appletviewer
<http://www.manti scorp.com/books/java/found/TestMediaHello.html>

This will come in handy when you want to test pages after you’ve placed them on the Internet, as
described in “Making Applets Live on the Web” later in this chapter. If you’re anxious to get on the
Web, feel free to jump ahead.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch06/06-04.html (4 of 4)6/26/2005 7:56:02 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Botching the Code

Code that compiles perfectly doesn’t help you understand the debugging features of Java, however, so
let’s screw it up a bit. The source code in Listing 6-2 is a version of MediaHelloWorld (originally found in
Listing 6-l) with a slippery little problem that will give us a good opportunity to work with the Java
debugger.

Listing 6-2: A buggy version of MediaHelloWorld.java

import java.applet.*;
import java.awt.*;

public class MediaHelloWorld extends HelloWorldApplet {


Image myImage;
AudioClip myAudio;
int horizontal, vertical;
boolean SoundOn = true;

public void init() {


super.init();
myImage=getImage(getCodeBase(), “images/world.gif”);
myAudio=getAudioClip(getCodeBase(), “audio/hello.au”);
}

public void paint(Graphics g) {


if (myImage !=3D null) { /* only draw if the variable
contains
data! */
g.drawImage(myImage, horizontal, vertical, this);
}
super.paint(g);

file:///F|/books/java%20books/Java%20Bible/ch06/06-05.html (1 of 5)6/26/2005 7:56:02 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

}
public void start()
myAudio.loop();
}

public void stop()myAudio.stop();


}
public boolean mouseDown(java.awt. Event event, int x, int y)
{
if (SoundOn) {
myAudio.loop();
SoundOn = false;
}
else {

myAudio.stop();
SoundOn : true;
}
return true;
}

public boolean mouseMove(java.awt. Event event, iht x, int y)

horizontal:x;
vertical=x;
repaint();
return true;
}

Can you see the error in Listing 6-2? How about if you compare it to Listing 6-l7 Because the entire
body of code for this applet is relatively short and clean, you can probably spot the error immediately.
But if you can’t find it right off the bat, here’s a clue: When executed, the image doesn’t follow the
cursor around as it once did. Specifically, when you move the mouse, the image isn’t painted on the
screen at the same coordinates as the cursor.

The source code for both HelloWorld and MediaHelloWorld are provided on the CD-ROM
included with this book, as are all source code examples. If you want to save yourself the
effort of typing, simply refer to Appendix C for details on where these files are located. Open
them with any text editor and then save them to your local hard drive.

file:///F|/books/java%20books/Java%20Bible/ch06/06-05.html (2 of 5)6/26/2005 7:56:02 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

The bug I’ve introduced to this code is really just an oversight, something you might do when tired or
rushed to finish a program. And, unless you go through the code line by line, it’s tough to find, because
the compiler doesn’t know there’s a problem. But there is one, and it’s in the mouseMove() method:

public boolean mouseMove(java.awt. Event event, int x, int y) {


horizontal:x;
vertical=x; // here’s the little bugger...
repaint();
return true;
}

Instead of setting the vertical variable to y, as it should be, I’ve set it to x. Sure, we don’t need a debugger
to find this; with a little effort we’d find it ourselves. After all, with such a short code listing, where
could it hide? But it will serve our purpose and give us a chance to use the debugger, in preparation for
times when we can’t hunt down a bug just by scanning through the source code.

Be warned

If I’ve sounded like a Java zealot so far, it’s because I absolutely love the language and what it’s done
and will do for network-centric computing. But as much as I love Java, I hate the debugger that comes
with the JDK (intensely, with the white-hot intensity of a thousand fiery orbs in the sky). Alas, Sun—the
company that blessed us with the Java language—also bestowed upon us the jdb debugger.

The jdb debugger is about as bare-boned as you can get. It is, in fact, written in Java just as the Hot Java
browser is. But what makes it unbearable isn’t the fact that it’s entirely command-line based (something
DOS and UNIX programmers won’t mind at all), or that it lacks the ability to set conditional breakpoints
(such as, “break when x exceeds 100”). No, I can live with these things. What I can’t bear is how terribly
unstable the debugger can be at times.

So why would I tell you to use the jdb? So you can share my pain? No. In fact, I suggest you don’t use
it, if at all possible. If you’re serious about debugging, or plan to make extensive use of Java, you
shouldn’t rely on the JDK alone. Instead, I’d highly recommend a full-fledged Java development
environment from a company that specializes in development tools. Borland, Symantec, and Metrowerks
all have superior Java development environments that will free you from the shackles of the JDK’s
limited toolset.

Perhaps you’ll become fast friends with jdb and drop me a few lines of flamemail to tell me how wrong
I was to deride this virtuous tool. Fire away: aacon@ mantiscorp.com. I hope that’s the case, truly, but in
my experience and that of everyone I’ve dealt with who uses the jdb, you’re more likely to join our
“Programmers Who Love Java but Hate the JDB Support Group” than to defend it.

And there’s another reason I’ve decided to include this section. Over time, I’ve gathered a few tips and

file:///F|/books/java%20books/Java%20Bible/ch06/06-05.html (3 of 5)6/26/2005 7:56:02 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

warnings that, if followed, can bring some stability to the product, which you’ll find throughout the
remainder of this chapter. Because you may indeed need to use the jdb from time to time, employing
these suggestions can make your experience more rewarding.

But enough with the warnings already; on with the show. . .

Stages in debugging your code

After you insert the bug and recompile the code, you have to follow several steps to properly find that
annoying bug:

1. Invoke the jdb debugger.


2. Get the applet running.
3. Issue debugging commands.
4. Start your search.
5. Check the source code.
6. Resume program execution.

If there’s still a problem:

1. Step through the code.


2. Clean your house.

Recompile the source code

To run through this exercise, you don’t need to bother entering the source code from scratch. Instead,
just change the one line in mouseMove() that introduces the bug we’ll be tracking:

vertical=x;

Once you’ve slipped this change into your code, you’ll need to recompile it. But you need to do more
than just a straight compile; you need to instruct the compiler to include line numbers and information
about local variables when it generates a class file. By default, the javac compiler only generates line
numbers. To generate information about local variables, you must use the - g option when compiling:

> javac -g MediaHelloWorld.java

By invoking this option, you’ll be able to see the local variables and their values when debugging. And,
because we need to inspect the variables our program uses to see what’s happening, this option is a
necessity.

file:///F|/books/java%20books/Java%20Bible/ch06/06-05.html (4 of 5)6/26/2005 7:56:02 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch06/06-05.html (5 of 5)6/26/2005 7:56:02 PM


file:///F|/books/java%20books/Java%20Bible/ch06/images/06-01.jpg

file:///F|/books/java%20books/Java%20Bible/ch06/images/06-01.jpg6/26/2005 7:56:03 PM
Java Bible:Extending, Enhancing, Debugging, and Uploading

X
Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Invoke the jdb debugger

As with the other JDK tools, the jdb debugger is entirely text-based, controlled by issuing commands on
the command line. UNIX developers will recognize it as being very similar in nature to the dbx or gdb
debuggers often used on that platform.

When invoked, the jdb actually starts the Java interpreter and “attaches” itself to it. As a result, you can
supply jdb with any of the options the interpreter itself can handle: jdb simply passes such options over
to the Java interpreter. In addition, you can execute the Applet Viewer in a debugger mode, which will
invoke the jdb for you. This is the option we’ll use, because our program is an applet and needs to be
debugged as such:

appletviewer -debug TestMediaHello.html

If all goes according to plan, the debugger will be invoked and you’ll be staring at a command-line
prompt, from which you can enter jdb commands. If, however, you see something similar to the error
message shown in Figure 6-2, you’ll have to ensure that a connection to the lnternet has been established
and try again. In this case, simply connect as you usually do when surfing the Web with a browser, and
then return to the command line and issue the above command again.

Figure 6-2: The jdb requires that you first establish a connection to the Internet before it will execute.

Issue debugging commands

Once invoked, the jdb waits around for a command. For a list of the commands it understands, enter
help (or ?) or refer to Table 6-1. The first command we’ll issue is run to get the applet running.

file:///F|/books/java%20books/Java%20Bible/ch06/06-06.html (1 of 5)6/26/2005 7:56:03 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Table 6-1
jdb Options and Commands

1 Description
Options
-host hostname Sets the name of the host machine of the interpreter session you want to
debug.
-password password “Attaches” the jdb to the current interpreter session, which must have
been revoked with the -debug option, causing it to generate a password.
Without this password, the debugger won’t be able to attach to the
interpreter.

Commands

!! When used, these two characters are replaced by the text of the previous
command. When followed by additional text, that text is appended to the
end of the previous command.

catch [exception Sets a breakpoint for the specified exception; whenever the exception is
classname] thrown, jdb will break. Displays all exceptions currently being caught, if
one isn’t specified (see ignore).

classes Prints a list of all loaded classes.

Clear [Class: line] Removes breakpoint for a specified line in the class. Displays all current
breakpoints (along with line numbers), if one isn’t specified.

cont Resumes program execution.

down [number] Moves down a number of frames in the current thread’s call stack(stack
frame). The default is one frame (see up).

dump object Prints the instance variables of a given object. Objects may be specified
by their hexadecimal IDs or by their names.

Note: When a class you’d like to dump isn’t loaded, you must provide its
full name (such as Java.awt.Button). When a class is already loaded,
however, you can specify a partial name (such as Button).

file:///F|/books/java%20books/Java%20Bible/ch06/06-06.html (2 of 5)6/26/2005 7:56:03 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

exit (or quit) Terminates the current jdb session.

gc Forces garbage collection (reclaims unused objects, freeing memory).

help (or ?) Displays a list of commands the debugger understands, along with a brief
description of each.

ignore exception Turns off the catch mechanism for the specified exception, preventing it
classname from being treated as a breakpoint (by default, exceptions that aren’t
caught are treated as a nonrecoverable breakpoints).

list [line number] Lists the specified line of code (and several before and after it), or the
current thread’s stack frame if no line number is provided (see use).

load Loads the specified class.

locals Displays locals variables for the current stack frame.

Note: Code must be compiled using -g option

memory Displays amount of memory being used by the current program.

methods classname Prints all methods for the specified class.

next Steps one line-steps over calls.

print object Prints a Java object, calling that object’s toString() method in order to
properly format the output. You can print objects by specifying their IDs
or names.

Note: When a class you’d like to print isn’t loaded, you must provide its
full name (such as java. awt. Button). When a class is already loaded,
however, you can specify a partial name (such as Button).

file:///F|/books/java%20books/Java%20Bible/ch06/06-06.html (3 of 5)6/26/2005 7:56:03 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

resume [threads] Resumes execution of the specified thread(s); resumes or suspends threads
if none are specified (see suspend).

run [classname] Executes the main () method in the specified class. Any arguments
[arguments] specified - which can be any of those supported by the java interpreter-are
passed to the class.

step Executes the current line of code, and then stops program execution.

stepi Executes the current instruction.

stop [at Classname: Sets a breakpoint at the class’s specified line of code or for the specified
line] [in classname. method. Displays all breakpoints, if neither are supplied.
method]

suspend [threads] Suspends the specified thread(s), or all threads if none are specified (see
resume).

thread theard Sets the current thread.

threadgroup Sets the current thread group.


groupname

thread group. Lists all thread groups in the current debugger session.

threads Lists the current threads in the default thread group, if a thread group is
[threadgroups] specified.

up [number] Moves up a number of frames in the current thread’s call stack (stack
frame). The default is one frame (see down).

use [path] Sets the path jdb will use to locate source files (the default is the path
specified by classpath). If no path is specified, it outputs the path.

Where [thread] Prints the stack of a specific thread (or the current thread, if one isn’t
specified). Prints the stack trace for all threads when the all option is
specified.

file:///F|/books/java%20books/Java%20Bible/ch06/06-06.html (4 of 5)6/26/2005 7:56:03 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

wherei [threadid] [all] For PC platforms only. Prints the stack of a specific thread - providing PC-
specific information.

1
When a class file is specified when jdb is invoked, any of the Java interpreter options may be
supplied. However, when “attaching” to an existing interpreter session, only these two options are
available.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch06/06-06.html (5 of 5)6/26/2005 7:56:03 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

X
Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

If there’s still a problem...

But suppose you didn’t realize the improper variable assignment, even though it’s obvious by looking at
the code listing. Hey, it can happen. A few weeks of long nights and non-stop pressure to get a product
out the door can do strange things to your eyes and mind. You might look straight at the error, but still
get the message that “everything looks just fine here.” One way to find errors is to walk through your
code while it’s running, one line at a time: See the “Stepping Lightly” sidebar next for more information
on intelligently walking through your code.

Stepping Lightly

When stepping though code, it’s possible that you may lose your “place” in the program. Thanks to
threading, many things are going on at once in a Java program, and a thread may have a shot at
executing during the time you’re stepping from one line to the next. in this case, you won’t be able to
see the source code or print variables for your method!

What you must do is return the debugger to your method, so you’ll have access to your source and
variables. To do so, you must first find out where you are:

> where

The where command displays a stack trace for the current thread. The frame of the stack you are
currently in is displayed on the jdb command line in square brackets:

AWT-Call back Win32[1]

In the above example, the current thread is AWT-Callback-Win32 and the frame is 1. However, if
you’re in a frame other than the one containing your method, you won’t be able to do much of anything.
In that case, you must use the up or down commands to ensure the jdb command line is at the same frame
as the one containing your method. This process is shown in Figure 6-6.

file:///F|/books/java%20books/Java%20Bible/ch06/06-08.html (1 of 5)6/26/2005 7:56:04 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Figure 6-6: Use the where command, along with up and down, to ensure you are in the correct stack
frame.

Single-step through the code

In this case, it’s time to single-step through the two lines of code that assign values to the horizontal and
vertical variables:

> step
> step

Of course, you can also set a breakpoint for the line following these two, and then issue the cont
command. This is particularly useful when a number of lines must be executed, and you don’t want to
step though them one at a time:

> stop at MediaHelloWorld:55


> cont

Inspect the local variables

Now, inspect the local variables to see if x or y have magically changed. If they’re in order, check to see
if the assignment to your horizontal and vertical variables actually took place:

> locals
> print horizontal
> print vertical

A-ha! The x and y local variables are fine, but the assignment never took place. What’s this? Have you
mistakenly assigned x to both horizontal and vertical? Impossible! Rub your eyes again, if you like, but
the results will look the same every time this method is invoked: you’ve found the bug! (See Figure 6-7.)

Figure 6-7: After stepping through the two lines of assignment code and inspecting the results, our bug
becomes clearly visible.

file:///F|/books/java%20books/Java%20Bible/ch06/06-08.html (2 of 5)6/26/2005 7:56:04 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Cleaning house

Having tracked down your first bug using jdb, you’ll want to clear any remaining breakpoints and
continue program execution before exiting altogether. Although you shouldn’t have to bother, in theory,
you’ll be in for a rude surprise if you don’t. About half the time I tried to exit the debugger without
clearing each breakpoint and resuming program execution, it resulted in a crash. Save yourself the
headache:

> clear (lists the current breakpoints)


> clear class:55
> clear class-53
> cont
> exit

Of course, once program execution has resumed, you can quit the applet by closing the Applet Viewer
itself. Alternately, you can issue jdb’s exit or quit commands to terminate the debugging session. But
either way you do it, be sure to clear all breakpoints and resume program execution beforehand (see
Figure 6-8).

Figure 6-8: Be sure to clear all breakpoints and continue program execution before exiting the
debugger.

Debugging Tips and Warnings

In the course of working with the jdb debugger, there are a few words of caution I’d like to put forth. If
the crashes that brought an untimely close to many of my debugging sessions don’t plague you, you
won't have to worry about taking these extra precautions. However, if you’re having problems working
with jdb, the following suggestions might be just the trick.

Disable sound and graphics

Whenever possible, comment out the line(s) of source code that play sound clips. Then do the same for
code that displays images, and recompile. Unless playing audio or painting to the screen are integral to
your debugging session, you&$146;re only making jdb’s job more difficult than it needs to be.

For example, you didn’t need to hear the audio snippet in the previous debugging session. By
commenting out the lines of code that dealt with playing audio, you’ve taken a burden off the debugger
and the runtime system. The same goes for painting graphics in many cases; if it’s not directly related to

file:///F|/books/java%20books/Java%20Bible/ch06/06-08.html (3 of 5)6/26/2005 7:56:04 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

the bug you’re tracking down, comment it out!

Quit programs you don’t need

Debugging is a delicate process, as you’ll soon find out. There’s no reason to have programs in the
background sucking away much-needed resources, especially when it comes to memory. Quit every
program you don’t really need to have running; this will free up memory and the CPU for the debugger
and your program.

Don’t try to copy/paste in the DOS box

Windows users may be tempted to save time by not typing jdb commands, but using the Copy
and Paste toolbar buttons supplied in the DOS box instead. After ali, why type something
when you can paste it in?

Don’t try it.

Every time I paste a command into the debugger, the puppy seizes up, as if asked to recite poetry in
public. Sometimes, but not always, pressing the Escape key followed by Enter brings it back to life.

The jdb supports the ! ! command, which takes some of the repetition out of typing commands
(see Table 6-l). Although not as flexible as copy/paste, it won’t lock up the debugger.

Clear breakpoints and resume program

You can exit a debugging session in one of two ways: issue the exit (or quit) command to jdb, or allow
the program to terminate naturally (for applets, this means closing the Applet Viewer window).
However you chose to exit the session, be sure to first clear all breakpoints and resume program
execution using the cont command! (See Figure 6-8 earlier in this chapter.)

Even though it shouldn’t make a bit of difference if breakpoints are set or the program is suspended, my
computer has gone up in smoke on many occasions when exiting the debugger under such conditions.
Clearing breakpoints and resuming program execution prior to an exit, however, seems to do the trick.

Making Applets Live on the Web

Once you’ve created an applet, the chances are pretty good that you’ll want to make it available to the
entire Web population. To do this, you must upload the various files that make up the applet to a Web
site and test it, to make sure nothing breaks in the process.

file:///F|/books/java%20books/Java%20Bible/ch06/06-08.html (4 of 5)6/26/2005 7:56:04 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Uploading applets to a Web site assumes you have the authority, and tools (such as an FTP tool), to do
so. if the site to which you want to add the applet is maintained by someone other than yourself, you’ll
have to obtain permission and perhaps even get the access passwords, if you plan to upload the materials
yourself. If you don’t already have such authority, you’ll have to arrange for it, or provide the applet and
the various files it uses to someone who will eventually perform the upload.

Web server directory layout

If this is the first time Java is being used at a site, a directory structure will need to be created to hold
your compiled Java classes and associated files (such as the audio and graphics files used in our latest
version of HelloWorld). This is pretty straightforward because the directories you create on the Web will
be similar to those you created locally.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch06/06-08.html (5 of 5)6/26/2005 7:56:04 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Get the applet running

At this point, our applet isn’t actually running. Applet Viewer simply invoked the debugger with the
class file embedded in the HTML file we passed to it. The first thing you’ll want to do is get the applet
running:

> run

Once executed, this command puts our applet into motion as expected. In a few seconds, you’ll hear the
soundtrack and see the image appear. Just to make sure everything is working as normal, and to prepare
for our debugging session, move the cursor around as you normally would. As you can see, the image
doesn’t appear where it should. Now, it’s time to find out why.

Start your search

Of course, you already know why the image doesn’t appear where it should, hut pretend for just a
moment that you don’t have any idea. The first thing you need to cio is consider where the problem is
occurring. Naturally, you’ll want to see what’s going on in the method that paints the image to the
screen. After all, this is the place where the rubber hits the road; where the image is actually slapped up
on the screen.

Use the methods command

Assuming you forgot the exact spelling of the paint () method (work with me here), or weren’t sure of
exactly what methods were in the program to begin with (and so didn’t know where to begin looking for
suspicious behavior), you could get a listing of each by issuing the methods command:

> methods MediaHelloWorld

The results are shown in Figure 6-3, and they give you a good idea of where to start the debugging
process. Oh, yes, it is indeed the paint() method that we want to look inside while the program is running.
And it’s spelled p-a-i-n-t. Imagine that. Let’s set a breakpoint for this method:

file:///F|/books/java%20books/Java%20Bible/ch06/06-07.html (1 of 4)6/26/2005 7:56:04 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

> stop in MediaHelloWorld.paint

Figure 6-3: Use the methods command for a listing of the methods in a class.

Once set, you’ll need to force your applet to invoke the method. The debugger will just sit around and
wait until this method is invoked, at which point it will stop the program execution entirely. To invoke
the paint() method, you need only switch to Applet Viewer (perhaps moving your mouse to trigger the
method).

The jdb supports two types of breakpoints: method and line number. In this case, we only want to break
when paint() is called. Later, we’ll set a breakpoint at a specific line number. Keep in mind that the
commands for each differ slightly:

stop in class.method (sets breakpoint for method)


stop at class:line (sets breakpoint at line number)

Check the source code

Once the breakpoint is reached, the applet will seem to “freeze.” The sound will stop playing, and the
image will no longer move. This is because the debugger has suspended ail activity, and is now waiting
for another command. At this point, we’]] want to take a look at the source code within the debugger and
see exactly where execution was stopped:

> list

Once executed, the list command shows you precisely where the debugger has stopped the flow of
program execution. Not only is the method listed, but an arrow points to the line of code that will be
executed next (see Figure 6-4). If you don’t see the code listing, you may have to specify the path to
your source file:

> use

Figure 6-4: After listing the source code for the current breakpoint, print out the variables you want to
inspect.

file:///F|/books/java%20books/Java%20Bible/ch06/06-07.html (2 of 4)6/26/2005 7:56:04 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

The use command

If you issue the use command by itself, it displays the path list that jdb uses to find source files. By
default, the class path is used. However, if the directory containing your source file isn’t included, you
won’t be able to list the source code at all!! In this case, you must supply the path to the file (use <path
list>):

> use C:\java\aewcode\HelloApplet

Assuming the source file is available, the list command will spit out the code (with line numbers)
surrounding the breakpoint.

The print command

At this point, you can see that the drawImage() method is about to be invoked. But are the horizontal and
vertical values being provided to it valid? There’s only one way to find out:

> print horizontal


> print vertical

The print command outputs the value of the item you provide to it. You’ll use this command to inspect
the value of classes, objects, and variables. You can either specify the name of these items, as we have,
or the hexadecimal number that is used to uniquely identify an object running in the debugger.

In our case, printing out these variables reveals that they are exactly the same (see Figure 6-4).
Coincidence? Perhaps. Enter the cont command to resume execution, move your cursor over a different
part of the applet, and print out these values again. Hmmm... looks like we’re on to something.

The dump command

Use the dump command to find out the names and IDs of the methods and variables for a class, along
with the superclass and any interfaces it may implement:

dump MediaHelloWorld

Clear the breakpoint

Perhaps we should take a look at the method that calls this one? But first, clear the breakpoint that
you’ve already set. If you don’t, each time you return to Applet Viewer it will attempt to refresh the
display by calling the paint() method, triggering the breakpoint each time.

file:///F|/books/java%20books/Java%20Bible/ch06/06-07.html (3 of 4)6/26/2005 7:56:04 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

First, execute the clear command without any parameters. This will give you a listing of all the current
breakpoints, of which there will only be one. Using this information, clear the breakpoint by specifying
the name of the method and the line number:

> clear (get a listing of all breakpoints)


> clear MediaHelloWorld:28 (clear breakpoint using method:line
form)

Resume program execution

Once the breakpoint has been cleared, issue the cont command to resume program execution. Once
program execution has resumed, set a breakpoint for the mouseMove() method:

> cont
> stop in MediaHelloWorld.mouseMove

After setting the breakpoint, invoke it by moving the mouse inside the running applet. This triggers the
mouseMove() method and grinds program execution to a halt once again as the debugger waits for your
command. List the code, as usual, and then take a peek at the values of the local variables, using the
locals command:

> list
> locals

At this point, we know the x and y values are valid—they’re coming into the mouseMove() method set to
different values, as seen in Figure 6-5 (unlike our horizontal and vertical variables, which always have
the same value). Of course, local variables are only available if you’ve recompiled your source code
using the -g option. If you didn’t, you’ll have to exit the debugger, recompile with - g on, and try again.
(See “Debugging Tips and Warnings” later in this chapter before exiting the debugger!)

Figure 6-5: Use the locals command to inspect the value of variables in a method.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch06/06-07.html (4 of 4)6/26/2005 7:56:04 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Create a directory structure

First, you’ll need to create a directory on the Web server to store your HTML file. For this example,
why not use the same name as the directory on your local hard drive?

Although any name will do, I’ll assume you use HelloApplet. Inside this directory you must create two
additional directories: images and audio. These will hold the graphic and sound files your applet requires.
Because the directory and filenames are hard-coded in our applet, we don’t have the option of using any
other names; the names you use on the Web must exactly match those used locally.

When a Java-savvy browser comes upon an HTML file containing an <APPLET> tag, it looks inside the
same directory as the HTML file for the specified class file (MediaHelloWorld.class in this case), unless
told to look elsewhere. If the browser finds the class file specified in the <APPLET> tag, it downloads
that file onto the local computer and hands it off to the Java runtime environment for execution.

Although it’s possible to specify a different directory location for the class file by using an
optional <APPLET> tag attribute (the CODEBASE attribute, illustrated in Chapter 7), for now
we’ll assume it’s located in the same directory as the HTML file that calls for it.

Relative support

When executed, our MediaHelloWorld applet loads the image and audio files it requires. Because we’ve
used the method getCodeBase() to reference these files, the browser looks for them relative to the Applet
class file itself. That is, the browser looks inside the directory in which it found the compiled class for
the two directories we specified in our applet, images and audio, expecting to find the files world.gif and
hello.au. If available, each file is downloaded over the Internet and onto the user’s local computer.

If we had used getDocumentBase() instead of getCodeBase() in each getImage() method, the browser would
expect these files to be located relative to the HTML document, rather than relative to the class file. (See
the sidebar “Getting to Base” earlier in this chapter.)

Because our <APPLET> tag doesn’t specify a unique location for the class file, it is expected, by default,

file:///F|/books/java%20books/Java%20Bible/ch06/06-09.html (1 of 3)6/26/2005 7:56:05 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

to be inside the same directory as the HTML file. As a result, it really doesn’t matter if we use
getCodeBase() or getDocumentBase(); the audio and graphic files our applet uses will be located relative to
the HTML document in either case, unless we utilize the optional CODEBASE <APPLET> attribute to
specify a different location for the class file (refer to Chapter 7 for an example).

Uploading the files

Once you’ve created the required directories, it’s time to upload the various files that comprise our
applet onto the Web server. You can do this easily using an FTP tool, although if you happen to
administer your own Web server, you probably don’t have to bother with FTP at all. In this case, simply
move the files on your Web server by network or removable media (tape, floppy disk, and so on).
Regardless of how you get the files to the Web server, make sure each is placed in its appropriate
directory.

The HTML file should be located one directory level above the audio and images directories, along with
the compiled MediaHelloWorld applet class files. Because our applet actually extends HelloWorldApplet,
the compiled class file for HelloWorldApplet must also be uploaded into the same directory as the
MediaHelloWorldWorld class. In fact, you have to place every class file your applet uses, with the
exception of those that come with the Java runtime environment (the Applet and awt classes, for
instance), on the Web server in the same directory. If you don’t, your applet won’t be able to execute!

After the HTML and all applet classes have been uploaded to the Web server, upload the audio and
graphic files into their appropriate directories. The world. gif file should be placed in the images
directory, while hello. au must be located in the audio directory. For a graphical representation of where
each file is located, see Figure 6-9.

Figure 6-9: When uploading applets to the Web, be sure to use the same directory structure found on
your local system.

When uploading files to your Web server, be sure their names remain intact. Many FTP
programs impose the DOS filename restriction of eight characters for the name and only three
characters for the extension, automatically chopping off the others! As a result,
MediaHelloWorld.class might become MediaHel.cla.

If this happens, rename the files before terminating your FTP session. And don’t forget to supply the
proper mix of uppercase and lowercase characters (MediaHelloWorld.class is not the same as mediahelloworl
d.class!)

file:///F|/books/java%20books/Java%20Bible/ch06/06-09.html (2 of 3)6/26/2005 7:56:05 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Testing the applet

When all the files have been uploaded into their appropriate directories, it’s time to test the applet.
Simply access the HTML file on the Web server with your Javasavvy browser by loading its URL. Or, if
you prefer, do it with Applet Viewer. Applet Viewer can execute applets on the Web, as long as you
provide a URL to the page like this:

appletviewer
<http://www.mantiscorp.com/books/java/found/TestMediaHello.html>

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch06/06-09.html (3 of 3)6/26/2005 7:56:05 PM


file:///F|/books/java%20books/Java%20Bible/ch06/images/06-06.jpg

file:///F|/books/java%20books/Java%20Bible/ch06/images/06-06.jpg6/26/2005 7:56:06 PM
file:///F|/books/java%20books/Java%20Bible/ch06/images/06-07.jpg

file:///F|/books/java%20books/Java%20Bible/ch06/images/06-07.jpg6/26/2005 7:56:07 PM
file:///F|/books/java%20books/Java%20Bible/ch06/images/06-08.jpg

file:///F|/books/java%20books/Java%20Bible/ch06/images/06-08.jpg6/26/2005 7:56:08 PM
Java Bible:Extending, Enhancing, Debugging, and Uploading

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

In the above example, Applet Viewer will connect to the Web page and execute any applets it finds. If a
connection isn’t already established to the lnternet, it will attempt to establish one. Of course, Applet
Viewer doesn’t display anything but applets, so you won’t see any HTML, as you would using a Java-
savvy browser.

However, because Applet Viewer is fast and easy to use, I prefer to use it first. If the applet works as
expected using Applet Viewer, I then test it with a Java-savvy browser, such as Netscape Navigator. But
however you do it, be sure to test your applets once you’ve placed them on the Web.

If all goes well, you’ll be greeted by the same “Hello World!” text string that appeared when the applet
was executed locally. And, in a few moments (give or take a few more moments, depending on the
speed of your connection), the image will be downloaded from the World Wide Web and also appear
(see Figure 6-10). At about the same time, the sound track will finish downloading and begin to play.

Figure 6-10: MediaHelloWorld, now living on the Web, is accessible to the world.

If it does, the world’s your oyster! if it doesn’t, consider some of the problems outlined in the sidebar “If
Your Applet Fails to Load.”

If Your Applet Fails to Load

If your applet fails to load, there are a few things to consider. First, make sure your files are all uploaded
and in their proper directories. If the browser can’t locate the compiled class specified in the HTML file,
the applet will fail to execute. Also, if the image and sound files are missing or in the wrong place, the
applet will fail to execute as it should. For instance, if the graphic file is in the wrong place or missing
altogether, you won’t see it. And if the audio file can’t be found, you won’t hear a background track at
all.

file:///F|/books/java%20books/Java%20Bible/ch06/06-10.html (1 of 4)6/26/2005 7:56:09 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

If all the files are on the Web server and in their proper directories, check to see that each filename is
spelled exactly as it is on your local hard drive. Because some FTP tools take the liberty of appending
extensions to files during the upload process, or truncating long names, you may have to rename the file
once it is on the Web. And be sure to check the case of each filename-a browser won’t be able to find
MediaHelloWorld.class if it appears on the Web site as mediahelloworld.class.

Also, make certain the files were successfully uploaded. Although a filename might appear on your Web
server, that doesn’t mean the entire file was successfully transferred. To be certain, compare the file
sizes of each upload to those on your local machine. While it’s normal for file sizes to be off by a few
kilobytes either way, if the difference between your local and uploaded file sizes is significant, you’ll
have to try again. In this case, delete the file from the Web server and upload it from scratch.

Between each attempt to rectify an applet problem, it’s a good idea to quit your browser and launch
anew (or manually force the page containing your applet to reload from scratch). This way, you can be
certain that the browser is loading a fresh copy of the applet instead of opening a cached copy from your
hard disk.

Getting complex and flexible

The applet you have just created and deployed on the World Wide Web would be considered complex to
software developers who don’t program in Java. After all, it’s an example of dynamic Web content
featuring text, graphics, and audio. But as you know, the real complexity is taken care of by Java,
allowing you to concentrate on the behavior of your applet without getting bogged down with the details
of writing graphics and audio routines. Even the ability to locate and utilize resources such as image and
audio files on the network is taken care of by the rich Java classes that have already been written for
you, meaning you don’t have to write a line of this code yourself. You simply import the classes you
need from those there for the taking.

But what if you want your applet to be a bit more flexible than it would be if you hard-coded the names
and locations of files? After all, to change the name or directory location of the audio or image file, you
must actually change the code of the applet itself, recompile it, then upload the resulting class once
again. Wouldn’t it be nice if there was a mechanism for supplying your applet with information directly
from the HTML document, such as specifying filenames and locations? Wouldn’t this greatly increase
the flexibility of your applets? That’s exactly what the folks at Sun thought, and so they created the
notion of “applet attributes.” We’ll explore these and application command-line parameters in the next
chapter.

Odds ‘n’ Ends

Before we come to a close, a few areas deserve a bit more attention. Specifically, you should be aware

file:///F|/books/java%20books/Java%20Bible/ch06/06-10.html (2 of 4)6/26/2005 7:56:09 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

of the this and super variables that are commonly found in Java programs. And, in addition, you should
know the fundamental methods all applets support.

this and super

In order to allow convenient access to the current object and its superclass, Java provides two special
variables: this (references the current object) and super (references the object’s superclass). You can use
these variables, discussed in detail in Chapter l4, anywhere in the body of a class.

You can also use this to invoke the current object’s constructor, although typically you don’t use it to
invoke methods, because the method name alone will do the trick:

this([parameterList]); // invoke current object’s constructor


this.methodName(); // functional equivalent to methodName();
Meanwhile, super is typically used to invoke a method or
constructor in the superclass:
super.methodName(); // invoke superclass method
super([parameterList]); // invoke superclass constructor

Fundamental applet methods

Every Java applet inherits five key methods from the applet class: init (), start (), stop (), paint (), and destroy
(). These methods give applets the ability to respond to major events, such as when a Web page
containing the applet is viewed or left by the user.

Following is the basic structure of an applet, including these five methods. Although the init() method
must be overridden, the remaining four do not necessarily need to be. If your applet has no use for one
of them, simply ignore it (that is, don’t bother to override it). The applet structure looks like this:

public class AnyApplet extends java.applet.Applet {


. . .
public void init() { . . . }
public void start() { . . . }
public void stop() { . . . }
public void paint(Graphics g) { . . . }
public void destroy() { . . . }

Although you can probably guess what each of these methods should do if you choose to override them,
Table 6-2 gives a brief explanation of each one.

file:///F|/books/java%20books/Java%20Bible/ch06/06-10.html (3 of 4)6/26/2005 7:56:09 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch06/06-10.html (4 of 4)6/26/2005 7:56:09 PM


file:///F|/books/java%20books/Java%20Bible/ch06/images/06-09.jpg

file:///F|/books/java%20books/Java%20Bible/ch06/images/06-09.jpg6/26/2005 7:56:11 PM
Java Bible:Extending, Enhancing, Debugging, and Uploading

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Table 6-2
An Applet’s Five Basic Methods

Method Description

init() Override this method to initialize the applet each time it’s loaded or
reloaded. At the very least, this is where most applets call the resize ()
method to set the size of their canvas.

start() Override this method to begin actual applet execution, as when the page
containing the applet is loaded or reloaded by the user.

stop() Override this method to terminate applet execution when the user
leaves the Web page containing the applet or quits the browser.

paint (Graphics g) Override this method if you wish to display text or images on the applet
canvas. This method is called every time the applet’s display needs to
be drawn (in other words, when the applet first becomes visible to the
user, when it’s scrolled, or when the applet itself requests to be
repainted).

destroy() Override this method if you need to do a final clean-up in preparation


for unloading.

As stated earlier, not every applet is obligated to override ali five methods. The most simple applets,
such as our original HelloWorld applet, need only implement init() and possibly paint (). However, most
applets are more complex. Those that change their visual appearance, or interact with the user, for
example, will likely override start() and stop() as well.

file:///F|/books/java%20books/Java%20Bible/ch06/06-11.html (1 of 2)6/26/2005 7:56:11 PM


Java Bible:Extending, Enhancing, Debugging, and Uploading

Such is the case with the MediaHelloWorld applet detailed in this chapter. A sound clip is played
continuously once start() is executed and it stops playing when stop() is called. You’ll notice, however,
that we don’t bother to override destroy(), as we do everything necessary to “clean up” in our stop()
method, which is called before destroy(). Applets that must release resources they access upon executing,
however, can rely on destroy() as a final step in bringing their applet to a successful close.

Summary

It is very simple to add images and soundtracks to Java applets. Once you’ve considered whether your
applet should be enhanced or extended, it’s merely a matter of implementing the code that will do the
work. Compiling the code is easy—just as you saw in the previous chapter.

• If you plan to debug your Java programs, you’ll have to recompile them with the -g option.
This option ensures you’ll be able to view local variables, something you won’t want to be
without in a debugging session.
• You can use the jdb tool (although I would strongly suggest investing in a professional
development environment for the robust debugging tools alone) to debug your Java applications.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch06/06-11.html (2 of 2)6/26/2005 7:56:11 PM


file:///F|/books/java%20books/Java%20Bible/ch06/images/06-10.jpg

file:///F|/books/java%20books/Java%20Bible/ch06/images/06-10.jpg6/26/2005 7:56:12 PM
Java Bible:Command-Line Arguments and Applet Tag Attributes

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

CHAPTER 7
Command-Line Arguments and Applet Tag Attributes
In This Chapter

Adding flexibility to Java applications and applets with command-line arguments

Understanding Java applications’ command-line argument conventions

Adding command-line arguments to the HelloWorld application

Using applet attributes

Until now, the Java programs we’ve written have been very inflexible. That is to say, the data these
programs use is hard-coded and can’t be changed, except by a programmer.

The original HelloWorld application will always output the words “Hello World!” to the screen, until
the program has been altered by the programmer to say something else. And the MediaHelloWorld
applet you created in the previous chapter will always use the same audio and image files until it is
rewritten to use others. In both cases, the programs require fiddling around with the source code and
must be recompiled before changes to the data they use can be put into effect.

Need for Flexibility

In some cases, this lack of flexibility may be exactly what you want. Perhaps there is a portion of the
data your program uses that you want never to change unless the program itself is updated. Such is the
case with copyright notices and developer credits, which remain constant throughout the life of a
particular software version release.

However, more often than not, the data your programs use will change regularly.

file:///F|/books/java%20books/Java%20Bible/ch07/07-01.html (1 of 4)6/26/2005 7:56:13 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

In the case of an application, you may well want your program to act in a certain way, depending upon
what input is provided by the user at the time of execution. For this, you have the option of using Java
command-line arguments. With command-line arguments, you can specify any number of parameters to
the application at the time it is executed.

If you’re a C/C++ programmer with experience developing programs executed from the command line,
the notion of command-line parameters will come as no surprise. If not, the following chapter will be of
particular interest.

But how does this affect applets? These little devils live on the Web, and are downloaded into your
computer by the browser. Why would you need to provide parameters to an applet, and how would you
do such a thing, even if you wanted to?

To help answer these questions, consider for a moment the environment in which an applet exists on the
Web. Think about the Web server, and why applets have become so popular. Until Java came along, the
Web was a very static environment that, for the most part, merely connected people to information.
Thanks to Java, our Web sites can now support executable content: Distributed multimedia and true
interaction with the user are a reality. Web pages have become dynamic, alive.

But why have flexible applets?

From a practical standpoint, the answer lies in the Web server. Unless the directory structure of your
Web site never changes, and the files your applet relies on are always in the same place, applet
flexibility is a tremendous advantage when it comes to maintaining a site. Most Web sites grow
continually, with new content being added on a regular basis. If the data files your applet requires are
hardcoded, as ours have been, maintaining a Web site becomes a nightmare.

If you think of the Web server as a giant, universally accessible hard drive, it may help drive home the
point that you’re more likely than not to be reorganizing files and directories regularly. How many times
have you moved files and directories around on your local hard drive to keep it organized? This will
eventually become necessary on your Web server, if it isn’t already. And if you have to update source
code, recompile it, and then upload the result for each applet at your site merely to reflect changes in the
server directory layout, you’ll certainly appreciate the ability to pass parameters to applets.

Couple ease of maintenance with an ability to create very robust applets that can be customized without
touching the applet or applet source code, and you have extremely compelling reasons to build flexible
applets. And, thanks to applet attributes, your applets can be as flexible as you choose.

Let’s take a look at how command-line arguments are handled by Java applications, and then move on to
applets and the use of applet attributes. Of course, most of you will have only passing interest in
developing applications. Creating applets is by far the most popular use of Java, and so you may be
tempted to jump ahead to the section covering applet attributes. If this is the case, I suggest that you at

file:///F|/books/java%20books/Java%20Bible/ch07/07-01.html (2 of 4)6/26/2005 7:56:13 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

least skim through the first section regarding application command-line arguments and then give special
attention to the section on String objects. Regardless of whether you develop Java applications or applets,
you’ll be dealing with the String class.

Java Command-Line Arguments

Java command-line arguments are arguments that are passed to a Java application when it is invoked
from the command line. If you created the HelloWorld application discussed in Chapter 5, you’re
already familiar with executing Java applications at the command line:

c:\> java HelloWorld

Here, no command-line arguments are passed to the HelloWorld application. And for good reason:
HelloWorld, as we wrote it, doesn’t know what to do with command-line arguments, if we provided
them, nothing would happen.

Although you are free to pass any number of command-line arguments to a Java application,
it’s up to the application to make use of them. If an application hasn’t been written to handle
command-line arguments, it will execute as it normally would and ignore the arguments
altogether.

Supporting command-line arguments

So, how do you write a Java program capable of handling command-line arguments? If you’re a C/C++
programmer, you probably have a pretty good idea. If not, don’t worry; supporting command-line
arguments is easy. All arguments are passed to your application through an array of strings in the main()
method. You simply take them out of the array, and do with them as you wish. This is the signature of a
typical main() method in Java:

public static void main (String args[]) ( ... )

Programmers who have worked with C/C++ command-line arguments are already familiar with the
concept of receiving parameters through the main() function. In Java, however, there are a few
differences in how the commands are passed to an application that affect how they are processed.

In Java, executable routines such as main() are known as methods. In C, such routines are
referred to as functions or procedures. And, just to confuse you, in C++, they are referred to as
member functions as well as methods.

file:///F|/books/java%20books/Java%20Bible/ch07/07-01.html (3 of 4)6/26/2005 7:56:13 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch07/07-01.html (4 of 4)6/26/2005 7:56:13 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Java command-line arguments versus C/C++

Command-line arguments in Java differ from their C and C++ counterparts in two major ways: number
and type. C/C++ uses two variables to pass arguments to applications; Java uses only one, and the data
type of the variable containing the parameters is not the same.

Number of argument variables

With C and C++, the operating system passes command-line arguments directly to the program using
two argument variables:

• argc: the number of arguments appearing on the command line


• argv: a pointer to an array of strings containing the arguments

In Java, only one argument variable is used:

• args: an array of strings that contain the command-line arguments

Since the variable used to store command-line arguments in Java is an array of String objects, there is no
need for a second variable to hold the number of arguments. By simply referencing the length instance
variable of the array, you can find the number of command-line arguments:

args.length; /* get number of command-line arguments */

Because each element in the args array is a command-line argument, the length of the array is equal to
the total number of command-line arguments the user provided when executing the application. By
referencing the number of elements in the array, as shown above, your Java applications will know
exactly how many command-line arguments were provided when executed. This eliminates the need for
a second variable to keep track of how many command-line arguments were provided.

Argument variable type

file:///F|/books/java%20books/Java%20Bible/ch07/07-02.html (1 of 4)6/26/2005 7:56:13 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

In addition to eliminating the need for a variable to hold the number of command-line arguments passed
to your application, Java differs from C and C++ in the data type used to hold these arguments. In C/C+
+, this variable is a pointer to an array of strings. In Java, it’s simply an array of String objects; you don’t
have to dereference a pointer and then deal with an array to get to the arguments.

In Java, you deal directly with the array. To access a command-line argument, you only need to access a
particular element in the args array. Suppose, for instance, that you wanted to get the third command-line
argument provided by the user. Since all array indexing begins with 0 (zero; just as with C/C++), this
would do the trick:

String theArg; /* variable to hold argument */


theArg = args[2]; /* retrieve third argument */

If you’re already comfortable using C or C++, this approach makes plenty of sense. If not, you’re
probably wondering why in the world we’re using an index of 2 in order to retrieve the third value in the
array! While it may be confusing at first, once you commit this indexing convention to memory (or
carve it in your mousepad), you’ll have no problem dealing with this “off by one” situation.

In C, C++, and Java, the individual elements in an array are accessed by supplying an index, or
subscript, to the element in its position in that array. In the example above, we’ve provided a subscript
of 2 in an attempt to retrieve the third element, or member, of the args array. Because array indexing
begins with 0 in these programming languages (and not 1, as you might expect), we need to subtract 1
from our subscript value before attempting to use it. Since we want item 3 in the array, we come up with
a subscript value of 2. Perhaps the following will help you commit this to memory:

String theArg; /* variable to hold argument */


theArg = args[0]; /* retrieve first argument */
theArg = args[1]; /* retrieve second argument */
theArg = args[2]; /* retrieve third argument */
theArg = args[3]; /* retrieve fourth argument */
theArg = args[4]; /* retrieve fifth argument */

In this example, I assume at least five elements are in the array. If there were fewer than five
elements, this code would be attempting to access an element that does not exist. In this case,
our subscript would be out of the legal range and would cause the runtime system to throw an
ArrayIndexOutOfBoundsException exception. See the discussion on applets later in this chapter for
details on exceptions, or refer to Chapter 10, “Language Fundamentals.”

It’s considered bad programming style to use explicit numbers as subscripts to arrays (as we’ve been
doing), so array elements are usually accessed with an integer index variable. Keep in mind that the
index variable must be one less than the element you wish to retrieve. To keep confusion to a minimum,
it’s a good idea to initialize this variable to zero (0) and use the following “off by one” method when

file:///F|/books/java%20books/Java%20Bible/ch07/07-02.html (2 of 4)6/26/2005 7:56:13 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

changing its value:

String theArg; /* variable to hold argument */


int i:0; /* index variable, initialized to zero */

theArg = args[i]; /* retrieve first argument */


i = 5 - 1; /* prepare index to retrieve 5th element in array
*/
theArg = args[i]; /* retrieve fifth argument */

Although subtracting 1 from the value of the index you want to access (five in this case) might seem like
extra work, doing so will help you become comfortable with the idea that the array subscript is always
one less than the element you want to retrieve. After using this “off by one” method for a while, you’ll
have no need for it: The technique will become second nature. If you want to access the fifth element in
an array, you’ll automatically use an array subscript of 4.

It may help to mentally repeat “off by one” to yourself every time you think of arrays. But be
warned: While this method will almost certainly guarantee that you subtract 1 from your
subscript values, it may have disastrous consequences in your personal life. Without getting
into such details, let’s just say you’ll come up one short in just about everything you do.
Shopping, paying bills, and having children will never be the same again.

Argument variable contents

Aside from the number of variables and their data type, yet another difference exists between Java and C/
C++ command-line argument variables: the contents of the argument array. In C and C++, the command-
line argument array variable contains the name of the program that is executed, in addition to the
command-line arguments:

c:\> HelloWorld howdy doodie

In this C/C++ example, the array variable would contain all three strings on the command line:
HelloWorld, howdy, and doodie. In Java, this array consists only of command-line arguments:

c:\> java HelloWorld howdy doodie

Upon execution, only howdy and doodie would be in the args array. Only the actual command-line
arguments would be passed to your program by the runtime system. There is no need for your program
to receive the name of the application, since it’s always the same as the name of the class where the main
() method is defined. In this example, main() would have been defined in class HelloWorld.

file:///F|/books/java%20books/Java%20Bible/ch07/07-02.html (3 of 4)6/26/2005 7:56:13 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch07/07-02.html (4 of 4)6/26/2005 7:56:13 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Java strings are first-class objects

As you now know, all elements in a Java command-line argument array are strings. Perhaps you’ve
noticed that the word string often begins with a capital S when we talk about Java, yet also appears in
lowercase from time to time and whenever we’re talking about the C and C++ languages. Why is this?

Java strings are defined in the String class; when we instantiate and use them, we’re dealing with String
objects. Anytime we’re talking about the String class or String objects, the S is capitalized. It we’re just
talking about strings in general, without any specific reference to the class or object, the S is in
lowercase. But when it comes to C and C++, there are no built-in String classes or objects. Here, we’re
always dealing with the generic concept of strings, not a formal class or object that is identified by an
uppercase S.

In C/C++, a string is nothing more than an array of null-terminated characters. As a result, C/C++ strings
don’t have well-defined behavior or mechanisms for manipulating them. A common problem with C/C+
+ strings is that it’s very easy to overrun their array boundaries.

Since no error-checking is performed with C/C++ strings, there is no way to be certain if the subscript
you provide is out of range. Suppose you were dealing with a C string 15 characters in length, but forgot
that array indexing begins at zero. By accessing an element in the array using a subscript value of 15,
you’d actually be attempting to access the sixteenth element. But you might not realize it, since it’s
possible in C/C++ to reference any location in memory! A value would be returned, and you might go
merrily along your way none the wiser.

Now, suppose you later tried to change the value you had just referenced. In that case, you’d be hip-deep
in trouble. You’re not changing the string, as you think, but altering some unknown memory location by
mistake. You would be lucky to get out alive, and your program runs the risk of crashing. When reading
and writing to data in such a situation, you’re dealing with garbage values at best and running the risk of
corrupting your data. But with Java, this won’t happen.

Java strings behave predictably

With Java strings, you’re dealing with first-class objects that have a number of methods created

file:///F|/books/java%20books/Java%20Bible/ch07/07-03.html (1 of 4)6/26/2005 7:56:13 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

specifically for retrieving and setting data. To prevent problems like the one I just described from
sneaking up on the unsuspecting programmer, bounds-checking is performed at compile and run time.

If you explicitly exceed the value of an array directly in your code, the compiler will catch the mistake
and let you know. If the index can’t be checked at that time, as is often the case, the runtime
environment will catch any out-of-range values. Unlike C/C++, you’ll know immediately where the
problem is and have an opportunity to fix it.

With C/C++, you make a small sacrifice to the beta-test gods and pray each night to the software testing
cycle that any such errors are caught before the product ships. Okay, to be fair, there are tools that help
find these problems during the development stage, but you have to use them. With Java, it’s all taken
care of within the environment itself.

Java provides two classes for dealing with strings: String and StringBuffer. String is used for strings that
will not change, while StvingBuffer is a class for dealing with strings that may be changed. Since we don’t
alter the command-line arguments in our applications, this chapter focuses on the String class. For details
on both String and StringBuffer, refer to Chapter 12.

You should also note that both the String and StringBuffer classes are part of the java. lang
package. A package is a group of related classes. For details on packages, refer to Chapter 11.

Java Command-Line Argument Conventions

The Java language adheres to UNIX conventions for command-line arguments, defining three different
types:

• Word arguments
• Arguments that require arguments
• Flags

You should be sure to adhere to the conventions listed in the next three sections when dealing with
command-line arguments.

Word arguments

Word arguments, such as -verbose, must be specified precisely on the command line. As a result, -ver
would not be valid if you wanted to invoke the -verbose option: only - verbose would work!

Typically, your program will test to see if a particular word argument has been specified, and set a flag
accordingly:

file:///F|/books/java%20books/Java%20Bible/ch07/07-03.html (2 of 4)6/26/2005 7:56:13 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

if (argument.equals(“-verbose”)){
verbose = true; // turn the verbose flag (verb) “on”
}

In this case, we’ve tested for the-verbose word argument and set the verb flag accordingly.

Arguments that require arguments

In many cases, you’ll want to use arguments that are followed by some type of information (that is, more
than just the argument itself is necessary). You might, for example, want to use a command-line
argument such as -file to redirect output of the program into a file. The -file option alone, however, isn’t
enough. A filename must also be supplied.

In this case, you need to read in the filename following the -file argument. That is, you must parse the
command line to retrieve the additional information:

if (argument.equals(“-file”)) {
if (nextarg < args.length)
filename = args[nextarg++]; // set the “filename” variable
else
System.err.println(“-file must be followed by a filename!”);
}

In this example, we test to see whether the user actually supplied an argument following - file. If so, it’s
retrieved and assigned to a variable. If not, a message is output to the user telling him or her how to use
this argument.

Flags

Single-character codes used to modify the behavior of a program are known as flags. You might, for
example, want to supply a help option in your program. In this case, you would use the -? flag. Of
course, you could also implement a -help word argument. In fact, you might want to use both.

Typically, flags can be specified separately and in any order. For example, either -?, -z, or -z -? work just
fine. In addition, flags can typically be concatenated and specified in any order. Thus -z? and -?z are also
hunky-dory.

Other conventions

In addition to the conventions described in the three previous sections, there are a few others that you
should be aware of when developing Java applications:

file:///F|/books/java%20books/Java%20Bible/ch07/07-03.html (3 of 4)6/26/2005 7:56:13 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

• You can assume the user will precede all options, flags, or series of flags with the dash
character(-).
• The names of files your program will use (operate on) are typically the last argument on the
command line.
• Your application should output a usage statement whenever a command-line argument can’t be
recognized; it should have the following form:

usage: application_name [ optional_args ] required_args

Using Command-Line Arguments in the HelloWorld Application

Now that you are comfortable with the concept of command-line arguments, it’s time to put what you’ve
learned to good use. We’ll start by enhancing HelloWorld to accept and process the most basic
command-line argument, and then walk through a generic command-line parser that you can customize
for your own specific purposes.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch07/07-03.html (4 of 4)6/26/2005 7:56:13 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Enhancing the HelloWorld application

When it comes to enhancing our existing HelloWorld application, there really isn’t much to work with.
The program was only a few lines of Java code that output “Hello World!” when executed. Since there
isn’t a lot of code to integrate with support for command-line arguments, this will seem like a major
overhaul. But, in reality, we’re only adding very rudimentary command-line argument support for the
moment.

As always, we’ll choose a new name for our program, since it’s a very different program than the one
we created several chapters ago. The real reason we’re adding support for command-line arguments
(aside from the pulse-pounding adrenaline rush) is to make our program more flexible by being able to
process information supplied by the user at the time of execution. For this reason, we’ll call our new
program FlexibleHelloWorld (see Listing 7-1).

Listing 7-1: FlexibleHelloWorld.java source code

/**
* FlexibleHelloWorld.java
*
* “Flexible” HelloWorld application. Uses command-line
* arguments as part of the standard “Hello” output to user.
*
* @author Aaron E. Walsh
* @version 1.0, 17 Jan 98
*/

class FlexibleHelloWorld {
public static void main (String args[]) {
int argCount, i=O;
String theArg;
argCount = args.length;
System.out.println(“Total number of arguments: ” +

file:///F|/books/java%20books/Java%20Bible/ch07/07-04.html (1 of 4)6/26/2005 7:56:14 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

argCount);

while (i < argCount) {


theArg = args[i];
i = i+1;
System.out.print(i + “:” + theArg );
System.out.println(“...Hello ” + theArg + “!”);
}
}
}

Did you notice that the name of the class, FlexibleHelloWorld, isn’t exactly the same as the name
of the file it is saved in? This is because we didn’t specify the class as being a public class. If
we had, the name of the source code file would have to be the same as the public class it
contains. In this case, the source code file would be named FlexibleHelloWorld.java to reflect the
public FlexibleHelloWorld class it defines. However, since the class isn’t public, the file name
can be anything we’d like. For details on public classes, see Chapter 11.

By this point, you should be comfortable with the process of creating and compiling a new Java
program. Assuming you’ve entered the source code exactly as it appears in Listing 7-1, it will compile
without a problem. With that done, let’s step through the code that you may not be familiar with. That is,
the code dealing with command-line arguments:

public static void main (String args[]) {..}

Although you’ve seen the main() method signature several times before, now you’re seeing it with new
eyes. In particular, the args parameter stands out. And for good reason: It’s the array that contains all
command-line arguments received by our program. It’s easy to see that we’re dealing with an array, and
not just one string, thanks to the brackets ([]) that appear immediately after the variable name.

Following this method signature (which happens to be the only method in the program) are the variables
our program uses when processing the arguments:

int argCount, i=0;


String theArg;

The first two variables, argCount and i, are integers. You’ll notice that i is initialized to zero, while
argCount isn’t initialized at all. The i variable is used as a subscript for accessing elements in the args
array, and so I’ve taken the liberty of initializing it to the index value for the first element. This
technique was described earlier, and ensures we begin accessing array elements at the very beginning.
By initializing it here, we don’t have to worry about setting its value later.

file:///F|/books/java%20books/Java%20Bible/ch07/07-04.html (2 of 4)6/26/2005 7:56:14 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

We don’t have to bother initializing argCount, however, since the first line of code sets this variable equal
to the total number of elements in the array:

argCount = args.length;

Here, we’ve used the array instance variable length to determine how many command-line arguments
were passed into our application. We then output this value to the screen with the following line:

System.out.println(“Total number of arguments: ” + argCount);

The last portion of code is a while loop, in which each argument in the args array is retrieved in
succession and output along with its position in the array:

while (i < argCount) {


theArg = args[i];
i = i+1;
System.out.print(i + “:” + theArg );
System.out.println(“...Hello ” + theArg + “!”);
}

Executing with command-line arguments

When executed, this program outputs the number of command-line arguments supplied at the time of
execution and then drops into the while loop. Once in the loop, each element in the args array at index
value i is retrieved and output, as shown in Figure 7-1.

The four lines of code inside the loop were chosen to illustrate the “off by one” problem discussed
earlier. Experienced programmers would likely have written the loop with only two lines of code in the
body:

while (i < argCount) {


theArg = args[i++];
System.out.println(i + “:” + theArg + “...Hello ”+
theArg + “!”);
}

This loop is functionally the same as our original one, yet takes half as many lines of code. You’ll notice
in both cases that our array subscript, i, is increased by one inside the body of the loop. Of particular
interest is where this increment takes place: after the array element has been retrieved, yet before it is
output to the screen. This is due to the “off by one” situation we’ve been dealing with all along.

file:///F|/books/java%20books/Java%20Bible/ch07/07-04.html (3 of 4)6/26/2005 7:56:14 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

Figure 7-1: When in the while loop, each element in the args array is retrieved and output.

Coming into the loop for the first time, our subscript i is 0 (zero). Using an index value of 0 ensures that
we retrieve the first element in the array. However, we want to tell the user that we’ve received the first
command-line argument, not the zero item! So, we bump up the index value by one before using it, to
tell the user what argument we’ve processed.

In doing so, we’ve dealt with the “off by one” situation, while also incrementing the index to ensure that
the next element in the array is retrieved as we repeat the loop. If we incremented the index after the
output statement, as shown in the following code snippet, we’d be off by one (see Figure 7-2):

while (i < argCount) {


theArg = args[i];
System.out.print(i + “:” + theArg );
System.out.println(“...Hello ” + theArg + “!”);
i = i+1; /* RESULTS IN THE ABOVE OUTPUT BEING OFF BY ONE! */
}

Figure 7-2: By incrementing our counter after the print statements, our output appears “off by one,”
even though it is correct: The user would prefer to see the numbering begin at one, not zero.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch07/07-04.html (4 of 4)6/26/2005 7:56:14 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

However, we could have incremented the index inside the conditional portion of the while statement, as
long as we subtracted one from it when retrieving elements in the array:

while (i++ < argCount) {


theArg = args[i-1];
System.out.print(i + “:” + theArg );
System.out.println(“...Hello ” + theArg + “!”);
}

Many programmers prefer this style of code; it’s very clear, going into the loop, where the index is
incremented and by how much. And, since there is only one line of code that accesses the array, we
don’t have to spend much mental energy keeping track of what’s going on.

But suppose we forgot to subtract one from the index in that line of code? Thanks to Java’s runtime
bounds-checking facilities, you’d know the first time the program was executed. In this case, the runtime
system throws an ArrayIndexOutOfBoundsException exception, as shown in Figure 7-3.

Figure 7-3: The runtime system throws an ArrayindexOutOfBoundsException exception if the index in
the code is out of the legal range.

Spaces and quotations

In each of the preceding examples, we’ve supplied two command-line arguments: howdy and doodie. I
stuck to these two arguments throughout the examples in order to make the output in each case
consistent and easy to follow. However, any number of arguments could have been provided. Since the
system interprets the space character as a separator for command-line arguments, we can feed our
program as many arguments as we’d like, as long as each is separated by a space.

file:///F|/books/java%20books/Java%20Bible/ch07/07-05.html (1 of 5)6/26/2005 7:56:14 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

But what if you need to supply a space as part of the argument itself? In this case, you would need to use
quotation marks on the command line. Any text surrounded by quotation marks is treated as a single
argument, as illustrated in Figure 7-4.

Figure 7-4: Text surrounded by quotation marks is treated as a single argument.

Parsing arguments

Our FlexibleHelloWorld application is an extremely simple program. It accepts command-line


arguments and outputs them in the order they were supplied. Sure, it also outputs the total number of
arguments supplied, and uses the arguments as part of the Hello output, but as far as real functionality
goes, the program is just about worthless.

Many programs that accept command-line arguments do so to allow the user a degree of control over
some aspect of execution. Such is the case with UNIX and DOS utility programs. Take, for instance, the
utility program that displays files in a directory. In DOS, the dir program is used, while UNIX users rely
on ls. In both cases, the user can supply command-line arguments along with the program that affect the
way in which files are listed.

Since a number of different arguments can be provided, the program must somehow find out which one
(s) the user is supplying. To complicate matters, these arguments can be supplied in any order. Because
it’s entirely up to the program to figure out which commands were used and act accordingly, the
program must parse the command line.

To help you parse command-line arguments in your own Java applications, you can use a generic
command-line parser (see Listing 7-2) as the basis for your own work. This skeleton program accepts
command-line arguments of each type: a word argument (-verbose), an argument that requires an
argument (-out, which must be followed by the name of a file to be used for output), and several flags (?,
x, y, and z). In addition, this program requires a file name (an input file). If the program is invoked
without the proper arguments, a usage statement is output in accordance with command-line argument
conventions. (See the “Other conventions” section earlier in this chapter.)

Listing 7-2: ParseSkeleton .java, a generic command-line\ argument parser

/*

file:///F|/books/java%20books/Java%20Bible/ch07/07-05.html (2 of 5)6/26/2005 7:56:14 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

A generic command-line argument parser. (you must first


understand Java strings, arrays, and loops before this code
will make complete sense).
*/
class ParseSkeleton {

public static void main(String args[]) {


String command = “”; /* to hold each command-line
argument as

they are processed */


boolean verbose = false; // initialize verbose flag to
false
boolean xFlag= true, yFlag= true, zFlag = true; /* a few
flags, initialized to false
*/
String outputfile = “”; /* variable to recieve -out
argument’s
argument */
int i = O; // a little variable to control our while
loop...
/* — Parse all command-line arguments via a while loop —
*/
while (i < args.length && args[i].startsWith(“-”)) {
command = args[i++];
/* --- Parse Word Arguments --- */
if (command.equals(“-verbose”)) {
verbose = true;
}
/* —- Parse Arguments That Require Arguments —- */
else if (command.equals(“-out”)) {
if (i < args.length) {
outputfile = args[i++];
} else {
System.err.println(“The -out argument must be
followed
by an output file name!”);
}
}
/* —- Parse Flags —- */
else {
char flag; // a temporary variable to process flags
for (int loop = 1; loop < command.length(); loop++) {

file:///F|/books/java%20books/Java%20Bible/ch07/07-05.html (3 of 5)6/26/2005 7:56:14 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

flag = command.charAt(loop);
switch (flag) {
case ’?’:
System.out.println(“ --------- HELP ----------
”);
System.out.println(“Help? You want help? Try calling 911...”);
System.out.println(“Ring...”);
System.out.println(“Ring...”);
System.out.println(“Ring...”);
System.out.println(“Sorry, all operators are taking a coffee
break. Try again
later.”);
System.out.println(“-----------------------------”);
break;
case ’y’:
yFlag = true;
if (verbose) System.out.println(”The y option has been
specified.“);
break;
case ’x’:
yFlag = true;
if (verbose) System.out.println("“he y option has been
specified.”);
break;
case ’z’:
zFlag = true;
if (verbose) System.out.println(“The z option has been
specified.”);
break;
default:
System.err.println(flag + “ is not a valid option!”);
break;
}
}
}
}
/* — The final verdict? — */
if (i == args.length) {
System.err.println(“Usage: ParseSkeleton [-verbose] [-?xyz]
[-out outputFile] inputFile”);
}
else if (verbose) {
System.out.println(“Input file = ”+ args[i++]);

file:///F|/books/java%20books/Java%20Bible/ch07/07-05.html (4 of 5)6/26/2005 7:56:14 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

System.out.println(“Output file = ”+ outputfile);


}
}
}

The following is the usage statement for the program:

Usage: ParseSkeleton [-verbose] [-?xyz] [-out outputFile]


inputFile

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch07/07-05.html (5 of 5)6/26/2005 7:56:14 PM


file:///F|/books/java%20books/Java%20Bible/ch07/images/07-01.jpg

file:///F|/books/java%20books/Java%20Bible/ch07/images/07-01.jpg6/26/2005 7:56:15 PM
file:///F|/books/java%20books/Java%20Bible/ch07/images/07-02.jpg

file:///F|/books/java%20books/Java%20Bible/ch07/images/07-02.jpg6/26/2005 7:56:16 PM
Java Bible:Command-Line Arguments and Applet Tag Attributes

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Although the arguments inside brackets ([ ]) are optional, the filename argument is required. If you don’t
include a filename argument when executing this program, the usage statement will be displayed. Figure
7-5 shows this output, in addition to the output produced when the program is executed properly.

Figure 7-5: ParseSkeleton is executed initially without command-line arguments and then again with
several arguments specified on the command line.

The ParseSkeleton.java program makes use of the Array, String, and System classes. If you find this
code difficult to understand, you might consider turning ahead to Chapter 12 and Chapter 13
for detailed information on these classes before attempting to integrate this program with your
own.

Applet Attributes

Now that you’re comfortable with receiving and processing command-line arguments within Java
applications, chances are your attention wants to turn to the applet. After all, most of you will be dealing
with applets, and many may never bother with applications beyond what we cover in this book. But how
is information passed to an applet?

While it’s pretty obvious that command-line arguments are supplied on the command line at the time of
execution, an applet is downloaded from the Web and passed to the Java runtime environment for
execution. At first glance, there doesn’t seem to be a mechanism for supplying applets with user-defined
information, as there is with applications. But there is, and it’s an elegant one: applet attributes.

What are applet attributes?

Applet attributes are specified in the <APPLET> HTML tag, and provide information that either the
browser, the Java runtime system, or the applet itself will use to execute properly. The HEIGHT and

file:///F|/books/java%20books/Java%20Bible/ch07/07-06.html (1 of 4)6/26/2005 7:56:16 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

WIDTH items specified in all the HTML documents we’ve created so far are actually applet attributes,
just as the name of the class file we specify for CODE is:

<APPLET CODE:“MediaHelloWorld.class” WIDTH=200 HEIGHT=150>

At a minimum, these three attributes must be included in the <APPLET> tag. They are required, whereas
the majority of applet attributes are optional.

The identifiers used to specify applet tags (such as CODE, HEIGHT, and WIDTH) are not case-
sensitive. They can be in uppercase, lowercase, or a mixture of both. For the sake of
readability, however, it’s a good idea to use uppercase. The values you provide for these
attributes, such as MediaHelloWorld.class in the above example, are another matter. Be certain to
use the proper case: MediaHelloWorld.class is not the same as MEDIAHELLOWORLD.CLASS!

The following code illustrates the basic structure of the <APPLET> tag:

<APPLET standard-attributes>
applet-parameters
alternate-context
</APPLET>

Until now, we’ve only specified standard applet attributes. And of these standard attributes, we’ve only
used the three that are required: CODE, HEIGHT, and WIDTH.

There are a number of optional applet attributes. Although they are optional, they are still considered
part of the standard suite. Table 7-1 details all required attributes, while Table 7-2 describes the optional
ones.

Table 7-1
Required Applet Attributes

Attribute Description

CODE Specifies the name of the class file (applet), which must be a subclass of java.awt.
Applet.

WIDTH Specifies the initial width of your applet in pixels.

file:///F|/books/java%20books/Java%20Bible/ch07/07-06.html (2 of 4)6/26/2005 7:56:16 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

HEIGHT Specifies the initial height of your applet in pixels.

To use an optional attribute, you simply include its name and an associated value within the <APPLET>
start tag. The start tag begins with <APPLET and ends with a closing angle bracket (>). You can supply
optional attributes after the required ones, as long as they are inside the closing angle bracket:

<APPLET CODE=“MediaHelloWorld.class” WIDTH=200 HEIGHT=150


ALIGN=top>

Table 7-2
Optional Applet Attributes

Attribute Description

ALIGN Specifies where your applet is placed on the page in respect to the text
around it. It can have one of the following nine alignments: left, right, top,
texttop, middle, absmiddle, baseline, bottom, and absbottom.

ALT Specifies alternate text to be displayed by text-only browsers.

CODEBASE Specifies the base URL for your applet. The applet itself must be located
relative to this URL If CODEBASE isn’t specified, the URL of the HTML
document in which the applet is embedded is used.

HSPACE Specifies the horizontal space surrounding your applet. The value you
specify for HSPACE is used only when the ALIGN attribute is set to left or
right.

NAME Specifies the symbolic name of your applet, allowing other applets
embedded in the same page to locate your applet by name.

VSPACE Specifies the vertical space surrounding your applet. The value you
specify for VSPACE is used only when the ALIGN attribute is set to left or
right.

file:///F|/books/java%20books/Java%20Bible/ch07/07-06.html (3 of 4)6/26/2005 7:56:16 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

ARCHIVE Specifies one or more archives (for example, JAR files) that will be
preloaded. Classes are loaded using an instance of the AppletClassLoader
with the CODEBASE specified. JAR files are discussed in more detail in
Chapter 15, “Weaving Applets into Web Pages.”

OBJECT Specifies the name of a class that contains a serialized version of an


applet. When a serialized applet is loaded, its init() method is not invoked,
but its start() method will be. An applet must have either the OBJECT or
CODE attribute specified.

Although Applet Viewer will resize itself in response to an applet invoking the resize() method,
not all browsers will do so. Netscape Navigator, for example, sets the size of an applet to the
values specified in HTML by the WIDTH and HEIGHT attributes and ignores calls to resize()
altogether!

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch07/07-06.html (4 of 4)6/26/2005 7:56:16 PM


file:///F|/books/java%20books/Java%20Bible/ch07/images/07-03.jpg

file:///F|/books/java%20books/Java%20Bible/ch07/images/07-03.jpg6/26/2005 7:56:17 PM
file:///F|/books/java%20books/Java%20Bible/ch07/images/07-04.jpg

file:///F|/books/java%20books/Java%20Bible/ch07/images/07-04.jpg6/26/2005 7:56:18 PM
Java Bible:Command-Line Arguments and Applet Tag Attributes

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

As a result, you shouldn’t rely on the resize() method to work as you’d expect. Instead, rely on the WIDTH
and HEIGHT attributes that are required in all <APPLET> tags.

Here, we’ve added the optional ALIGN attribute, specifying a value of top. When the browser loads this
applet, the top of it will be aligned to the surrounding text (see Figure 7-6). Had we specified bottom, the
bottom of applet would have been aligned to the surrounding text, as shown in Figure 7-7.

Figure 7-6: The top of the applet is aligned to the surrounding text, using the ALIGN attribute and
specifying a value of top.

Figure 7-7: The bottom of the applet is aligned to the surrounding text by specifying a value of bottom.

It’s worth noting that the start tag can extend over several lines, even though we’ve managed to cram it
onto a single line. As long as the opening and closing angle brackets are present, the start tag can span as
many lines as needed:

<APPLET CODE=“MediaHelloWorld.class”
WIDTH:200
HEIGHT=150
ALIGN=top>

Attributes can appear in any order, although it’s a good idea to place the required three immediately
following the word APPLET.

file:///F|/books/java%20books/Java%20Bible/ch07/07-07.html (1 of 4)6/26/2005 7:56:19 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

The following is functionally equivalent to the start tag above, but more difficult to read because you
expect the required attributes to appear first and in a certain order:

<APPLET
ALIGN=top WIDTH=200
CODE=“MediaHelloWorld.class”
HEIGHT=150>

You might have noticed that i didn’t include the </APPLET> end tag in these examples. It is certainly
required! I omitted it simply so we could focus exclusively on the start tag. Without it, the browser
would consider everything following the start tag to the end of your HTML document as part of the
<APPLET> body. An example of proper usage follows:

<APPLET CODE=“MediaHelloWorld.class”
WIDTH=200
HEIGHT=150
ALIGN=top>
</APPLET>

Similarity to command-line arguments

Applet attributes are similar in nature to command-line arguments in that they provide an easy way to
allocate the applet with information. However, the standard suite of attributes won’t allow you to pass
special information to your applet for processing. It merely allows you to set the various attributes
needed by the browser or Java runtime system to execute your applet.

Take, for instance, the CODE attribute. Your applet doesn’t do anything with it, or with any other
standard attribute for that matter. CODE simply tells the browser what file to download and hand off to
the runtime system; it means nothing to your applet.

In this sense, you can think of standard attributes as special settings that the browser and runtime system
use to execute your applet according to your specifications. And while it’s true that methods do exist
that allow your applet to retrieve the values for some of these attributes (such as getCodeBase(), which
returns the base URL for your applet), you can’t use any of the standard attributes to pass special
information to your applet.

If your applet is to be flexible—able to receive and process input—there must be a mechanism for
passing information to it. Thankfully, there is.

Applet “parameter” attributes

In order to pass information to your applet, such as the URL of a file on the Web or a text string to

file:///F|/books/java%20books/Java%20Bible/ch07/07-07.html (2 of 4)6/26/2005 7:56:19 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

display when executed, you’ll need to use an attribute designed for just such a purpose. Specifically,
you’ll have to use an applet parameter attribute, more commonly known simply as an applet parameter.

Applet parameters follow the <APPLET> start tag, yet come before the </APPLET> end tag. They appear
as a pair of name and value attributes inside a <PARAM> tag:

<PARAM NAME=hello VALUE=“Hello World!”>

In this example, the parameter called hello is specified as having the value “Hello World!”. In order to
retrieve this value from within an applet, we must use the getParameter( ) method defined in the Applet
class:

String helloStr = getParameter (“hello”);

Here, we’ve declared a String variable, helloStr, into which we’ve received the value of the hello
parameter. After this line of code is executed, helloStr will contain the string “Hello World!”. Of course, we
could have just as easily declared the variable on one line and retrieved the parameter on another:

String helloStr; /* declare the variable first


*/ helloStr = getParameter (“hello”); /* and then get the
parameter */

Functionally, these two approaches are equivalent. Yet in both cases, we’re assuming an applet
parameter specifying a value for hello exists in the HTML document. We’re expecting something like
this:

<APPLET COOE=“MediaHelloWorld.class” WIDTH=90 HEIGHT=50


ALIGN=top>
<PARAM NAME:hello VALUE=“Hello World!”>
</APPLET>

This HTML code clearly specifies a hello parameter with the value of “Hello World!”. But what if the
second line of code didn’t exist? What if you forgot to include it when creating the HTML document,
yet included the code in your applet to retrieve a hello parameter. In this case, your helloStr variable
would be set to null, since the getParameter() method would fail to find the hello parameter and return null
instead of a valid string.

It’s a good idea to test for null values when processing applet parameters and act accordingly.
In some cases, such as with the code I’ll present here, you may provide default values to allow
your applet to continue executing where it would otherwise fail to run properly.

file:///F|/books/java%20books/Java%20Bible/ch07/07-07.html (3 of 4)6/26/2005 7:56:19 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

As with the identifiers used to specify attributes (CODE, HEIGHT, WIDTH, PARAM NAME, VALUE, and so
on), you can use either uppercase or lowercase letters when associating a value with the PARAM NAME.
As you can see, I’ve supplied the word hello in all lowercase characters. I could just as easily have used
all capital letters (HELLO), or a combination of both (Hello).

Since the getParameter() method isn’t case-sensitive, it really doesn’t matter how we name an applet
parameter. The Java code getParameter(“hello”) will find and return the value associated with hello, HELLO,
or even Hello. However, to make your HTML code easier to read, it’s a good idea to use uppercase
letters for the attribute identifiers (CODE, HEIGHT, and so on) and lowercase for the actual parameter
(such as hello in our example).

Be extremely cautious when entering the attributes of your applet tag! Specifically, make sure when you
enclose items that you only use one set of quote marks. For example, the following is fine:

<PARAM NAME=hello VALUE=“Howdy”>

While this is not:

<PARAM NAME=hello VALUE=“ Howdy”“>

The parameter value in this code, Howdy, has an extra closing quote. No big deal, right?
Wrong! The current version of Applet Viewer will just wait around forever for another closing
quote, even if you didn’t bother to write a corresponding getParameter( ) method. Other
browsers may crash as well, or simply be unable to parse the HTML correctly. Picky, picky...

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch07/07-07.html (4 of 4)6/26/2005 7:56:19 PM


file:///F|/books/java%20books/Java%20Bible/ch07/images/07-05.jpg

file:///F|/books/java%20books/Java%20Bible/ch07/images/07-05.jpg6/26/2005 7:56:19 PM
Java Bible:Command-Line Arguments and Applet Tag Attributes

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

All applet parameters are strings

Because the getParameter() method always returns a String object, all applet parameters—even numeric
parameters—come to you in the form of a string. This is extremely important to realize, since you must
first convert the string to an actual number if you want to use it as such!

Suppose, for instance, that you want to specify an applet parameter that controls how often a while loop
is executed. Your HTML parameter tag might look like this:

<PARAM NAME=loop VALUE=5>

This is just fine. However, the Java source code that you might be tempted to write to retrieve this
parameter might look like this:

int loop = getParameter ("“loop”);

At first, this might look fine as well. But it’s not. Since the getParameter() method returns a string, not an
int, the compiler will choke when it gets to this line of code and generate a “type mismatch” error.

In order to properly retrieve this value, you must receive the parameter as a string and then convert it
into an int. There are two ways you can do this:

String loopString = getParameter(“loop”);


int loop = Integer.valueOf(loopString).intValue();

The first line retrieves the loop parameter in string form, as it should. The second line makes use of the
Integer class, a special class known as a type wrapper.

In Java, numbers (int, long, float, and double data types) are not actually objects. Since most of the Java
utility classes require objects, such numbers must somehow be converted into objects before they can be
used. A direct conversion, or cast, isn’t possible. As a result, we “wrap” the number inside an object
using type wrapper classes. (For details on wrapper classes, see Chapter 12.)

file:///F|/books/java%20books/Java%20Bible/ch07/07-08.html (1 of 3)6/26/2005 7:56:20 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

In the second line of this code, we’ve used the Integer class to convert loopString into an Integer object. We
then invoke the intValue() method, which returns the value of this Integer as an int. It may seem a bit
complicated, but it’s necessary.

The valueOf () method requires a valid string, one that can be used to create an Integer object
initialized to an int value. If the string it receives can’t be treated as an int, an
exception—NumberFormatException—is thrown. For details on exceptions, see Chapter 10,
“Language Fundamentals”.

As an alternative, we could have used the parseInt() method without having to explicitly create a new
Integer object:

String loopString = getParameter(“loop”);


int loop = Integer.parseInt(loopString);

Assuming loopString represents an integer, parseInt() will return the value of that integer. If the String
object passed to parseInt() can’t be treated as an int, the method will throw an exception, just as valueOf ()
would.

When specifying an integer parameter in your HTML file, you either surround the value in quotes, as
you would a string, or leave the quotes off, as we did earlier. As far as your applet is concerned, the
following two lines of HTML code are functionally the same:

<PARAM NAME:loop VALUE=5>


<PARAM NAME=loop VALUE:“5”>

Alternate applet context

Now that you’re familiar with applet attributes and parameters, we come to the part of the <APPLET> tag
known as the alternate applet context. This allows you to include any type of HTML code between the
last applet parameter and the </APPLET> end tag. It is displayed by browsers that are not Java-savvy, and
won’t be visible to users viewing the document with a browser that is capable of dealing with Java
applets.

Alternate applet context can contain any type of HTML code you wish, such as text or tags, or both.
This is an example of text-only applet context:

<APPLET CODE= MediaHelloWorld.class” WIDTH=90 HEIGHT=50


ALIGN=top>
<PARAM NAME=hello VALUE=“Hello World!”>
...This page requires a Java-savvy browser: GET ONE!

file:///F|/books/java%20books/Java%20Bible/ch07/07-08.html (2 of 3)6/26/2005 7:56:20 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

</APPLET>

The line immediately preceding the </APPLET> end tag will appear as standard HTML text to a browser
that doesn’t support Java, as shown in Figure 7-8.

Figure 7-8: Alternate applet context can contain any type of HTML code you wish; it will appear as
standard HTML would.

You’re free to include any type of HTML code to be used as alternate applet context. In the next piece of
code, I’ve added a simple hypertext link that will bring users to Sun’s Java home page when they click
the words “GET ONE!”:

<APPLET COOE:“MediaHelloWorld.class” WIDTH:90 HEIGHT=50


ALIGN=top>
<PARAM NAME=hello VALUE=“Hello World!”>
...This page requires a Java-savvy browser:
<A HREF=“http://www.javasoft.com”>GET ONE!</A>
</APPLET>

Of course, you’re not limited to text. You could just as easily display a graphic using the <IMG> tag, or a
combination of both text and graphics. What you provide as alternate applet context depends on how
you want your page to look to users who don’t use a Java-savvy browser.

In most cases it’s a good idea to include alternate applet context when creating your HTML
pages, even if it’s nothing more than a “You need a Java browser to see this page!” message. If
you don’t, those users who view your pages using a browser that doesn’t support Java will
have no idea that they are missing out on something.

Using Applet Attributes in MediaHelloWorld

Now that we’re comfortable with applet attributes, especially the special-purpose PARAM attribute, it’s
time to create a flexible version of the MediaHelloWorld applet created in Chapter 6. While there are
many ways to customize an application, we’ll extend MediaHelloWorld by allowing it to receive input
through parameter attributes.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch07/07-08.html (3 of 3)6/26/2005 7:56:20 PM


file:///F|/books/java%20books/Java%20Bible/ch07/images/07-06.jpg

file:///F|/books/java%20books/Java%20Bible/ch07/images/07-06.jpg6/26/2005 7:56:21 PM
file:///F|/books/java%20books/Java%20Bible/ch07/images/07-07.jpg

file:///F|/books/java%20books/Java%20Bible/ch07/images/07-07.jpg6/26/2005 7:56:21 PM
Java Bible:Command-Line Arguments and Applet Tag Attributes

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

The source code in Listing 7-3 adds great flexibility beyond the MediaHelloWorld applet it subclasses.
For this reason, we’ll call this new program FlexibleMediaHello. Unlike its predecessor,
FlexibleMediaHello does not rely on hard-coded filenames when it comes to displaying a graphic image
and playing a background sound track, since these may be supplied as applet parameters. If these
parameters are omitted from the HTML file in which our applet is embedded, FlexibleMediaHello uses
defaults that are defined in the program itself.

Listing 7-3: FlexibleMediaHello.java source code

/**
* FlexibleMediaHello.java
*
* “Flexible” extension of the HelloWorld applet.
* Displays “Hello World!” string in applet canvas while a
* background audio track plays and an image follows the mouse
* around.
* “Flexible” due to the ability to accept <PARAM> applet
* attributes specified within the <APPLET> tag, allowing URLs to
* audio and image files to be used in the HTML document that
* references this applet.
*
* @author Aaron E. Walsh
* @version 1.0, 17 Jan 98
*/

import java.applet.*;
import java.awt.*;
import java.net.URL;
import java.net.MalformedURLException;

public class FlexibleMediaHello extends HelloWorldApplet {

file:///F|/books/java%20books/Java%20Bible/ch07/07-09.html (1 of 6)6/26/2005 7:56:22 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

String helloString;
Image myImage;
AudioClip myAudio;
int horizontal, vertical;
boolean SoundOn = true;

public void init() {

/* GET THE APPLET PARAMETERS: */


helloString = getParameter (“hello”);
String imageString = getParameter (“image”);
String audioString = getParameter (“sound”);

/* GET FILES USING PARAMETERS: */


if (imageString==null) {
myImage=getImage(getCodeBase(), “images/world.gif”);
}
else {
URL imageURL=null;
try {
imageURL = new URL(imageString);
}catch (MalformedURLException e) { ; }
myImage=getImage(imageURL);
}

if (audioString==null) {
myAudio=getAudioClip(getCodeBase(), “audio/hello.au”);
}
else {
URL audioURL=null;
try {
audioURL= new URL(audioString);
}catch (MalformedURLException e) { ; }
myAudio=getAudioClip(audioURL);
}
}

public void paint(Graphics g) {

if (myImage != null) {
g.drawImage(myImage, horizontal, vertical, this);
}

file:///F|/books/java%20books/Java%20Bible/ch07/07-09.html (2 of 6)6/26/2005 7:56:22 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

if (helloString==null) {
super.paint(g);
} else {
g.drawString(helloString,50,100);
}
}

public void start() {


myAudio.loop();

}
public void stop() {
myAudio.stop();
}
public boolean mouseDown(java.awt.Event event, iht x, int y) {
if (SoundOn) {
myAudio.loop();
SoundOn = false;
}
else {
myAudio.stop();
SoundOn = true;
}
return true;
}

public boolean mouseMove(java.awt. Event event, int x, int y) {


horizontal:x;
vertical=y;
repaint();
return true;
}
}

file:///F|/books/java%20books/Java%20Bible/ch07/07-09.html (3 of 6)6/26/2005 7:56:22 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

Unlike our FlexibleHelloWorld application, we’ve defined the applet version of this program
to be public. More precisely, the class declaration of the applet shown in Listing 7-3,
FlexibleMediaHello, has been declared public. As a result, the file containing the source code
for this program must have the same name: FlexibleMediaHello.java. (For details on public
classes, see Chapter 11.) In addition, FlexibleMediaHello is no longer hard-coded to output
“Hello World!” in the paint() method; it will display whatever text is associated with the hello
parameter supplied in the <APPLET> tag. If this parameter is omitted, it calls upon its
superclass, MediaHelloWorld, to perform the paint() operation. Because MediaHelloWorld calls
upon its own superclass when paint() is invoked, the paint() method we created in our original
HelloWorldApplet program is used! As a result, “Hello World!” will be output to the screen
(see Figure 7-9).

Figure 7-9: Using the super keyword, our program can now invoke the paint() method of its superclass,
which itself invokes the paint() method of its own superclass!

At this point, the source code for FlexibleMediaHello should make sense to you. It may be a little more
complex than what we’ve dealt with so far, but there are only two elements that should cause you to
raise an eyebrow: uniform resource locators (URLs) and exceptions.

URLs and exceptions

Our original HelloWorldApplet program used a sound and image file, both located relative to the applet
itself. We have since augmented the program to make it more flexible (see Listing 7-3); it now has the
ability to retrieve these files, as specified by a URL. To provide our applet with this capability, we
imported the class that deals with URLs:

import java.net.URL;

However, to allow our program to form a URL from a String object, we also had to handle exceptions
that might arise in the process. Although exceptions are discussed in detail in Chapter 10, for now you
can think of them as general-purpose error handling mechanisms. In order to deal with the possible
exceptions that might occur when creating URLs, we included the following import statement:

import java.net.MalformedURLException;

file:///F|/books/java%20books/Java%20Bible/ch07/07-09.html (4 of 6)6/26/2005 7:56:22 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

Both of these classes could have been included in your program using one line:

import java.net.*

The asterisk is treated as a wild card, meaning all classes in the network package will be available to
your program, instead of any specific one.

Understanding the code

The most significant changes to our original code are in the init() method. It is here that we retrieve and
process the applet parameters that our program now supports: hello, image, and sound. This code shows
you how these parameters might be specified:

<PARAM NAME:hello VALUE=“Hickory, dickory, doc.”>


<PARAM NAME=image
VALUE=“http://www.anywhere.com/images/picasso.gif”>
<PARAM NAME:sound

VALUE=“http://www.anywhere.com/audio/milesdavis.au”“>

Due to security restrictions imposed by Java, applets can only load URLs that point to
resources located on the host on which the applet itself resides. As a result, the URLs I’ve just
specified are only valid when the FlexibleMediaHello applet is executed from Mantis
Development Corp.’s Web site. This means that any Web page that references this applet must
either reside on this host, or use the CODEBASE applet attribute to point to it. For more details
on the CODEBASE applet attribute, refer to Chapter 15.

The changes to the init() method are substantial, although easy to understand if you walk through them
step by step. The first three lines of code do nothing more than load the applet parameters:

helloString = getParameter (“hello”);


String imageString = getParameter (“image”);
String audioString = getParameter (“sound”);

The first line sets the variable helloString equal to the value associated with the hello applet parameter
specified in our HTML file. Unlike the next two lines, which declare the variables imageString and
audioString on the same line as their assignment statements, the helloString variable is declared outside the
scope of init().

file:///F|/books/java%20books/Java%20Bible/ch07/07-09.html (5 of 6)6/26/2005 7:56:22 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch07/07-09.html (6 of 6)6/26/2005 7:56:22 PM


file:///F|/books/java%20books/Java%20Bible/ch07/images/07-08.jpg

file:///F|/books/java%20books/Java%20Bible/ch07/images/07-08.jpg6/26/2005 7:56:23 PM
Java Bible:Command-Line Arguments and Applet Tag Attributes

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

As such, it is available to all methods in the class, not just init(). Since we only need imageString and
audioString long enough to create a URL object from each, we declared these variables on the spot.
Thanks to Java’s automatic garbage collection, the memory associated with these variables is released
once the init() method has executed.

Most programmers are accustomed to declaring ali variables before the first line of executable
code. In C, the compiler would choke because the executable line of code helloString =
getParameter (“hello”); appears before the string variables are declared. With Java (and C++) you
can declare a variable where it is needed, just as we have done.

Once we’ve retrieved the parameters, they are processed. We begin with the image parameter, using the
imageString variable that now contains the value associated with this parameter:

if (imageString==null) {
myImage=getImage(getCodeBase()?? “images/world.gif”);
}
else {
URL imageURL=null;
try {
imageURL = new URL(imageString);
}catch (MalformedURLException e) { ; }
myImage=getImage(imageURL);
}

First, we check to see if the HTML document did indeed specify an image parameter. If the parameter
isn’t specified, imageString will be null. In this case, we use the same line of code found in
MediaHelloWorld as a default.

If an image parameter was specified in the HTML document, we attempt to build a URL from it. First,
we declare a URL variable, and set it to null:

URL imageURL=null;

file:///F|/books/java%20books/Java%20Bible/ch07/07-10.html (1 of 4)6/26/2005 7:56:23 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

Once the variable exists, we use a special try-catch clause to form what is known as an exception
handler. We “try” to form the URL, and if the operation fails we “catch” the error:

try {
imageURL = new URL(imageString);
}catch (MalformedURLException e) { ; }

However, you’ll notice that we don’t actually do anything if an error occurs. Rather than add complexity
to the code, we ignore it entirely. This is intentional, since we’ll deal with exceptions in Chapter 10. For
this chapter, you need only know that any error-handling code would appear in the braces, where now
only a semicolon exists.

Regardless of the outcome from our exception handler, we next attempt to load the image from the
resulting URL:

myImage=getImage(imageURL);

In an actual production environment, you’d handle any exceptions and ensure the URL was valid before
attempting to use it. For details on how this is done, refer to Chapter 10. At the moment, we’re not
concerned with making this applet bulletproof; we’re mainly concerned with processing parameters.

You may have noticed that our code contains two versions of the getImage() and getAudioClip()
methods. In procedural programming languages such as C, the compiler wouldn’t permit two
versions of the same function to exist. Yet in Java and C++ it is not only possible but is a vital
part of the language: Methods in a class can share the same name as long as the parameter list
is different. This is a feature known as overloading, which is supported by most object-
oriented programming languages.

After processing the image parameter, we process the sound parameter, following the same steps. When
our init() method is complete, we’ve retrieved all three parameters and processed two of them. With that
done, the remaining code is nearly identical to that of our original HelloWorldApplet program. The only
place where the code differs is in the paint() method:

public void paint(Graphics g) {


if (myImage != null) {
g.drawImage(myImage, horizontal, vertical, this);
}

if (helloString==null)
{super.paint(g);
}

file:///F|/books/java%20books/Java%20Bible/ch07/07-10.html (2 of 4)6/26/2005 7:56:23 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

else {
g.drawString(hellloString,50,100);
}
}

Here, we draw the image at the horizontal and vertical coordinates set in our mouseMove() method, just as
we did in HelloWorldApplet. However, we also test helloString to determine if a hello applet parameter was
supplied in our HTML document. If this parameter was omitted, our helloString is null. In this case, we
invoke the paint() method of FlexibleMediaHello’s superclass. If not, we output the value supplied with the
hello parameter.

Writing the HTML document

The next piece of code supplies all the applet parameters in the HTML document. FlexibleMediaHello
will use each one during execution. You should keep in mind, however, that applets are only able to
access files residing on the same Web site from which they come. This security restriction, discussed in
Chapter 15, means the following HTML example will work only when the applet itself resides on the
Mantis Development Corp.’s Web server or on your local computer. Of course, you’re free to change the
image and sound URLs to point to files on your own server.

When an applet doesn’t reside on the Web, however, it’s treated as a “trusted” program. As a result,
your Web browser isn’t as paranoid: Local applets are allowed to access files residing on the Web
without concern for what server these files are coming from. This means you’ll be able to hear and see
the files the following HTML document points to, if it and the applet are located on your hard drive (or
CD-ROM, as the case may be):

<HTML>
<HEAD>
<TITLE> “Flexible” MediaHelloWorld Applet Test </TITLE>
</HEAD>
<BODY>

Here is our flexible applet:

<APPLET CODE=“FlexibleMediaHello.class”
WIDTH:200 HEIGHT=150
ALIGN:top>
<PARAM NAME=hello VALUE=“Hello! How are you?”>
<PARAM NAME=image
VALUE:“http://www.mantiscorp.com/images/mdchomebutton.gif”>
<PARAM NAME=sound
VALUE=“http://www.mantiscorp.com/java/classes/audio/welcomeIntr

file:///F|/books/java%20books/Java%20Bible/ch07/07-10.html (3 of 4)6/26/2005 7:56:23 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

o.au”>
...This page requires a Java-savvy browser:
<A HREF=“http://www.javasoft.com”>GET ONE!</A>
</APPLET>
</BODY>
</HTML>

This use of applet parameters is illustrated in Figure 7-10. If the sound and image files pointed to by the
URL exist on the same host as the applet itself, they are utilized.

Figure 7-10: FlexibleMediaHello, no longer bound to hard-coded values, displaying an image pulled
off the Web

The CODEBASE Attribute Saves Time

Using the CODEBASE attribute, HTML documents can utilize applets residing anywhere on the Web.
Suppose, for example, that the following CODEBASE attribute were included in the HTML file:

CODEBASE:“http://www.mantiscorp.com/java/applets/FlexibleMediaHel
lo/”

In this case, the applet specified by the CODE attribute would be coming from the Mantis Development
Corp’s Web server. As a result, the files pointed to by the image and sound URLs would also have to be
located on this server.

Also note that, even though the image and sound files appear to be loaded in our init() method, this isn’t
the case. Only when the image is first drawn is it downloaded to the user’s computer, and the sound file
isn’t downloaded until it’s first played. This saves time and processing power in the event that you
reference an audio or graphics file that isn’t used. Why bother downloading a file if it isn’t actually used?

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch07/07-10.html (4 of 4)6/26/2005 7:56:23 PM


file:///F|/books/java%20books/Java%20Bible/ch07/images/07-09.jpg

file:///F|/books/java%20books/Java%20Bible/ch07/images/07-09.jpg6/26/2005 7:56:24 PM
Java Bible:Command-Line Arguments and Applet Tag Attributes

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Applets that make use of parameters are tightly coupled to the HTML file in which the parameters are
supplied. As a result, you must consider the HTML file as you design your program. You must consider
not only the parameters that your applet will use, but what each should be named and how they should
be organized.

Applet usage guide

Some applets require a great number of parameters to be specified in the HTML document, making it a
chore to recall which parameter does what. It’s a good idea to provide a usage guide with your applets
that specifies how the parameters are to be used. In this guide, you should group similar parameters.
This will reduce any confusion that may result when someone else attempts to configure an HTML
document that references your applet. Following is a sample usage guide for FlexibleMediaHello:

<APPLET CODE:“FlexibleMediaHello.class” WIDTH:ZOO HEIGHT=150>


<PARAM NAME=hello VALUE:“Hello! How are you?”>
<PARAM NAME=image
VALUE=“http://www.mantiscorp.com/images/earth.gif”>
<PARAM NAME=sound
VALUE=“http://www.mantiscorp.com/audio/welcome.au”>
...This page requires a Java-savvy browser:
<A HREF=“http://www.javasoft.com”>GET ONE!</A>
</APPLET>

FlexibleMediaHello is a simple applet that takes three parameters:

• hello: A string that is output as text on the Web page. The default for this parameter is “Hello
World!”.
• image: A URL pointing to a GIF or JPEG graphics file that will follow the mouse cursor around
as it’s moved in the applet. The default for this parameter is not a URL, but a GIF file named
world.gif, which is assumed to be located in an images directory relative to the applet itself.
• sound: A URL pointing to a AU format sound file that will play continuously once the applet is
loaded. The default for this parameter is not a URL, but an .au file named hello.au, which is
assumed to be located in an audio directory relative to the applet itself.

file:///F|/books/java%20books/Java%20Bible/ch07/07-11.html (1 of 2)6/26/2005 7:56:24 PM


Java Bible:Command-Line Arguments and Applet Tag Attributes

If one of these three parameters is omitted, the defaults are used. The HTML file shown next omits all
three parameters, relying on the default values our applet provides for each:

<HTML>
<HEAD>
<TITLE> “Flexible” MediaHelloWorld Applet Test </TITLE>
</HEAD>
<BODY>

Here is our flexible applet:

<APPLET CODE:“FlexibleMediaHello.class” WIDTH=200 HEIGHT=150>


...This page requires a Java-savvy browser:
<A HREF=“http://www.javasoft.com”>GET ONE!</A>
</APPLET>
</BODY>
</HTML>

Summary

With Java, we can write two very different types of programs: applications and applets. In this chapter
you learned how to prepare you Java applications and applets for the ever changing world out there.
Things to remember when writing dynamic applications and applets include:

• Java command-line arguments are arguments that are passed to a Java application when it is
invoked from the command line.
• Where applications are stand-alone programs that reside in and are executed on a local
environment, applets live on the Web and are downloaded by a Java-savvy browser before they
are executed.
• By necessity, and due to their very nature, applications and applets are further distinguished by
the manner in which you can pass information to each prior to execution.
• Applications accept arguments on the command line, much like C/C++ programs, while applets
accept special attributes supplied in the <APPLET> HTML tag. By taking advantage of these
mechanisms, we’re able to develop robust, powerful, and fully customizable Java programs.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch07/07-11.html (2 of 2)6/26/2005 7:56:24 PM


file:///F|/books/java%20books/Java%20Bible/ch07/images/07-10.jpg

file:///F|/books/java%20books/Java%20Bible/ch07/images/07-10.jpg6/26/2005 7:56:25 PM
Java Bible:Surfing the Web for Java Source Code

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

CHAPTER 8
Surfing the Web for Java Source Codey
In This Chapter

Finding cool Java applets — rely to use in your own applications — on the Web

Surfing up some coot Java development resources on the Web

Using Internet search engines to find Java applets

Making sure you give the pro per credit for code you’ve borrowed

Although the CD-ROM included with this book contains a hefty number of applets and their source
code, including those supplied with the original and current Java Development Kit (JDK 1.02 and JDK
1.1.5), you’ll probably want even more. Perhaps you need an example not provided with the JDK, want
to see how a particular feature is coded, or are simply interested in the latest Java developments.
Whatever the case, you’ll be happy to know that a great deal of Java source code is available directly on
the World Wide Web.

A surprising number of Java developers have made their source code public on the Web, providing a
large repository of Java code that’s there for the taking. More often than not, the source code is provided
as a link on the applet page itself, so you can see the applet in action and download the source code then
and there if you need it. In fact, Java programming has become so popular that several sites have been
established as a resource for developers looking for code.

Table 8-1 lists a few places to visit when looking for Java source code. These Web-based Java developer
resources are broken up into three main categories:

• Code repositories
• Support areas
• Electronic magazines

file:///F|/books/java%20books/Java%20Bible/ch08/08-01.html (1 of 4)6/26/2005 7:56:25 PM


Java Bible:Surfing the Web for Java Source Code

Although most sites provide some degree of coverage in all three categories, they are strongest in the
category listed in the table.

Table 8-1
Java Developer Resource

Name Category Address Description


(URL)

Mantis Java Links Code http://www. A master page providing Java links to all sites
repository mantiscorp. mentioned in this book and up-to-date links and
com/java/ source code for each applet provided on the CD-
ROM with this book (and many that weren’t
available at press time). Includes links to source
code repositories and other Java resources on the
Web beyond those listed here.

Gamelan Code http://www. A comprehensive Java applet and source code


repository gamelan.com/ repository. It includes the ability to search for
specific files at the site.

JARS Code http://www. A code repository with a twist: a rating system!


repository jars.com/ Here you’ll find links to top-rated applets, as rated
by a large panel of judges.

Sun’s Java Site Support area http://www. This is Sun Microsystems’ official Java site. It
javasoft.com/ includes Sun’s latest Java tools, documentation,
and source code examples.

Java Language Support area news:comp.lang. The “official” Java language newsgroup. Here
Newsgroup java you’ll find answers to Java problems of all levels,
source snippets, links to Java sites, and heated
debates about the Java language.

file:///F|/books/java%20books/Java%20Bible/ch08/08-01.html (2 of 4)6/26/2005 7:56:25 PM


Java Bible:Surfing the Web for Java Source Code

Digital Espresso Support area http://www. A well-organized summary of the Java Language
mentorsoft. Newsgroup (news: comp.1ang.java). If you don’t
com/DE/ want to wade through the sometimes
overwhelming newsgroup, this is the place to visit.

Java FAQ Archives Support area http://wwwnet. Do you have a question about Java? Chances are,
com/java/faq/ you’ll find the answer in one of the many Java-
specific frequently asked questions (FAQ)
documents archived here.

IDG’s JovaWorld Electronic http://www. A Web-based magazine dedicated to to Java


magazine Javaworld. development.
com/

Table 8-2 suggests a number of search engines you might use if you can’t find the code you need on the
sites listed in Table 8-1. Although the majority of search engines are more or less the same, in that they
index pages on the World Wide Web, many have areas dedicated to Java. One of the engines, Alta Vista,
allows you to do an actual search by class name for applets embedded into Web pages (see “Alta Vista”
later in this chapter).

Between the online Java resources and the large number of search engines to choose from, you could
spend the better part of your waking hours trolling through the thousands of Java links out there.
Whatever your needs, you’re likely to find the source code you’re looking for and much, much more
along the way.

Fire up your browser and dig in!

Table 8-2
World, Wide Web Search Engines

Engine Name Web Address (URL)

SEARCH.COM http://www.search.com/

Lycos http://wwwo.lycos.com/

file:///F|/books/java%20books/Java%20Bible/ch08/08-01.html (3 of 4)6/26/2005 7:56:25 PM


Java Bible:Surfing the Web for Java Source Code

WebCrawler http://webcrawler.com/

Internet Search http://home.netscape.com/home/internet-search.html

InfoSeek http://www.infoseek.com/

Yahoo! http://www.yahoo.com/

World Wide Web Worm http://www.cs.colorado.edu/home/mcbryan/WWWW.html

Alta Vista http://www.altavista.digital.com/

DejaNews http://www.dejanews.com/

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch08/08-01.html (4 of 4)6/26/2005 7:56:25 PM


Java Bible:Surfing the Web for Java Source Code

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Java Developer Resources

With Java-powered pages spreading like wildfire—thanks to hundreds of thousands of Java developers
scattered around the world—the demand for comprehensive developer support has gone through the
roof. In response to this need, a number of sites dedicated to assisting Java developers have emerged.

Although it’s difficult to pigeonhole these sites, they can, more or less, be distinguished by the resource
(s) they provide. Three significant categories become apparent: code repositories, support areas, and
electronic magazines. These aren’t hard-and-fast categories, however, since many of the sites you can
visit feature a bit of all three!

Depending on what you’re looking for, you’ll find yourself visiting certain sites more than others. For
example, if you’re looking for source code, hit the code repositories first. If you’re looking for support
resources, such as tools, newsgroups, or FAQs, hit the support areas first. If you want instructional
resources in the form of articles and tutorials, hit the electronic magazines first. !f your first shot draws a
blank, visit the others in that category. If you still don’t find what you’re looking for, try resources listed
in another category. Eventually you’ll find what you’re looking for.

Just because you’re looking for source code, for instance, is no reason to ignore the support areas. You’ll
find that most support areas also provide some amount of source code, and vice versa. Likewise, the
source code you’re looking for may wind up being discussed in detail in an online article in one of the
electronic magazines. It’s hard to know exactly where the information you’re looking for will surface,
but starting in the category that best matches your needs is a wise move.

Depending on your needs, you may find yourself hitting sites in all three categories during your quest
for Java. If these fail to produce what you’re looking for, you can always turn to the search engines.
Personally, we tend to use search engines as a last resort, and only after making the rounds of my tried-
and-true Java sites. Since what we’re looking for is usually located at one or more of the sites listed in
Table 8-1, we usually turn to the search engines only after coming up empty-handed.

file:///F|/books/java%20books/Java%20Bible/ch08/08-02.html (1 of 4)6/26/2005 7:56:26 PM


Java Bible:Surfing the Web for Java Source Code

For fast access to these sites, add them to your browser bookmarks (also called hotlinks or
favorites). If you don’t want to bother keeping track of the links—some of these addresses may
change over time—or if you would like a current list of the best resources as they emerge,
bookmark the Mantis Java Links site (http://www.mantiscorp.com/java/). Here you’ll find all
of the links mentioned in this book, including developer resources and search engines, updated
regularly and categorized for easy access.

Code repositories

If you’re looking to get your hands on a specific piece of source code, either to plug into what you’re
doing or to learn how to do something in particular in Java, a code repository is the first place to hit.

Mantis Java Links

The code repository established for this book, Mantis Java Links, is a repository in the purest sense of
the word (see Figure 8-1). Here the applets and their source code physically reside on one Web server
and are maintained by a team of Webmasters dedicated to this site alone. The applets and source code
you’ll find here are an extension of those found on the CD-ROM that accompanied this book; you can
think of this site as a Web-based “upgrade” to the CD-ROM Not only are all the applets found on the
CD-ROM at this site, many more have been added.

Figure 8-1: You can think of the Mantis Java Links code repository as a Web-based upgrade to this
book’s CD-ROM.

As a self-contained code repository, all Mantis Java Links applets and source code reside on the Mantis
Development Corporation server. Because they’re located and managed at a single site, these links are
not dependent on external resources. This is a controlled approach to maintaining a code repository,
since you don’t have to click a hyperlink and jump to the applet author’s site to view the applet or
retrieve the source code. As a result, the authors of the applet are free to rearrange their Web pages (or
entire site!) without fear of “breaking” the Mantis Java Links site. Since external links are not provided,
applet authors don’t have to worry about maintaining the applet once it has been placed in this
repository.

Gamelan

file:///F|/books/java%20books/Java%20Bible/ch08/08-02.html (2 of 4)6/26/2005 7:56:26 PM


Java Bible:Surfing the Web for Java Source Code

Gamelan is perhaps the best known, most used, and most comprehensive code repository on the Web,
and it is a favorite among Java developers. Rather than maintaining applets and source code on its own
Web server, Gamelan provides links to external pages maintained by the applets’ authors. Although this
might not sound like a “true” repository, in the traditional sense of being a single storage area, it really
is. If you think of the Web as being a seamless network of storage devices, a repository is any site that
maintains links to resources that span the network.

And maintain links it does! Gamelan offers links to hundreds of applets and source code (see Figure 8-
2). But it doesn’t stop there; Gamelan is a place where Java developers can register themselves as
resources. Later, when someone searches for a particular piece of code using Garnelan’s private search
engine, the author’s profile is made available along with any matching applets.

Figure 8-2: Gamelan is the mother of all code repositories.

Gamelan is also a wonderful place to find anything related to Java, not just source code. You’ll find
links to applets, source code, electronic magazines, developers, newsgroups, support areas, and
everything else having to do with Java. In addition to being a wonderfully rich storehouse of Java-
related links, Gamelan has categorized its contents nicely, allowing developers to browse for code
according to functionality rather than forcing them to rely on the search engine provided.

Java Applet Rating Service (JARS)

Where Gamelan is a code repository of impressive proportions, the Java Applet Rating System (JARS)
intentionally pares clown its offering by rating the applets it references. Although JARS provides
hyperlinks to external Java-powered pages, it ranks the applets in these pages according to the average
score it receives by a large panel of judges. When you look at the “JARS Top 1%” list of applets, you
know you’re dealing with the cream of the crop (see Figure 8-3).

Figure 8-3: JARS applets are ranked by a large panel of judges using a “best of breed” approach to
categorizing the applets.

Support areas

file:///F|/books/java%20books/Java%20Bible/ch08/08-02.html (3 of 4)6/26/2005 7:56:26 PM


Java Bible:Surfing the Web for Java Source Code

Support areas, unlike code repositories, attempt to provide you with the tools and information you’ll
need as a developer. They may also provide source code, but that’s not their focus. Instead, you’re more
likely to find Java development tools, documentation, technical support, frequently asked questions
(FAQ), and other information that is extremely valuable to programmers.

The most obvious Java support area is Sun’s own Java site, JavaSoft. This is the official home of Java,
available at http://java.sun.com/. Here you’ll find all supported versions of the Java Developer’s Kit,
extensive documentation, frequently asked questions, source code samples, and links to other Java
resources.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch08/08-02.html (4 of 4)6/26/2005 7:56:26 PM


Java Bible:Surfing the Web for Java Source Code

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Another area of support is the Java newsgroups. There are now a number of Javalanguage newsgroups,
including these:

comp.lang.java.advocacy comp.lang.java.announce
comp.lang.java.api comp.lang.java.misc
comp.lang.java.programmer comp.lang.java.security
comp.lang.java.setup comp.lang.java.tech

Here you’ll not only find tons of questions and answers running the gamut of Java issues, but you’ll also
find links to source code and other Java resources (see Figure 8-4).

Figure 8-4: The Java newsgroups are chock-full of text-based conversations between Java developers;
these messages often contain source-code snippets and links to other Java resources.

They’re great places to visit if you’re having a problem and need help, or have a useful nugget of Java
code in which you think others might be interested.

Unfortunately, the Java newsgroups have become so popular recently that they’re regularly flooded with
scores of new questions every day, most of which go unanswered. As a result, you’ll spend a lot of time
wading through messages to find the piece of information for which you’re looking. In the process, you
can learn a lot about Java, but it can be frustrating if you’re pressed for time.

Worse, a lot of tripe finds its way into the discussions. Since they are not monitored (led in a general
direction), discussions that contribute little or nothing to the Java programming community often
surface, if you have the time, it can be a real hoot to follow the messages and flames that abound on
these newsgroups, and pick up some real Java gems along the way. If you don’t have much time, or
aren’t in the mood to explore, you’ll probably just find yourself knee-deep in Java drivel.

file:///F|/books/java%20books/Java%20Bible/ch08/08-03.html (1 of 3)6/26/2005 7:56:26 PM


Java Bible:Surfing the Web for Java Source Code

If you need to find the answer to a question that you think might have been posted to a Java newsgroup,
but don’t have the time or patience to filter through ali the messages, take heart: Digital Espresso comes
to the rescue. Digital Espresso is a standard Web site, not a newsgroup, that distills the best of the Java
language newsgroups into a well-organized set of pages, as shown in Figure 8-5. This is especially nice
if you don’t have a newsgroup reader or access to a newsgroup server. Fire up your ol’ Web browser and
take a sip of Digital Espresso. It’s just the thing for frazzled nerves.

Figure 8-5: Digital Espresso distills the best of the Java language newsgroups into a well-organized set
of Web pages.

In addition, many search engines allow you to search through newsgroup messages, meaning that you
can bypass the newsgroup entirely by searching for what you need through the engine, rather than
manually. If you’re interested in saving time, check out DejaNews at http://www.dejanews.com. The
DejaNews Web site is a search engine dedicated to newsgroups, and well worth a visit if you haven’t
been there before.

When it comes to the Java newsgroup, become part of the solution and not the problem: Look
high and low for the answer to your question rather than simply posting it to the group right
off the bat. There are far too many unanswered questions on the newsgroup, probably because
most of the answers to these questions have been posted time and time again! With a little
research, most of the folks posting questions could find the answer elsewhere (even by looking
farther back in the newsgroup, in the “digests” of questions answered in the past) and save the
group from being further saturated with unanswered queries.

If newsgroups aren’t your style, you can turn to any number of sites popping up on the Web to help
answer Java questions. After a trip or two to Mantis, Gamelan, and JARS, you’ll have found more Java
links than you probably dreamed were possible. But perhaps you’re a cut-and-dry, no-nonsense type of
person. You may have a bunch of questions and no time to hunt down the answers. Time is of the
essence, and you just don’t seem to have any. Clearly, you need to take a vacation. But until then, you
can visit the Java FAQ Archives.

The Java FAQ Archives could be considered a FAQ repository; it’s dedicated to documents answering
frequently asked questions. If you have a question, and it’s been asked enough times by other folks, it
will likely have made its way into a FAQ document. Since they are nothing more than text documents,
you can download FAQs to your local computer and then use them anytime you have a question. If you

file:///F|/books/java%20books/Java%20Bible/ch08/08-03.html (2 of 3)6/26/2005 7:56:26 PM


Java Bible:Surfing the Web for Java Source Code

don’t want to spend a lot of time scanning through FAQ documents, you can always use a text-search
tool (such as that of your word processor) or any “find” utility that allows you to search the contents of
files.

There are a number of FAQs out there related to Java, and there’s no better place to get to them all than
the Java FAQ Archives (see Figure 8-6). You’ll find Java-related FAQs of all stripes and colors here,
and it’s worth visiting them from time to time if you like to stay current.

Figure 8-6: The Java FAQ Archives site is dedicated to Java-related FAQ documents.

Electronic magazines

A new breed of Java resource has emerged on the Web. Electronic magazines, or e-zines, are sprouting
up at every turn. Much like traditional magazines, e-zines contain articles written to inform you about
something. In the case of Java e-zines, that “something” is...drum roll...Java!

A lot of e-zines are out there, but relatively few are dedicated to Java. This will change over time, as
more publishers migrate to the Web. I’m talking about professional publishers here, a small minority
when compared to the millions of folks out there who happen to publish information on the Web, in
between their full-time jobs and weekend outings.

With professional e-zines, you can expect consistent, well-written information to be published on a
regular basis. The others aren’t usually as reliable, well thought out, or comprehensive. However, they
are often much more creative, irreverent, exciting, and visceral. Since they’re not tied to a corporate
culture or required to conform to standards or regulations that might otherwise be imposed on a
professional publisher, independent e-zines are the free spirits of publishing.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch08/08-03.html (3 of 3)6/26/2005 7:56:26 PM


file:///F|/books/java%20books/Java%20Bible/ch08/images/08-01.jpg

file:///F|/books/java%20books/Java%20Bible/ch08/images/08-01.jpg6/26/2005 7:56:28 PM
file:///F|/books/java%20books/Java%20Bible/ch08/images/08-02.jpg

file:///F|/books/java%20books/Java%20Bible/ch08/images/08-02.jpg6/26/2005 7:56:30 PM
file:///F|/books/java%20books/Java%20Bible/ch08/images/08-03.jpg

file:///F|/books/java%20books/Java%20Bible/ch08/images/08-03.jpg6/26/2005 7:56:31 PM
Java Bible:Surfing the Web for Java Source Code

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Unfortunately, they have a much more difficult time attracting professionals to contribute articles. When
it comes to Java, this means the caliber of content in independent e-zines tends to pale in comparison to
their professional brethren, I suspect this will change in time, however, as more and more developers
become fluent in Java and are willing to contribute to independent e-zines.

Until then, you can turn to JavaWorld. This online magazine, published by IDG Books Worldwide (the
same company that published the book you’re now reading) is a wonderful piece of work. So wonderful,
in fact, that we’ve included on the CD-ROM all the back issues of JavaWorld available at the time this
book went to press.

JavaWorld (http://www.JavaWorld.com) is packed with detailed articles written expressly for Java
developers (see Figure 8-7). Here, you’ll not only read about the technology, you’ll see it working right
then and there. With a click of your mouse, you’ll see the entire source code listing, ready to copy/paste
into your own programs, or save to disk for later. It’s one of my all-time favorite Java resources, and one
you shouldn’t ignore.

Figure 8-7: JavaWorld is packed with detailed articles written expressly for Java developers.

Search Engines

When standard Java resources don’t deliver, it’s time to turn to search engines. More often than not, we
turn to these only as a last resort, since the plethora of Java resources just discussed usually turns up
whatever we’re looking for. In the rare occasion that I come up empty-handed, I call in the Mounties.

Actually, using a search engine is more like calling in the dogs; bloodhounds, to be precise. Search
engines typically employ a technology known as a spider, or agent, which scours the Web tirelessly,
looking for new pages and information day and night. (If you’re wondering why I used the analogy of
“calling in the dogs,” rather than spiders, just think about it; if you were lost in the woods, cold, hungry

file:///F|/books/java%20books/Java%20Bible/ch08/08-04.html (1 of 4)6/26/2005 7:56:31 PM


Java Bible:Surfing the Web for Java Source Code

and near death, which would you prefer the authorities send in to find you? A dog or a spider?)

Spiders return information to the search engine in the form of hyperlinks, along with some details about
the information itself. Using this data, the search engine provides an “index” (actually a gigantic
database) of the Web, which you can query. If, for example, you search for the keyword applet, the
search engine will return all the occurrences of applet in the database, along with a brief description of
each. If a particular description sounds interesting, you can click on that item to visit the actual site.

The problem with this approach is that you will receive a vast quantity of information if you don’t
qualify your search. Instead of searching for a general term such as applet, you should supply specific
details about what you are actually looking for (such as ticker tape applet, Java games, and the like). But
even in this case, you’re going to get back a large number of matches. To see whether these are really
what you want, you’ll have to visit each one. This is why we rarely use search engines; we’d rather
spend the time prowling around newsgroups and code repositories.

Luckily, the best search engines also categorize their index for you. Rather than visiting all the links
returned by a query, you can see all those that fall within a specified category. Yahoo!, for example,
features a Java category that contains only links to valid Java sites (see Figure 8-8). As a result, you
won’t be off on a wild goose chase; Yahoo! chases the geese for you.

Figure 8-8: The best search engines categorize their links to save you from wild goose chases.

Many search engines allow you to search newsgroups. If time is of the essence, and you don’t
want to waste time sifting through the messages in a newsgroup, you can use a search engine
instead. We don’t mind searching through newsgroups manually, since we usually find three
or four useful pieces of information having nothing to do with our original quest in the
process. If you’re interested in saving time, check out DejaNews at
http://www.dejanews.com. The DejaNews Web site is a search engine dedicated to
newsgroups; it’s well worth a visit if you haven’t been there before.

Alta Vista

Although the best search engines are similar in their capabilities, one alone demands special attention.
Digital Equipment Corporation’s Alta Vista search engine claims to be the fastest and most
comprehensive. But really, don’t they all?

file:///F|/books/java%20books/Java%20Bible/ch08/08-04.html (2 of 4)6/26/2005 7:56:31 PM


Java Bible:Surfing the Web for Java Source Code

The most impressive part of Alta Vista isn’t how big or fast it is. That’s not much of a help when it
comes to finding Java on the Web, since you have to sift through all the sites manually unless they’re
categorized for you. What makes Alta Vista worth mentioning is a unique feature it offers when
searching for applets.

Where other search engines simply return all matches to the word applet wherever it occurs in a
document, Alta Vista lets you search for the name of the applet class file itself. You can actually search
inside the <APPLET> tag! If you wanted, for example, to find all the pages that had an applet named
LivingLinks embedded in them, you could do just that (see Figure 8-9). Using Alta Vista, you’d simply
precede the name of the applet with applet: as follows:

applet: LivingLinks

Other search engines, in contrast, would return every page that had the word LivingLinks in it, even if
they had nothing to do with applets or Java. Rather than having to separate the wheat from the chaff
yourself, so to speak, Alta Vista does it for you. This is particularly helpful if you need to track down a
particular applet or are looking for one that has a certain functionality.

If you don’t know the name of the applet you’re looking for, you can take a pretty good guess. Since
most programmers tend to name classes based on their functionality, a few reasonable guesses would do
the trick. For example, If you wanted to find an applet that performed texture mapping on 3D wire-frame
models, you might try the following variations:

applet:texture
applet:map
applet:3-D
applet:wireframe
applet:wire
applet:model

LivingLinks is a powerful applet that brings Web pages to life with animation, special effects,
sounds, music, and multiple hyperlink capabilities. It’s highly configurable, thanks to the rich
set of PARAM settings it understands, and Java programmers can extend it by using “effect”
plug-ins. The LivingLinks applet is provided on the enclosed CD-ROM, along with the
LivingLinks Software Developer’s Toolkit (LivingLinks SDK), should you want to create your
own special effects.

file:///F|/books/java%20books/Java%20Bible/ch08/08-04.html (3 of 4)6/26/2005 7:56:31 PM


Java Bible:Surfing the Web for Java Source Code

Figure 8-9: Alta Vista allows you to search for applets embedded in Web pages; it looks inside the
<APPLET> tag.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch08/08-04.html (4 of 4)6/26/2005 7:56:31 PM


Java Bible:Surfing the Web for Java Source Code

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Although you’d have to manually visit each site Alta Vista returns to see whether the applets did what
you wanted, at least you’d know they all contain applets. With other engines, performing a search with
these keywords will return zillions of pages of information having nothing to do with Java applets.

Clearly, the example I’ve used here is fictional. A 3D texture-mapping applet is way too cool
to live in obscurity; as soon as one becomes available, every Java resource will have a link to
it. If you happen upon one before the general Java public does, drop me a note at
[email protected]. (It’ll be our little secret.)

Don’t think for moment, however, that Alta Vista will be the only ticket in town for this show. By the
time you read this, or shortly after, l’d bet most of the other search engines add the same capability.
Searching for applets by name, inside the <APPLET> tag itself, is a useful feature. It won’t be long before
they all have it.

In fact, I’ll rub my crystal ball a little harder. I’ll bet $1.50 that in less than a year, one of the search
engines out there will unveil the ability to search for applets based on what they do, not just their names.
What!? How’s that possible? Ahhh... now I’ve got your attention, eh? Check out the “Peering into the
Crystal Ball” sidebar (coming up) for a peek into the future.

Peering into the Crystal Ball

All applets have the ability to implement the getApptetInfo() and getParameter Info () methods, which
programmers use to return detailed information about the applet. When the getAppletInfo() applet is
invoked, it returns a string containing the author of the applet. Typically, applet authors return a string
containing their name, the name of the applet, and the applet version. However, authors can provide
anything they like, as long as it’s in a String object.

The getParameter Info() method, on the other hand, returns details about the parameters that the applet
understands. This method, according to Sun Microsystems, can be used as the basis of a tool designed to
set parameters graphically. Come to think of it, typing in applet parameters really is a pain. Wouldn’t it

file:///F|/books/java%20books/Java%20Bible/ch08/08-05.html (1 of 3)6/26/2005 7:56:32 PM


Java Bible:Surfing the Web for Java Source Code

be much more fun and effective to use sliders, pop-up menus, and text entry boxes? You bet– wouldn’t
it be great to see the applet respond immediately, as you change the parameter, instead of having to save
the HTML code and reload? Absolutely!

With these two methods in the back of your mind, it doesn’t take long before the idea of another one, or
better yet, an extension to getAppletInfo(), surfaces. How about a String object that is used to describe the
applet in layman’s terms? When taken all together, a search engine’s spider could easily invoke the
appropriate methods to find out the complete functionality of an applet. Not just a description, mind you,
but all the parameters with which the applet knows how to deal.

In fact, an addition to these methods really isn’t needed at all. The getParameterInfo() method already
allows the applet author to provide a description of each parameter it supports. This alone is enough! All
it takes is a spider smart enough to query the applets it encounters and to store that information in the
search engine database for you to query.

No problem. I give it a year, tops, before a search engine is announced with just such a feature. In fact,
just to be safe, I’ll e-mail this sidebar to all the ones listed here. Hey, a dollar fifty is a dollar fifty.

Also new to JDK 1.1 is the reflection APl. Reflection allows a Java class to look inside itself. The
java.1ang.Class class has been enhanced to include methods which now return the fields, methods, and
constructors defined by a class. The java.lang.reflect package defines the Field, Method, and Constructor
classes that are returned by the reflection methods. Reflection allows your applications to obtain
complete and detailed information about any class during runtime. The most prevalent use of reflection
is with JavaBeans, which is discussed in more detail in Chapter 6. For further information about class
reflection, consult the Reflection Web page on the JavaSoft Web site at http://java.sun.com/products/
jdk/1.1/docs/guide/reflection/index.html.

Do the Right Thing

When you do find a piece of source code that fits your needs, you should give the person who wrote it
some degree of credit. You might drop him or her an e-mail, as a personal thank-you for freely
supplying something you need. Of course, how you use the source code greatly influences what type of
credit you give the person who wrote it.

If you only use it to see how something is done, as a sort of detailed documentation, then a personal
“thank-you” e-mail message may be fine. But what if you actually incorporate the source code into your
own program, meaning that you’re putting someone’s personal effort into your own work?

Electronic mail and Web page footnotes

file:///F|/books/java%20books/Java%20Bible/ch08/08-05.html (2 of 3)6/26/2005 7:56:32 PM


Java Bible:Surfing the Web for Java Source Code

If you actually use somebody’s source code, why not give the person credit in your applet?

Some folks give credit by providing a note at the bottom of the page in which they’ve used the other
programmer’s source code. In this case, the note might read something like “Special thanks to J. Doe,
Benjamin Spock, and Dr. Kevorkian.” Others might go so far as to specify precisely what functionality
the other programmer contributed, and even provide a link to his or her home page though standard
HTML.

Applet-based credit

The manner in which you credit someone really depends on how much you value the person’s effort,
how critical it is to your program, and whether you can provide thanks on the Web page their work is
part of. Non-personal sites (such as your company’s home page) might be prohibited from including a
line of thanks at the bottom of a page containing such an applet. If the site is your own, or you have
authority over what the site is comprised of, you really aren’t prohibited from providing a word of
thanks directly on the Web page in which the applet appears. But with many commercial sites (and
similar ones such as government, company, and network sites), you might not be able to include credit
directly on the Web page because of organization policy. What then?

Again, it comes back to how much or how little the contribution means to you and your program. How
do you really want to say thank you? A personal “thank-you” e-mail might be just fine, but if you want
to include credit to a programmer who really helped you out, you’ll find a way, even if the site your
applet appears on is prohibited from displaying an explicit “Thanks to J. Doe” directly on its page. In
these cases, you can include thanks in the applet itself, if the program lends itself to such a thing.

Say, for instance, the applet is a Web-based video game. You might include a scrolling list of credits in
the game introduction splash screen, at the end of each game played, or somewhere in the online
documentation. In this case, you’ve included credit in a way that doesn’t alter the look of a Web page,
yet manages to extend a word of thanks to those who helped you when you were in a pinch.

For an example of scrolling text, take a look at any one of the “ticker tape” applets provided on
the CD-ROM. Although these applets are generally used to display a scrolling message on the
screen, you can use the source code in any way you see fit. In this case, simply copy the source
code that performed the scrolling text functionality and use it as a method (or perhaps even a
class) in your own program.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch08/08-05.html (3 of 3)6/26/2005 7:56:32 PM


file:///F|/books/java%20books/Java%20Bible/ch08/images/08-07.jpg

file:///F|/books/java%20books/Java%20Bible/ch08/images/08-07.jpg6/26/2005 7:56:33 PM
file:///F|/books/java%20books/Java%20Bible/ch08/images/08-08.jpg

file:///F|/books/java%20books/Java%20Bible/ch08/images/08-08.jpg6/26/2005 7:56:35 PM
file:///F|/books/java%20books/Java%20Bible/ch08/images/08-09.jpg

file:///F|/books/java%20books/Java%20Bible/ch08/images/08-09.jpg6/26/2005 7:56:36 PM
Java Bible:Surfing the Web for Java Source Code

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

In fact, this is the reason so many different applets have been provided on CD-ROM. Not only will
examining the source code show you how to get the most out of Java, you can use them as the basis for
your own programs.

If displaying credits directly in the applet itself isn’t possible, you can alternately display them on the
status bar of the browser itself. This is generally the area you’ll see messages such as “Connecting to
host... Please wait,” and a general progress report on what’s going on with the browser (such as what
percentage of the page transfer is complete, what state the applet is in, and so on).

To display text on the browser’s status bar, simply call the following method with the message you want
displayed:

showStatus(“Special thanks to Tiny Tim for all his help...”);

That’s it! This showStatus() method, defined in java.applet.Applet, shows the string you pass to it in the
status portion of the browser (see Figure 8-10). Actually, this method is described in Sun’s application
programming interface (API) documentation as one to “show a status message in the applet’s context.”
Most Java-savvy browsers respond to the method by displaying whatever string you pass to it directly on
the status area, although future browsers may handle it differently. (Browsers are free to handle this
method however they’d like, and aren’t even required to have a status area in the first place!)

To that end, another showStatus() method is defined in the java.applet.AppletContext class. Here, the API
documentation is even more terse, describing the method in four words: “Shows a status string.” This
method is usually cascaded with the getAppletContext() method (defined in java.applet.Applet), which returns
an AppletContext object:

getAppletContext().showStatus(“Howdy!”);

file:///F|/books/java%20books/Java%20Bible/ch08/08-06.html (1 of 4)6/26/2005 7:56:37 PM


Java Bible:Surfing the Web for Java Source Code

Figure 8-10: With showStatus() you can output text messages to the status area of a browser window,
which is typically located in the lower-left corner, as shown here.

The applet context allows an applet to control its environment, which is typically the browser
or the Applet Viewer.

In both cases, Netscape Navigator and Microsoft’s Internet Explorer display the string parameter you
pass to it in their status area. Although other browsers may deal with this call differently, Navigator
originally set the precedence for how showStatus () should be handled, since it was the first Java-savvy
browser to hit the ether. Many developers already rely on this method to display a message in the status
bar of the browser, and so it’s unlikely that a browser would do anything differently when showStatus () is
invoked. Although the status area may be located in different areas, depending on the browser itself, it’s
unlikely that it would ignore the call and refuse to output a message to the status area.

HTML comment tags

If the applet you’re creating doesn’t lend itself to an embedded credit, and if you’re prohibited from
including thanks in the applet’s documentation, there’s still hope: HTML comment tags. Using HTML
comment tags to give credit is about as unobtrusive and clean a way as you’ll find, outside of actually
dropping the contributor a personal e-mail. You can include anything you want in an HTML comment
tag, and it will never be seen by casual webbers unless they explicitly choose to view the HTML source
code of your page. Because Java programmers often peek at the HTML source code for pages with
embedded applets, your note of thanks won’t go unnoticed. In fact, it will be seen by that group of
people most likely to understand and appreciate it.

The following is an example of placing credit inside an HTML document. After the applet is specified
with the <APPLET> tag, a < ! > tag (comment tag) containing a word of thanks is included:

<APPLET = “CoolApplet.class” HEIGHT = 200 WIDTH = 300>>


<! This applet was written by me, with special thanks to
J. Doe for graciously providing the widget functionality.>

Give As Good As You Get

If you’ve used source code provided by others, either something from the CD-ROM included with this
book or code you found on the Web, consider going one step further and placing your own code on the
Web in return.

All you have to do is provide a hyperlink to the source code file somewhere in the page that contains
your applet; it’s that simple. For an example of how this is usually done, take a look at any of the applets

file:///F|/books/java%20books/Java%20Bible/ch08/08-06.html (2 of 4)6/26/2005 7:56:37 PM


Java Bible:Surfing the Web for Java Source Code

provided on the CD-ROM that comes with this book. Each of these pages contains a hyperlink to the
applet source code, allowing one-click access.

Once you’ve made your source code available, get the word out! Register your applet with Gamelan and
sign yourself up as a contributor on their site. Stop by the Mantis Java Links page, and take a look at the
other code repositories with which you can register your applet.

If you’ve developed an applet that you think would be of interest to fellow developers, register it with
the Mantis Java Links site or drop our Webmasters an e-mail at [email protected].

Don’t be shy! There’s a good chance your applet and source code could wind up on the CD-
ROM to be included with this book when it’s revised, as well as on our Web-based update.

By placing your code on the Web, you’re doing a great service to existing Java developers and those just
learning the language. Scores of people are looking for source samples of all levels of complexity and
you stand a good chance of helping somebody out by making yours freely available.

This is also a good idea from the perspective of the World Wide Web community in general. The Web
has become a place where businesses attempt to extract a profit in one way or another, sometimes at the
expense of good taste and ethics. It has also become tainted by some folks who have no apparent
restraint or responsibility for what they spew out into our community. In both cases, the spirit of the
Internet and World Wide Web has suffered.

By putting some of your own intellectual property out on the Web, you are taking another step towards
preserving it and the Internet as a universal conduit for give and take, fostering the notion of a truly
global village.

Summary

A great deal of Java source code is available directly on the World Wide Web. With the number of Java-
powered pages spreading like wildfire, thanks to hundreds of thousands of Java developers scattered
around the world, the demand for comprehensive developer support has gone through the roof. In
response to this need, a number of sites dedicated to assisting Java developers have emerged.

• If you’re looking to get your hands on a specific piece of source code, either to plug into what
you’re doing or to learn how to do something in particular in Java, a code repository is the first
place to hit.
• Support areas attempt to provide you with the tools and information you’ll need as a developer.
You’re likely to find Java development tools, documentation, technical support, and frequently
asked questions (FAQs).

file:///F|/books/java%20books/Java%20Bible/ch08/08-06.html (3 of 4)6/26/2005 7:56:37 PM


Java Bible:Surfing the Web for Java Source Code

• A new breed of Java resource has emerged on the Web. Much like traditional magazines, e-
zines contain articles written to inform you ali about Java.
• When standard Java resources don’t deliver, it’s time to turn to search engines. More often than
not, I turn to these only as a last resort, since the plethora of Java resources just discussed usually
turns up whatever I’m looking for.
• When you do find a piece of source code that fits your needs, you should give some degree of
credit to the person who wrote it.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch08/08-06.html (4 of 4)6/26/2005 7:56:37 PM


Java Bible:Tokens, Types, and Values

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

PART III
Programming Elements and Techniques
In This Part

Chapter 9:
Tokens, Types, and Values

Chapter 10:
Language Fundamentals

Chapter 11:
Classes, Interface, and Packages

Chapter 12:
Strings and Arroys

Chapter 13:
Input/Output: Java Streams

Chapter 14:
Threads

Chapter 15:
Weaving Applets into Web Pages

This part introduces the brass tacks of the Java programming language. Beginning with the basic
concepts of tokens, types, and values, the chapters explore all the nooks and crannies of Java. Part III
will be an ideal reference to use as you create your own applications.

These chapters show you how to do language basics such as defining and using variables, controlling

file:///F|/books/java%20books/Java%20Bible/ch09/09-01.html (1 of 4)6/26/2005 7:56:37 PM


Java Bible:Tokens, Types, and Values

program flow, creating your own classes, and handling exceptions—demonstrating that Java is more
than just a programming language. Much of the beauty of the java language is in its
packages—predesigned classes available for your use in your own applications. The chapters introduce
you to all the standard Java packages and classes, including strings, arrays, streams, and threads.

Finally, this part shows you how to weave your Java applications into Web pages—introducing you to
the HTML programming that’s required, and showing how to have your Web browser communicate
with your applications. You also learn how to package your Java applications efficiently, using Java
Archive (JAR) files for fast Web access.

CHAPTER 9
Tokens, Types, and Values
In This Chapter

Getting down to the basics of the java programming language

Attaining an overview of types and values provided by Java

Using the built-in language operators and methods

Understanding how to use objects, methods, and references to objects

Atsome or other, you’re going time to need detailed information on exactly how to use the Java
language. If you’ve made it this far, you’re probably ready for the hard stuff. At this point, you need
more than concepts, examples, and step-by-step explanations of different facets of the language. You
need the nuts and bolts of the language, detailed syntax, brass tacks.

Brass Tacks

Don’t worry, you’re not alone. Everyone learning a new programming language must, sooner or later,
learn proper syntax. Even language experts must learn the syntax for each language in their repertoire.
Depending on your personal tastes, the following chapter will be either exciting and revealing, or dry
and painful. Some folks absolutely love learning the details of new programming languages, while
others might prefer having root-canal work done instead. Either way, this chapter must be dealt with.

As you read, your eyes are guaranteed to glaze over at some point. What you’re about to experience is a
solid case of information overload; this chapter is packed with details. However, there’s no need to try
and memorize everything you read. This is an excellent chapter to skim though and come back to, time
after time, as needed. Eventually, you will absorb a large portion of it as you continue along the path to
Java enlightenment. And what you don’t remember will be waiting right here, in case you need a

file:///F|/books/java%20books/Java%20Bible/ch09/09-01.html (2 of 4)6/26/2005 7:56:37 PM


Java Bible:Tokens, Types, and Values

refresher or forget exactly how a particular syntax is supposed to be written.

This chapter was distilled from Sun’s official Java Language Specification document. For thrill seekers
and language lovers, I’d suggest taking a peek at that. You’ll find it loaded with more information than
you can imagine—it’s an essential guide to becoming a Java language expert. But for now, you can
warm up for that tome by concentrating on this chapter.

Let’s begin by examining how the lines of code you write are broken into pieces, or tokens, by the
compiler.

The Java Language Specification is available through the documentation section of JavaSoft’s
Web site: http://java.sun.com.

Tokens

Java is a tokenized language: The lines of code that you write are translated by the compiler into discrete
elements known as tokens. Working from left to right, the compiler discards all comments and
whitespace (blank spaces and similar meaningless characters). What remains is separated into one of
five possible tokens:

• Keywords
• Identifiers
• Literals
• Separators
• Operators

In order to fully understand the Java language, it’s important to have a solid grasp of each of these five
tokens. Of course, you don’t have to memorize this section in one pass, or even memorize it at all.
However, you’ll find it beneficial to understand the purpose of each type of token now. You can always
return later for details, as needed. Let’s begin by looking at keywords.

Java programs are written to the Unicode character encoding standard, which is a superset of
the ASCII character set. Unicode expands the number of bits used to represent characters to
16, whereas ASCII uses only eight. Unicode also provides characters for many non-Latin
languages, which ASCII does not.

Despite these differences, you need not concern yourself with finding a Unicode text editor! As long as
your Java programs are stored in ASCII text format, the compiler can do its job. For details on the
Unicode standard, see “The Unicode Standard: Worldwide Character Encoding” at http://unicode.org or
use FTP to connect to ftp://unicode.org.

file:///F|/books/java%20books/Java%20Bible/ch09/09-01.html (3 of 4)6/26/2005 7:56:37 PM


Java Bible:Tokens, Types, and Values

Keywords

Keywords are character sequences formed by ASCIi letters that are reserved by the Java language for
special purposes. You cannot use them for anything other than their intended purpose. For instance, you
can’t give a class, method, or variable the same name as a keyword.

Table 9-1 contains all the reserved keywords for the 1.0 release of Java, although a few aren’t actually
used by the language. The keywords gotto, byvalue, cast, const, future, generic, inner, outer, operator, rest, and
var are all reserved, even though they’re not used, They may be used in a future release of the language.

You should note that although true and false look as though they might be keywords, they are not.
Technically, true and false are boolean literals.

Since there are a large number of keywords, chances are you won’t remember most of them.
As a result, you may accidentally use a keyword without realizing you are doing so. If the
compiler doesn’t stop you, this may lead to unexpected problems with that code. If this
happens, check to see whether you’re using a keyword as an identifier. This can only happen
if the identifier in question is a sequence of all lowercase letters, however, since keywords are
never uppercase and do not contain numbers.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch09/09-01.html (4 of 4)6/26/2005 7:56:37 PM


file:///F|/books/java%20books/Java%20Bible/ch08/images/08-10.jpg

file:///F|/books/java%20books/Java%20Bible/ch08/images/08-10.jpg6/26/2005 7:56:38 PM
Java Bible:Tokens, Types, and Values

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Table 9-1
Java Keywords

abstract boolean break byte

case cast catch chars

class const continue default

do double else extends

final finally float for

future generic goto if

implements import inner instanceof

iht interface long native

new null operator outer

package private protected public

rest return short static

super switch synchronized this

file:///F|/books/java%20books/Java%20Bible/ch09/09-02.html (1 of 6)6/26/2005 7:56:39 PM


Java Bible:Tokens, Types, and Values

throw throws transient try

var void volatile while

Class modifier keywords

A subset of Java keywords, known as access specifiers, are used to control the access that objects have
to classes, methods, and variables. You can apply the Class Modifier access specifiers listed in Table 9-2
to classes and interfaces to define the extent to which other objects can access that class or interface.
(Interfaces are discussed later in this chapter, and in more detail in Chapter 11.)

Table 9-2
Class Modifier Keywords

Class Modifier Description

<blank> When no class modifier is specified, the class or interface is accessible to


objects within the current package.

public Specifies that the class or interface is accessible to objects outside the
package it is part of. Only one public class is permitted per source code file,
and that file must have the same name as the class and a .java extension (for
example, HelloWorldApplet.java).

final Specifies that the class or interface cannot be subclassed. The String class, for
example, is final. As a result, you can’t create a String subclass.

abstract Specifies that the class or interface contains abstract methods (methods
having no actual implementation), or that it isn’t directly implemented.

The following is the syntax for class modifiers. Note that items in square brackets ([]) are optional:

ClassModifier class name [extends superclass] [implements


interfaces] {
...
...

file:///F|/books/java%20books/Java%20Bible/ch09/09-02.html (2 of 6)6/26/2005 7:56:39 PM


Java Bible:Tokens, Types, and Values

For instance, suppose we don’t want our HelloWorldApplet to be subclassed. We can do this easily using
the keyword final, a modifier that prevents the class from being subclassed:

final class HelloWorldApplet extends java.applet.Applet {


...
...
}

What if we want to allow subclassing? Better yet, we might also want to allow other objects outside the
HelloworldApplet.class source code file to access this class:

public class HelloWorldApplet extends java.applet.Applet {


...
...
}

In this case, it can be subclassed. Since it’s public, HelloWorldApplet can be used by any other Java
program. If we hadn’t specified a class modifier, the class would have been available only within the
package it was part of (see Chapter 11 for information on packages):

class HelloWorldApplet extends java.applet.Applet {


...
...
}

Method modifier and field modifier keywords

Two other sets of access specifiers, Method Modifiers and Field Modifiers, also let you control the
access that objects have to methods and variables.

Method modifiers

The Method Modifier access specifiers listed in Table 9-3 can be applied to methods. Field Modifiers
are applied to class or method variables, which are also known as fields. They are the same as Method
Modifiers, with the exception of abstract, synchronized, and native (variables cannot be defined as abstract,
synchronized, or native).

file:///F|/books/java%20books/Java%20Bible/ch09/09-02.html (3 of 6)6/26/2005 7:56:39 PM


Java Bible:Tokens, Types, and Values

Table 9-3
Method Modifier Keywords

Method Modifier Description

<blank> When no access modifier is specified, the method or variable is accessible


only within the current package.

abstract Specifies that implementation for the method will be supplied by a subclass.

public Specifies that the method or variable is accessible outside its class.

private Specifies that the method or variable is only accessible to other methods
inside its own class.

protected Specifies that the method or variable is accessible to subclasses, and also to
the package in which it is defined.

private protected Specifies that the method or variable is accessible only within its class and
subclasses. A subclass can access variables it inherits, but not directly
through an instance of the superclass.

final Specifies that the method cannot be overridden, or that the value of a
variable won’t change.

Static Specifies that the method can be invoked without first instantiating an object,
and can only access static variables. Static variables are shared by all objects;
only one copy is available to all instances.

Synchronized Used with threads; specifies that the method will be locked when executed
by a thread, preventing another thread from invoking it until it is unlocked
upon exit by the first thread. (See Chapter 14.)

native Specifies that the method is actually a code stub written in another language,
such as C.

This is the syntax for method modifiers:

file:///F|/books/java%20books/Java%20Bible/ch09/09-02.html (4 of 6)6/26/2005 7:56:39 PM


Java Bible:Tokens, Types, and Values

MethodModifiers returnType name (argumentType1 argument1, ....) {


...
...
}

For instance, if we didn’t want any methods other than those defined in our HelloWorldApplet class to
have access to the paint() method, we would use the following:

private void paint (Graphics g) {


...
...
}

However, since we do want to grant methods outside the HelloWorldApplet class access to paint(), we
declare it as public:

public void paint (Graphics g) {


...
...
}

If we hadn’t specified a method modifier at all, the paint() method would have been available only to
methods within the package it was part of (see Chapter 11):

void paint (Graphics g) {


...
...
}

Field modifiers

When you apply access modifiers to variables, you should use this syntax:

FieldModifer type name;

For instance, the integer horizonta1 and vertical variables we defined in HelloWorldapplet could have been
restricted to only methods in that class:

private int horizontal, vertical;

file:///F|/books/java%20books/Java%20Bible/ch09/09-02.html (5 of 6)6/26/2005 7:56:39 PM


Java Bible:Tokens, Types, and Values

And we could have just as easily made them available to methods outside the HelloWorldApplet class:

public int horizontal, vertical;

However, we didn’t specify an access modifier for these two variables (or any other HelloWorldApplet
variables). As a result, they are available to all methods in the same package:

int horizontal, vertical;

Keep in mind that field modifiers are the same as method modifiers, with this exception:
abstract, synchronized, and native are not supported.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch09/09-02.html (6 of 6)6/26/2005 7:56:39 PM


Java Bible:Tokens, Types, and Values

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Identifiers

An identifier is a sequence of Unicode characters that you use to name a class, method, or variable.
Identifiers can be of any length, and they can contain both letters and digits. However, they must begin
with a letter, not a digit. You can use any name you can think of for an identifier, provided it doesn’t
begin with a digit and is not the same as a keyword. Because identifiers are Unicode, they can even
include non-Latin letters and digits.

As a general rule, you should use uppercase letters in your identifiers only if they help improve
readability. Identifiers that are all uppercase can make your code difficult to read, and they may reduce
the impact capital letters should have for emphasis. There is an exception to this rule, however (isn’t
there always?): Variables declared as final should be entirely in uppercase characters. Final variables
can’t be altered once declared, and are used to represent constant values (constants) in Java. For more
details on final variables, see Chapter 11.

Also, you should avoid the use of the underscore character (_), except when it appears between two
words as a way to improve readability. See Table 9-4 for examples of legal and illegal use of identifiers,
as well as those you should avoid, even though they may be legal.

Table 9-4
Examples of Legal and Illegal Identifiers

Legal Illegal Legal but Not Recommended

i if IF

dollar 1dollar _dollar

speed 5speed SPEED

file:///F|/books/java%20books/Java%20Bible/ch09/09-03.html (1 of 6)6/26/2005 7:56:40 PM


Java Bible:Tokens, Types, and Values

customerLastName customer-last-name customerlastname

leapYear leap-year leapyear

minutes_In_365_Days 365Days MinutesIn365DAYS

monthlyIncome monthly Income $monthlyIncome

Tables 9-5 and 9-6 contain the range of Unicode characters that comprise the digits and letters you can
use to form an identifier. Each table contains raw Unicode characters; they begin with \u and are
followed by four hexadecimal digits. When you use raw Unicode characters (as opposed to actual
characters, as shown in Table 9-4), Java converts them into the actual characters they represent.

Table 9-5
Unicode Digits

Point Code Range Description

\u0030-\u0039 ISO-LATIN-1 digits (0-9)

\u0660-\u0669 Arabic-Indic digits

\u06f0-\u06f9 Eastern Arabic-Indic digits

\u0966-\u096f Devanagari digits

\u09e6-\u09ef Bengali digits

\u0a66-\u0a6f Gurmukhi digits

\u0ae6-\u0aef Gujarati digits

\u0b66-\u0b6f Oriya digits

file:///F|/books/java%20books/Java%20Bible/ch09/09-03.html (2 of 6)6/26/2005 7:56:40 PM


Java Bible:Tokens, Types, and Values

\u0beT-\u0bef Tamil digit

\u0c66-\u0c6f Telugu digits

\u0ce6-\u0cef Kannada digits

\u0d66-\u0d6f Malayalam digits

\u0e50-\u0e59 Thai digits

\u0edo-\u0ed9 Lao digits

\u1040-\u1049 Tibetan digits

Table 9-6
Unicode Letters

Point Code Range Description

\u0024 $ (dollar sign—for historical reasons)

\u005f _ (underscore—or historical reasons)

\u0041-\u005a Latin capital letters (A-Z)

\u0061-\u007a Latin small letters (a-z)

\u00c0-\u00d6 Various Latin letters with diacritics

\u00d8-\u00f6 Various Latin letters with diacritics

\u00fS-\u00ff Various Latin letters with diacritics

file:///F|/books/java%20books/Java%20Bible/ch09/09-03.html (3 of 6)6/26/2005 7:56:40 PM


Java Bible:Tokens, Types, and Values

u0100-\u1fff Other non-CJK1 alphabets and symbols

\u3040-\u318f Hiragana, Katakana, Bopomofo, and Hangul

\u3300-\u337f CJK squared words

\u3400-\u3d2d Korean Hangul Symbols

\u4e00-\u9fff Han (Chinese, Japanese, Korean)

\ufg00-\ufaff Han compatibility

With the introduction of JDK 1.1, the Unicode 2.0 standard has been adopted. The Unicode
2.0 standard contains 38,885 distinct characters and covers the major written languages of
America, Europe, Middle East, Africa, India, Asia, and Pacifica. For more information on
Unicode and the Unicode standard, visit the Unicode Consortium at http://www.unicode.org

Identifiers are considered the same only if they have an identical Unicode code point for every
letter or digit. For instance, the single letters Latin capital A (\u0041), Latin small a (\u0061),
Greek capital A (\u0391), and Cyrillic small a (\u0430) each have a distinct code point and
therefore would not be considered identical.

Literals

Literals are explicit values, such as 18345 or “Helloworld!”, that are specified directly in your Java code.
Java supports three categories of literals:

• Those that are numbers (integer and floating-point literals)


• Boolean literals (true and false)
• Those that are composed of characters (character literals and string literals)

You use literals to specify values for variables, or to place explicit values directly in your source code.
For instance, in the following line of code, 135 is a numeric literal used to initialize an integer variable:

int myInteger = 135;

We can also assign a boolean literal, either true or false, to boolean variables:

file:///F|/books/java%20books/Java%20Bible/ch09/09-03.html (4 of 6)6/26/2005 7:56:40 PM


Java Bible:Tokens, Types, and Values

boolean myFlag = true;

You can also use literals to control the flow of program execution, as we’ve done here with the integer
literal 15 and the boolean literal false:

while (x < 15) {


...
}
while (myFlag != false) {
...
}

And, as you may recall from our “Hello World!” programs, you can also use literals as arguments to
methods. In our application, we used the string literal “Hello World!” to communicate with the user:

System.out.println(“HelloWorld!”);

In the applet version of Hello World, we used a string literal and two integer literals to position output at
an exact location on the screen:

g.drawString(“HelloWorld!”,50,100);

As with keywords and identifiers, you’ve been using literals all along in previous chapters. But now that
you’ve been formally introduced to them, let’s take a closer look at each type of literal in the Java
language.

Numbers

Java supports two types of numeric literals:

• Integer literals
• Floating-point literals

Integers are numbers that do not have a decimal point, while floating-point numbers do. Following are a
few integer numbers: 545, 43, 7632, 4367, 2346, and 57. And here are some floating-point numbers:
545.00456, 43.3535, .76326464, 4367.26, 2346.00, and 5.7.

Integer literals

The most common literal is the integer literal. Using ASCII characters, integer literals may be expressed
in three different ways:

file:///F|/books/java%20books/Java%20Bible/ch09/09-03.html (5 of 6)6/26/2005 7:56:40 PM


Java Bible:Tokens, Types, and Values

• Decimal (base 10)


• Hexadecimal (base 16)
• Octal (base 8)

The legal positive and negative ranges for each notation are shown in Tables 9-7, 9-8, 9-9, and 9-10 in
the next three sections.

An integer literal is considered to be of type int unless it is suffixed with an upperor lowercase
“L” (L or I). For instance, 15 is an integer literal of type int, while 15L and 15l are both integer
literals of type long.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch09/09-03.html (6 of 6)6/26/2005 7:56:40 PM


Java Bible:Tokens, Types, and Values

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Decimal literals

Decimal literals represent positive integer values, and consist of an initial digit ranging from 1 to 9,
which may be followed by one or more digits ranging from 0 to 9, such as: 935, 467L, 534643, 63036, 2,
and 2L.

The legal ranges of decimal literals are expressed in Table 9-7.

Table 9-7
Legal Ranges of Decimal Literals in Java

Literal Legal Range

Max Positive (2^31 - 1) int 2147483647

Max Negative (2^31) int n/a

Max Positive (2^63 - 1) long 9223372036854775807L

Max Negative (2^63) long n/a

Hexadecimal literals

Hexadecimal literals represent a positive, zero, or negative number. They consist of a leading 0x or 0X,
followed by one or more hexadecimal digits. The hexadecimal representation of decimal digits is shown
in Table 9-8. Hexadecimal digits 10-15 aren’t represented by digits, but are instead represented by the
letters A through F (or by a through f—these letters can be either uppercase or lowercase).

file:///F|/books/java%20books/Java%20Bible/ch09/09-04.html (1 of 5)6/26/2005 7:56:41 PM


Java Bible:Tokens, Types, and Values

Java’s Forbidden Numbers

The largest negative int (-2147483648, or -231) can’t be represented in Java as a decimal literal! Since
the literal - 2147483648 is tokenized as the unary operator “-” followed by the decimal literal value of
2147483648, the compiler generates an error (2147483648 exceeds the legal maximum value for
decimal integer literals, as shown in Table 9-7). You should represent this value in hexadecimal notation
(O×80000000).

Similarly, a compile-time error is generated if a decimal literal of type long is larger than 263-1. This
means the largest negative long can’t be represented as a decimal literal, because - 9223372036854775808L
is tokenized as the unary operator “-” followed by a decimal literal value of 9223372036854775808L
Because 9223372036854775808L is not a valid decimal long-integer literal, an error is generated. On the
off chance that you need to represent this value, use the hexadecimal literal 0×8000000000000000L
instead.

Table 9-8
Hexadecimal Digit Representation

Decimal Hexadecimal

1 0x1 or 0X1

2 0x2 or 0X2

3 0x3 or 0X3

4 0x4 or 0X4

5 0x5 or 0X5

6 0x6 or 0X6

file:///F|/books/java%20books/Java%20Bible/ch09/09-04.html (2 of 5)6/26/2005 7:56:41 PM


Java Bible:Tokens, Types, and Values

7 0x7 or 0X7

8 0x8 or 0X8

9 0x9 or 0X9

10 0xA, 0XA, 0xa, or 0Xa

11 0xB, 0XB, 0xb, or 0Xb

12 0xC, 0XC, 0xc, or 0Xc

13 0xD, 0XD, 0xd, or 0Xd

14 0xE, 0XE, 0xe, or 0Xe

15 0xE 0XE 0xf, or 0Xf

The legal ranges of hexadecimal literals are expressed in Table 9-9.

Table 9-9
Legal Ranges of Hexadecimal Literals in Java

Literal Legal Range

Max Positive (2^31 - 1) int 0x7fffffff

Max Negative 2^31) int 0x80000000

Max Positive 2^63 - 1 ) long OX7fffffffffffffffL

Max Negative (2^63 ) long 0x80000000000000000L

file:///F|/books/java%20books/Java%20Bible/ch09/09-04.html (3 of 5)6/26/2005 7:56:41 PM


Java Bible:Tokens, Types, and Values

Here are some examples of hexadecimal literals: 0xA887, 0X20C15E0, 0xFFFA9B12, 0xSAD6, 0x63036, 0X2,
and 0x2L.

Octal literals

Octal literals also represent a positive, zero, or negative number. They consist of a leading 0 (zero),
optionally followed by one or more digits in the range 0 through 7, like this: 0235, 05323434, 0000,
035674L, and 000235.

The legal ranges of octal literals are expressed in Table 9-10.

Table 9-10
Legal Ranges of Octal Literals in Java

Literal Legal Ranges

Max Positive (2^31 - 1) int 017777777777

Max Negative (2^31) int 020000000000

Max Negative (2^63 - 1) long 0777777777777777777777L

Max Negative (-2^63) long 0400000000000000000000L

Floating-point literals

Floating-point literals represent numbers with decimal values. A floating-point literal is composed of
five parts:

• A whole number
• A decimal point
• A fractional part
• An exponent
• A type suffix

Floating-point literals must have at least one digit, which may appear in either the whole number or the
fractional part of the number. They must also have either a decimal point or an exponent, although all

file:///F|/books/java%20books/Java%20Bible/ch09/09-04.html (4 of 5)6/26/2005 7:56:41 PM


Java Bible:Tokens, Types, and Values

other parts are optional.

The exponent, if one exists, is represented in scientific notation by the letter E (or e), which may be
followed by a signed integer.

A floating-point literal is considered to be of type double unless it is suffixed with an F or f, in


which case it’s of type float. For instance, 15.35 (as well as 15.35 D and 15.35d) is a floating-
point literal of type double, while 15.35F and 15.35f are both floating-point literals of type float.

The float type is used to represent single precision floating-point numbers, whereas the double
type represents numbers as double precision values. If your calculations need to be
exceptionally accurate, be sure to specify floating-point numbers as type double. Examples of
floating-point literals of type double include these: 3el, 5.34, 5.34d, 2., .366, and 3e-6. Floating-
point literals of type float include these others: 3elf, 5.34F, 5.34f, 2. f, .366F, and 3.03e+6f.

Boolean literals

In Java, boolean literals are of type boolean, and can have one of two possible values: true or false. Java’s
boolean literals are actual literals, not strings, and can’t be converted into string literals (see “String
literals” later in this chapter). Nor are they integer values of zero and one, as booleans in C and C++ are.

Character literals

An addition to the numeric and boolean literals described in the preceding sections, Java supports literals
that are composed of characters. These can be:

• An individual character (character literal)


• A number of characters in a string (string literals)

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch09/09-04.html (5 of 5)6/26/2005 7:56:41 PM


Java Bible:Tokens, Types, and Values

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Character literals are expressed as a single character, or an escape sequence beginning with the
backslash character enclosed in single quotes (‘ \ ’). The escape sequence permits non-graphic characters
to be represented, in addition to the single quote (’) character and the backslash (\) character themselves.

Character literals are 16-bit integer values. Following are a few examples of valid character literals: a, A,
z, Z, ‘ \t ’, ‘ \b’, ‘ \ul2d ’, ‘ \\ ’.

Table 9-11 shows the character literal escape codes for each escape sequence, as well as what they
represent.

Table 9-11
Character Literal Escape Codes

Escape Sequence Unicode Escape Code What It Represents

\b \u0008 backspace (BS)

\t \u0009 horizontal tab (HT)

\n \u000a linefeed (LF)

\f \u000c form feed (FF)

\r \u000d carriage return (CR)

\“ \u0022 double quote (“)

\’ \u0027 single quote (’)

file:///F|/books/java%20books/Java%20Bible/ch09/09-05.html (1 of 5)6/26/2005 7:56:41 PM


Java Bible:Tokens, Types, and Values

\\ \u005c backslash (\)

\? \u0034 question mark (?)

Unicode escapes are processed very early on in the compilation of Java code. For instance, if
you were to use a character literal escape sequence of \u000a (for linefeed), Java would see
the u000a Unicode escape and translate it into an actual linefeed on the spot. even before
realizing that it is part of a character literal escape sequence! This linefeed is then further
reduced to a line terminator, blowing your character literal out of the water. The same thing
happens when u000d is encountered As a result, you should use ‘ \n ’ for a character literal
linefeed and ‘ \r ’ for a carriage return.

String literals

String literals are comprised of zero (0) or more characters enclosed in double quotes (“ ”), and may use
the same escape sequences as character literals. Table 9-12 shows examples of valid string literals.

Table 9-12
Examples of Valid String Literals

Literal String Type

“Hello World!” basic string

“Are you looking at me?” your basic string, with an attitude

“” an empty string

“\”“ a sting containing only a double quote (“)

“This string is ” + three strings treated as

“too long to fit ”“ + an expression using the

“on one line!” +operator

file:///F|/books/java%20books/Java%20Bible/ch09/09-05.html (2 of 5)6/26/2005 7:56:41 PM


Java Bible:Tokens, Types, and Values

If your string literal contains a line separator (such as a carriage return or linefeed) between
the opening and closing double quotes (“ ”), the compiler generates an error. If necessary, you
can use the string concatenation operator, +, to break your string into smaller pieces, as shown
in Table 9-12.

Separators

Separators are characters used to group and arrange Java source code. They let you organize your code
into a form the compiler understands. The following characters are valid Java separators:

( ) { } [ ] ; , .

You’ve already seen all of these used in some way or other. For instance, the while loop used in Chapter
7 makes use of the ( ) and { } separators:

while (x <15) {
...
}

Perhaps you’ve used a for loop? If so, you’ve also used the; separator:

for (x=0; x<l00; x++) {


...
}

You’ve even used the; and. separators in one line of code, along with the () separators:

System. out. println(“HelloWorld!”);

And how about the comma (,) separator? We use that, and the () and; separators in every method that has
more than one argument:

g.drawImage(myImage, horizontal, vertical, this);

Finally, we’ve dealt with arrays. As a result, we’ve already used the [] separators:

theArg = args[i];

Operators

file:///F|/books/java%20books/Java%20Bible/ch09/09-05.html (3 of 5)6/26/2005 7:56:41 PM


Java Bible:Tokens, Types, and Values

Operators are individual characters and combinations of characters used to perform calculations. Table 9-
13 lists ali of the Java operators, current as of JDK 1.2. Chapter 10 provides a detailed overview of these
operators, including precedence and associativity.

Tables 9-13
Java Operators

= > < ! ~ ? : ==

<= >= != && || ++ - +

- F / & | ^ % <<

> >> += -= *= /= &= |=

^= %= <<= >= >>=

Types and Values

In this section, we shall look at two more important elements of Java syntax, types and values.

Types

Types are used to identify the information stored in variables and returned by methods (on those
occasions when a method does in fact return data when called). The information stored in a variable or
returned by a method is known as the value of the variable or return. In essence, you create variables that
have a certain type. The type, in turn, determines what values can be stored in the variable. The same is
true for method return types: You define what information will be returned by specifying a return type.
As a result, only values conforming to the type can be returned.

Because Java is a strongly typed language, you’re prevented from making common programming
mistakes seen with loosely typed languages. Passing incorrect data types as parameters to a method,
treating return values in a manner inconsistent with their type, and unwittingly casting data values from
one type to another are all prevented thanks to Java’s strong adherence to data typing.

Java supports four distinct categories of data types:

file:///F|/books/java%20books/Java%20Bible/ch09/09-05.html (4 of 5)6/26/2005 7:56:41 PM


Java Bible:Tokens, Types, and Values

• Primitive types
• Class types
• Interface types
• Array types

Every variable in a Java program has an associated data type, often called its compile-time type because
the compiler can always determine the type before the program is executed.

Values

Java also supports two kinds of data values:

• Primitive values
• References

These values can be stored in variables, passed to methods as arguments, returned as values, and
operated upon. In this section, we’ll take a look at the types and values that are supported by the Java
language.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch09/09-05.html (5 of 5)6/26/2005 7:56:41 PM


Java Bible:Tokens, Types, and Values

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Primitive values

Primitive values are indivisible, meaning they can’t be reduced any further. They don’t share state with
other primitive values. A variable defined as having a primitive compile-time type always holds a value
of that exact primitive type. Such a value is not shared in any way with any other variable, so the value
of the variable can be changed only by operations using that variable.

Values stored in a variable must be compatible with the compile-time type of that variable.
That is, you can’t define a variable of type int and then attempt to store a string in it.

References

References are pointers to dynamically allocated objects (here we mean the concept of pointing to
something in memory, not actual pointers of the kind found in C/C++; Java doesn’t support such
pointers). These objects are composed of primitive values, and are sometimes called composite data
types for that reason.

The rest of this chapter is dedicated to Java’s data types and values. To help organize this material, we’ll
explore these in the context of primitive types and references. Let’s begin with primitives.

Primitive types and values

Primitive types, also known as simple or basic types, are the fundamental data types of Java. They are
defined the same way in all implementations of the language, regardless of platform, making them more
portable than primitive data types of other languages, such as C and C++. When you use primitive data
types in Java, their representation and arithmetic behavior are consistent from system to system.

Primitives are named by one of the reserved keywords listed in Table 9-14, and fall into one of three
categories:

file:///F|/books/java%20books/Java%20Bible/ch09/09-06.html (1 of 5)6/26/2005 7:56:42 PM


Java Bible:Tokens, Types, and Values

• gxithmetic (integral or floating-point)


• Boolean
• Character

Table 9-14
Primitive Data Types

Type Category Values

byte intergral arithmetic 8-bit signed two’s complement intergers

short integral arithmetic 16-bit signed two’s complement integers

int intergral arithmetic 32-bit signed two’s complement integres

long integral arithmetic 64-bit signed two’s complement integers

float floating-point 32bit IEEE 754 floating-point numbers


arithmentic

double floating-point arithmetic 64-bit IEEE 754 floating-point numbers

char character 16-bit Unicode characters

boolean boolean true and false

The values that a primitive variable can contain depend upon the data type of that variable. It’s
interesting to note, however, that you can’t treat primitive types as objects. Instead, you have to place
them in what’s known as an object wrapper before passing them as arguments to most methods, in
addition to allowing you to embed primitive types in objects, type wrapper classes (discussed in detail in
Chapter 12) also contain MIN_VALUE and MAX_VALUE class variables for easy access to the upper and
lower range of values permitted for each type.

Integral arithmetic type and values

The primitive integral data types—byte, short, int, and long—are used to perform integer arithmetic. These

file:///F|/books/java%20books/Java%20Bible/ch09/09-06.html (2 of 5)6/26/2005 7:56:42 PM


Java Bible:Tokens, Types, and Values

types do not support numbers with decimals. The char data type is compatible with integral types
because it supports 16-bit unsigned integer values, which are used to represent a Unicode code point.

Ranges and casts

Table 9-15 shows the legal range for each integral type. Although the char type is not represented in this
table, any integral value may be cast to a type char, while any character may be cast to any of the integral
types. And, not surprisingly, any integral value may be cast to any other arithmetic type.

Table 9-15
Legal Value Ranges for Integral Types

Type Legal Range

byte -128 to 127,inclusive

short -32768 to 32767, inclusive

int -2147483648 to 2147483647, inclusive

long -9223372036854775808 to 9223372036854775807, inclusinve

Although integral types can be cast to a char type and vice versa, the same cannot be said for
boolean types. It is illegal to attempt a cast between integrals and booleans.

Operands

Table 9-16 includes the various operators that Java provides for performing integral operations.

Table 9-16
Java Operators for Integral Operations

Type Operators

file:///F|/books/java%20books/Java%20Bible/ch09/09-06.html (3 of 5)6/26/2005 7:56:42 PM


Java Bible:Tokens, Types, and Values

equality operators = and !=

relational operators <, <=, >, and >=

unary operators + and -

additive and multiplicative operators +, -, *, /, and %

prefix and postfix increment/decrement operators ++ and - -

signed and unsigned shift operators <<, &lg>, and >>>

unary bitwise logical negation operator ~

bitwise logical operators &, |, and ^

Widening

If an operation is performed on integrals, it is considered an integer operation, provided that both


operands are of the integral type. However, if one of the operands is of type long, the operation is
performed using 64-bit precision. In this case, all operands that are not also of type long are first widened
(as if a cast was performed) to type long, and the result is of type long as well (assuming the operation
wasn’t meant to return a boolean, in which case a boolean type is returned).

If none of the operands are of type long, the operation is performed using 32-bit precision. In this case,
ali operands that are not of type int are first widened to type int and the result is also of type int (once
again, assuming the operation wasn’t meant to return a boolean, in which case the boolean type is
returned).

Although the built-in integral operators widen their operands to perform 32-bit or 64-bit
precision operations, values of integral type are not automatically widened when used as
arguments in method calls. You can write individual methods to do so, but the calling process
does not automatically perform widening.

Exceptions

If the right-hand operand to an integer divide operator (/) or integer remainder operator (%) is zero, Java

file:///F|/books/java%20books/Java%20Bible/ch09/09-06.html (4 of 5)6/26/2005 7:56:42 PM


Java Bible:Tokens, Types, and Values

throws an ArtihmeticException. Some programmers may recognize this as the ol’ “divide by zero” error,
which everyone encounters at some time or another. However, this is the only way for an exception to
be generated by an operator on integral types.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch09/09-06.html (5 of 5)6/26/2005 7:56:42 PM


Java Bible:Tokens, Types, and Values

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Floating-point arithmetic types and values

The primitive floating-point data types—float and double—are used to perform single precision 32-bit
and double precision 64-bit format operations, respectively, on values that conform to the Institute of
Electrical and Electronics Engineers’ IEEE 754 standard. Unlike integrals, floating-point data types
support numbers with decimals. Their values can be positive, zero, or negative.

For detailed information on the IEEE 754 specification, refer to the publication “IEEE
Standard for Binary Floating-point Arithmetic,” ANSI/IEEE Std. 754-1985 (IEEE, New
York).

Ranges and casts

Table 9-17 shows the legal range for float and double data types. As with integrals, any floating-point
value may be cast to a type char, while any character may be cast to any floating-point type. In addition,
any floating-point value may be cast to any other arithmetic type.

Table 9-17
Legal Value Ranges for Floating-Point Types

Type Legal Range (Arranged from Smallest to Largest)

float negative infinity, negative finite values, negative zero, positive zero, positive finite
values, and positive infinity

double negative infinity, negative finite values, negative zero, positive zero, positive finite
values, and positive infinity

file:///F|/books/java%20books/Java%20Bible/ch09/09-07.html (1 of 4)6/26/2005 7:56:42 PM


Java Bible:Tokens, Types, and Values

And, just as with integrals, it is illegal to attempt a cast between floating-point types and the
boolean type. Booleans can only hold true or false values, and can’t be cast into other data types.

Finite non-zero values

Finite non-zero values of type float are of the following form:

s(m × 2e)

where s is +1 or -1, m is a positive integer less than 224, and e is an integer between -149 and 104,
inclusive.)

Don’t be confused by the ^ appearing in this section (as in 224). In this case, it’s used to
indicated a value “raised to the power of” another value. This isn’t Java code, mind you, but
simply a mathematical notation appearing in regular text.

In contrast, Java’s ^ operator has two different meanings, depending on the operands involved. When
used with integral operands, a bitwise exclusive OR (XOR) operation is performed. With boolean
operands, however, a logical exclusive OR (XOR) operation is performed, where the result is either true
or false.

Finite non-zero values of type double are also of the form:

s(m. 2e )

where s is +1 or -1, m is a positive integer less than 253, and e is an integer between –1045 and 1000,
inclusive.

NaN: Not-a-Number

Floating-point data types support a special value known as Not-a-Number (NAN). NaN is used to
represent the result of operations where an actual number isn’t produced. Most operations that have NaN
as an operand will produce NaN as a result.

The presence of NaN can produce unexpected results when dealing with floatingpoint data
types. Since NaN is unordered, the result of a <, <=, >, >=, or == comparison between a NaN
and another value is always false. In fact, == always produces false when both operands are
NaN. However, the result of a != comparison with a NaN is always true, even if both operands
are NaN.

file:///F|/books/java%20books/Java%20Bible/ch09/09-07.html (2 of 4)6/26/2005 7:56:42 PM


Java Bible:Tokens, Types, and Values

Operands

Table 9-18 lists the various operators that Java provides for performing floatingpoint operations.

Table 9-18
Java Operation for Floating-Point operations

Operation Operators

basic equality operations = and !=

relational operations <, <=, >, and >=

unary operations + and -

additive and multiplicative operations +, -, *, /, and %

prefix and postfix increment/decrement operations ++ and -

Operations

If an operation is performed on floating-point data types, it’s considered a floatingpoint operation if both
operands are of the floating-point type. An operation is also considered a floating-point operation if one
of the operands is a floating-point type and one is an integral data type.

If one of the operands is of type double, the operation is performed using 64-bit floating-point arithmetic.
In this case, any operand that is not also a double is first cast to type double and the result is of type double
(assuming the operation wasn’t meant to return a boolean, in which case a boolean type is returned). If
none of the operands are of type double, the operation is performed using 32-bit floating-point arithmetic.
If this is the case, all operands that are not float are first cast to type float and the result, if not boolean, is
of type float.

All operations on floating-point numbers behave exactly as specified by the IEEE 754
standard.

file:///F|/books/java%20books/Java%20Bible/ch09/09-07.html (3 of 4)6/26/2005 7:56:42 PM


Java Bible:Tokens, Types, and Values

Rounding

In Java, floating-point arithmetic is performed as if every floating-point operator rounds its floating-
point result to the result precision. Inexact results are rounded to the nearest representable value, in
accordance with the IEEE 754 “round to nearest” mode. For instance, if two representable values are
equally distant from the true mathematical result of the operation, Java returns the value whose
leastsignificant bit is zero (0).

Similarly, Java rounds towards zero when floating-point values are cast to integers.

Exceptions

In Java, floating-point arithmetic will not generate an exception. Any operation that overflows will
produce a signed infinity value, so there’s no need to throw an overflow exception (see Chapter 10 for
details on exceptions). Likewise, when an operation underflows, a signed zero is produced. If an
operation produces a result that has no mathematically definite value, NaN is produced. Since these are
all valid results, no exceptions are generated.

Character types and values

In Java, the char type is used to store a Unicode character value. While Unicode values are two bytes in
size, you don’t have to do anything special when assigning values to Java char types. Their internal
representation is not of concern to you, and, in fact, you can’t even tell what size a char type is (Java
doesn’t support the sizeof operation popular with C/C++).

Java char types are unsigned. As such, if a char is cast to another type (such as a byte or short) the result
may be a negative value.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch09/09-07.html (4 of 4)6/26/2005 7:56:42 PM


Java Bible:Tokens, Types, and Values

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Boolean types and values

Java’s boolean data type represents a 1-bit logical quantity with only two possible values: true and false.

Casts

No casts are defined for booleans, although an integer can be converted to a boolean following the
convention of the C programming language. Suppose we have an integer, x. Since C treats 0 as false and
every non-zero value as true, we can use the expression x!=0 to convert x into a boolean.

Likewise, a boolean value b is converted to a zero/one integer value using the expression b?1:0.
However, there are no explicit casts on booleans. You cannot, for instance, convert a boolean type to a
floating-point data type or String object.

Operands

Operations defined on booleans appear in Table 9-19.

Table 9-19
Java Operators for Boolean Operations

Operation Operators

relational operations == and !=

logical operations !, &, |, and ^

short-circuit logical operations && and ||

file:///F|/books/java%20books/Java%20Bible/ch09/09-08.html (1 of 4)6/26/2005 7:56:44 PM


Java Bible:Tokens, Types, and Values

The if, while, do, and for statement, all rely on boolean truth values to control the flow of
program execution. Likewise, the conditional ?: operator uses boolean truth values to
determine which subexpression is selected.

Reference types and values

In Java, there are two kinds of dynamically allocated objects:

• Class instances
• Arrays

These non-primitive types are commonly known as reference types, since they are dealt with using the
address of the object or array rather than the actual value of the object or array itself. The address, or
reference, of an object or array is what’s stored in variables and passed as an argument to methods. In
contrast, primitive types are handled by value: Actual values are stored in variables and passed as
arguments to methods. This makes for two very distinct types in Java:

• Primitive
• Reference

Since arrays are covered in detail in Chapter 12, this section focuses more on the nature of
objects. While arrays are treated a lot like objects, they are unique beasts. As such, special
attention is given to them later in this book. Feel free to skip ahead for details on arrays if
you’d like, or read on to learn more about objects.

Creating objects

Objects are created, or instantiated, from class definitions using the new keyword:

new ClassName(); // instantiates an object from class

When a constructor is used in the instantiation of an object, parameters are often required:

new ClassName(param1.param2.param3.... );

Typically, the objects you create are assigned to a variable. To do this, you must declare the variable as
being of the same data type as the class itself (or of a data type compatible with the class):

ClassName myObject = new ClassName(); // set variable equal to


new object

file:///F|/books/java%20books/Java%20Bible/ch09/09-08.html (2 of 4)6/26/2005 7:56:44 PM


Java Bible:Tokens, Types, and Values

Accessing methods

Methods in an object are invoked by sending that object a message using dot notation. The message you
send is actually the name (and parameter list, if parameters are required) for the method to invoke:

myObject.methodName(); // invoke method requiring no parameters


myObject.methodName(paraml.param2.param3....* ); // parameters
are required

Variables in an object may (or may not, depending on implementation) be available using dot notation.
Typically, variables are accessible only though special accessor methods:

myObject,variableName; // direct access


myObject.getVariableMethod(); // access via method

Class variables may be directly accessed without having to first instantiate an object, if they are declared
as static, by providing the name of the class in dot notation:

ClassName.classVariable; // class variable access without


instantiation

Likewise, static class methods may be accessed without first requiring object instantiation:

className.classMethod(); // class method access without


instantiation

For information about static variables and methods, see Chapters 5 and 11.

Object references

Whenever you assign an object to a variable or pass an object as a parameter to a method or class, it is
done by reference. That is, instead of the object itself, the address of the object is used. As a result,
dealing with objects is very different from dealing with primitive types.

Variables of interface types can contain references to objects that implement that interface.
For details on interfaces, see Chapter 11.

Copying objects

file:///F|/books/java%20books/Java%20Bible/ch09/09-08.html (3 of 4)6/26/2005 7:56:44 PM


Java Bible:Tokens, Types, and Values

Perhaps the most obvious difference between objects and primitives is seen with the = assignment
operator. With primitive types, this operator is used to store a value in a variable. With objects, however,
it stores the reference instead of the value.

For example, consider the following:

objectVariable1 = objectVariable2;

In this example, we don’t copy objectVariable2 into objectVariable1. Instead, objectVariable1 now merely
references (or points to) objectVariable2. Whenever objectVariable2 is altered, ObjectVariable1 sees the result.
This is very different from actually copying an object’s value, because both variables point to the same
instance instead of each maintaining a separate copy.

To copy the value of an object into another, you can use either the copy() or clone() method:

objectVariablel.copy(objectVariable2); // copy objectVariable2


into objectVariablel
objectVariablel = objectVariable2.clone(): // clone object

When using copy(), both objects are instances of the same class. The value of ali instance variables of the
object you pass as an argument to copy() are copied into the instance variables of the object on the left
side of the dot notation. If an instance variable contains the reference to an object, only the reference is
copied, not the object itself.

With clone(), a new instance is created and the value of all instance variables of the current object are
copied into the new one. Just as with copy(), if an instance variable contains the reference to an object,
only the reference is copied (not the object itself). If the two objects aren’t of the same type, you must
perform a cast:

objectVariablel = (objectVariablel) objectVariable2.clone();

Not all objects support copy() and clone(). When they are supported, you may need to cast
objects from one type to another in order to carry out the method. Casting objects is possible
as long as the object you’re casting is related (by inheritance) to the object it’s being cast to.
This means you can only cast an object to an instance of its superclass or subclass. To perform
the cast, enclose the name of the class you are casting the object to in parentheses:

(ClassName) theObject:

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch09/09-08.html (4 of 4)6/26/2005 7:56:44 PM


Java Bible:Tokens, Types, and Values

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

When a cast is performed, a new instance of the specified class is created, which has the contents of the
object. The original object isn’t altered, and can be used exactly as it was before the cast was performed.

In addition to explicit casts, variables can contain references to objects whose runtime type can be
converted to the variable’s compile-time type through assignment conversion.

Testing for equality

Dealing with objects by reference rather than by value also affects the way in which the objects are
tested for equality. With primitive types, the == operator is used for this. With objects, however, this
operator only tests the references to objects for equality. As a result, the following does not tell you if
the two objects are equal:

objectVariablel == objectVariable2; // test references for


equality

While this will tell you if two variables refer to the same thing, it doesn’t compare the contents of what
each points to. In order to find out if the objects themselves are equal, you must use the equals() method:

objectVariablel.equals(objectVariable2); // test value of


objects for equality

Null references

The null reference is used to specify an object that has no instance. We can set objects to null, and test
them to see if they are null or an actual instance:

anyObject = null; // set an object to null


if (anyObject = = null) { // test for null
...
}

file:///F|/books/java%20books/Java%20Bible/ch09/09-09.html (1 of 3)6/26/2005 7:56:44 PM


Java Bible:Tokens, Types, and Values

Determining an object’s class

Every object that isn’t an array is an instance of a class. An object’s class is often called its runtime type.
You can find out what class an object was created from by cascading the getClass() and getName()
methods, as follows:

anyObject.getClass().getName();
// retrieve the class name (returns a string)

Since cascading these two methods returns a String object, you’ll often assign the object to a string
variable for future use:

String theClassName = anyObject.getClass().getName();

The getClass() method is defined in the Object class (java.lang.Object), from which all classes are derived.
Since every Java class is ultimately a descendant of the Object class, the variables and methods defined in
this class are available to every object (see Table 9-20). As a result, we can send any object the getClass()
message in order to invoke that method and retrieve the class it was instantiated from.

Table 9-20
Class java.lang.Object

Method Signature Description

object public object () creates a new object.

clone protected Object clone() throws Creates a clone of the object.


CloneNot SupportedException

equals public boolean equals (object obj) Compares two objects for equality, returning
true if they are equal false if not

finalize protected void finalize() throws Code to execute when this object is garbage-
Throwable collected.

getClass public final Class getClass() Returns the class of this object.

hashCode public int hashCode() Returns the hash code for this object.

file:///F|/books/java%20books/Java%20Bible/ch09/09-09.html (2 of 3)6/26/2005 7:56:44 PM


Java Bible:Tokens, Types, and Values

notify public final void notify() Notifies a single waiting thread that another
thread’s conditions has changed (can only be
called from within a synchronized method or
block of code).

notifyAll public final void notifyAll() Notifies all waiting threads that a condition
has changed (can only be called from within
a synchronized method or block of code).

toString public String to String() Returns a string representing the value of


this object. Subclasses should override this
method

wait public final void wait(long timeout) Causes a thread to wait for a notification, or
throws InterruptedException until the specified timeout value expires (can
only be called from within a synchronized
method or block of code).

wait public final void wait(long timeout, int A more precise wait method (can only be
nanos) throws InterruptedException called from within a synchronized method or
block of code).

wait public final void wait() throws Causes a thread to wait indefinitely until
InterruptedException notified (can only be called from within a
synchronized method or block of code).

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch09/09-09.html (3 of 3)6/26/2005 7:56:44 PM


Java Bible:Tokens, Types, and Values

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

The getName() method is defined in the Class class (java.lang.Class), which contains the runtime
representations of classes. Since every Java object is an instance of some class, the methods in Table 9-
21 can be invoked when combined with the getClass() method, as we’ve done.

Table 9-21
Class java.lang.Class

Method Signature Description

forName public static Class fornName Returns runtime class descriptor for this
(StringclassName) throws class.
ClassNotFoundException

getClassLoader public ClassLoader getClassLoader() Returns the class loader of this class.
Returns null if a class loader isn’t used by
the class.

getInterfaces public Class[] getInterfaces() Returns the interfaces implemented by


this class (an array of length zero [0] is
returned if no interfaces are
implemented).

getName public String getName() getSuperclass() Returns the name of this class.

getSuperclass public Class Returns the superclass of this class.

isInterface public boolean, isInterface() Returns true or false, indicating whether


the class is an interface or not.

file:///F|/books/java%20books/Java%20Bible/ch09/09-10.html (1 of 4)6/26/2005 7:56:45 PM


Java Bible:Tokens, Types, and Values

newInstance public object newInstance() throws Creates a new instance of this class.
InstantiationException,
IllegalAccessException

toString public String toString() Returns the name of this class or


interface, with the word class prepended
to classes and the word interface
prepended to interfaces.

At times, you’ll want to know what class an object was created from. To do this, you can use the
instanceof operator, by providing the object to the left of the operator and the class name to the right:

anyObject instanceof ClassName

The boolean value of true is returned if the object is an instance of the specified class, otherwise false is
returned.

if (theObject instanceof ClassName) { // returns true if of


same class
}

Standard default values

In Java programs, every variable has a default value. If you don’t initialize a variable when it’s first
created, the default for that variable type is automatically provided in accordance with Table 9-22.

Although Java automatically initializes variables to their standard default values, it’s poor
programming style to rely on this process. These automatic default values are required to
guarantee portability of Java code, at considerable expense to the compiler. The compiler
must locate all variables that are used by your program before a value is provided for them.
Do the compiler a favor, and supply a value (either through initialization or later in the
program) for each variable before it is used.

Table 9-22
Default Values for Types

Type Default

byte zero: (byte)0

file:///F|/books/java%20books/Java%20Bible/ch09/09-10.html (2 of 4)6/26/2005 7:56:45 PM


Java Bible:Tokens, Types, and Values

short zero: (short)0

int zero: 0

long zero: 0L

float positive Zero: 0.0f

double positive zero: 0.0d

char null character: ’\u0000’

boolean false

reference null

Summary

This chapter reviewed the core of the Java language. Each of the elements described are essential to
understand before you begin to develop your own Java applications. Before you continue make sure that
you understand these key concepts presented in this chapter:

• Java is a tokenized language: The lines of code that you write are translated by the compiler
into discrete elements known as tokens. Working from left to right, the compiler discards all
comments and whitespace. What remains is separated into one of five possible tokens: keywords,
identifiers, literals, separators, operators.
• Keywords are character sequences formed by ASCII letters that are reserved by the Java
language for special purposes. You cannot use them for anything other than their intended
purpose.
• An identifier is a sequence of Unicode characters that you use to name a class, method, or
variable. Identifiers can be of any length, and they can contain both letters and digits. However,
they must begin with a letter, not a digit. You can use any name you can think of for an identifier,
provided it doesn’t begin with a digit and is not the same as a keyword. Because identifiers are
Unicode, they can even include non-Latin letters and digits.
• Literals are explicit values, such as 18345 or “Hello World!”, that are specified directly in your
Java code. Java supports three categories of literals: Those that are numbers (integer and floating-
point literals), boolean literals (true and false), and those that are composed of characters

file:///F|/books/java%20books/Java%20Bible/ch09/09-10.html (3 of 4)6/26/2005 7:56:45 PM


Java Bible:Tokens, Types, and Values

(character literals and string literals).


• Types are used to identify the information stored in variables and returned by methods (on
those occasions when a method does in fact return data when called). The information stored in a
variable or returned by a method is known as the value of the variable or return, in essence, you
create variables that have a certain type.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch09/09-10.html (4 of 4)6/26/2005 7:56:45 PM


Java Bible:Language Fundamentals

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

CHAPTER 10
Language Fundamentals
In This Chapter

Declaring, initializing and using variables in your Java applications

Using expressions to perform calculations and store values in variables

Controlling the flow of your Java applications with control-flow statements

Understanding and handling exceptions in your java applications

In This chapter, we’ll continue to explore the fundamental elements of the Java language. We’ll begin
with a look at variables and see how to declare, initialize, and use them in our programs.

From there, we’ll proceed to expressions, and learn how these statements are used to perform
calculations and store values in variables. Since expressions make use of operators, we’ll explore in
more detail the Java operators introduced in the previous chapter.

Next, we’ll see how the control of program execution is directed with Java’s control-flow statements.
We’ll discuss branching statements and loops, and see how they are used to control the way in which our
programs are executed.

Finally, we’ll cover Java’s general-purpose error processing mechanism, using what are known as
exceptions. By learning to use them, we can create robust and reliable Java programs.

Variables

Variables are used to store values in Java, something we’ve been doing all along without much ado.
Once a value is stored in a variable, we can use it for any number of purposes.

file:///F|/books/java%20books/Java%20Bible/ch10/10-01.html (1 of 5)6/26/2005 7:56:45 PM


Java Bible:Language Fundamentals

One such purpose is to represent an object’s state, as discussed in Chapter 2. Since the value stored in a
variable can be altered, the state of an object can also be altered by changing the value of its variables.

Variables are also used to perform calculations, control the flow of program execution, and effect the
overall state of a program. They are a fundamental part of programming languages; without them we’d
be hard pressed to develop software.

Declaring variables

To use a variable, you first have to declare it. A variable declaration consists of two parts:

• A data type: This determines the legal range of values a variable may contain, what operations
may be applied to the variable, and how such operations are performed.
• An identifier: An identifier is used to associate a name with a variable:

type identifier [, identifier];

Any number of variables can be declared on a single line, each of the same type, as long as each
identifier’s name is unique and separated from the others by a comma. A semicolon is used to signal the
end of a variable declaration.

Here, we declare an integer variable and give it the name horizontal:

int horizontal;

And here we declare several integer variables, all on the same line:

int horizontal, vertical, x, y, z, months, years, days,


ageInDays;

However, we could have broken the above declaration into a number of declarations:

int horizontal;
int vertical;
int x;
int y;
int z;
int months;
int years;
int days;
int ageInDays;

file:///F|/books/java%20books/Java%20Bible/ch10/10-01.html (2 of 5)6/26/2005 7:56:45 PM


Java Bible:Language Fundamentals

How you declare your variables depends mainly on personal taste, although most programmers would
have chosen the first example for ease of readability. You aren’t required to place all variable names on
the same line, as I did in the example, however. You can spread them over several lines, if you want, as
long as the last variable name is immediately followed by a semicolon:

int horizontal,
vertical,
x,
y,
z,
months,
years,
days,
ageInDays;

In fact, you can group variable names over several lines, in any way you see fit:

int horizontal, vertical,


x, y, z,
months, years, days,
ageInDays;

Variable types

As you learned in the previous chapter, Java data types fall into two major categories: primitives and
references to objects.

Primitive variables

Your programs will likely use a large number of different primitive variables. Any variable that you
declare of type byte, short, int, long, float, double, char, or boolean is a primitive variable. The following are
examples of variable declarations for each primitive type:

byte x;
short days InMonth;
int counter;
long bacteriaCount;
float accountBalance;
double exactBalance;
char middleInitial;
boolean quit;

file:///F|/books/java%20books/Java%20Bible/ch10/10-01.html (3 of 5)6/26/2005 7:56:45 PM


Java Bible:Language Fundamentals

Reference variables

Reference variables are used to store references, or pointers, to objects. (Keep in mind that we’re not
referring to pointers such as those used in C and C++ here, but simply the concept of pointing to an
object in memory.) These objects can be class instances, class instances that implement interfaces, or
arrays.

An interface is a collection of methods that are not implemented in code; interfaces are
explained in detail in Chapter 11.

Following are examples of reference variable declarations for each category of objects (class instances,
instances that implement interfaces, and arrays):

int highScores[]; /* array of integers */

Initializing and storing values in variables

Once a variable has been declared, a value may be stored in it. This may be done either at the time a
variable is declared—a process known as initialization—or anytime after it has been declared. In either
case, any value assigned to a variable must be of the same type as the variable itself.

These are examples of variables being initialized at the time of declaration:

byte x = 2;
short daysInMonth = 31;
int counter = 1043;
long bacteriaCount = 12239493;
float accountBalance = 533.35;
double exactBalance = 464.3243003;
char middleInitial = ’E’;
boolean quit = false;
String helloString = “Hello World!”;
AudioClip music = getAudioClip(getCodeBase(), “audio/hello.au”);

In each of the above examples, a value consistent with the variable’s data type is assigned to it at the
time of declaration. These variables have been initialized. From the moment they are created, they
contain a value. You’ll notice, however, that there is no example of an array being initialized.

Array initialization

file:///F|/books/java%20books/Java%20Bible/ch10/10-01.html (4 of 5)6/26/2005 7:56:45 PM


Java Bible:Language Fundamentals

In the case of arrays, each element may contain a value. If we declare an array having a dozen integer
elements, it can hold 12 different integers.

An array is typically initialized in two steps. First, we declare the number of elements it will have. Then
each element in the array is individually initialized, or set to a value (usually zero). Here is an example
of how we would initialize our array of integers:

int highScores[] = new int[12]; /* declare array of 12


integers */
for (short i=0; i < 12; i++) {
highScores[i] = 0; /* initialize each array element to zero */
}

As you can see, the for loop used above also contains a variable declaration. We declare an index, i, that
is used to access each element in the array. Before using i, we initialize it to zero (0), since the first
element in every array is at position zero (arrays in Java are zero-based, just as C/C++ arrays are). Each
time through the loop, the ith element in the array is initialized to zero. After 12 iterations, each element
in the array has been initialized to zero.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch10/10-01.html (5 of 5)6/26/2005 7:56:45 PM


Java Bible:Language Fundamentals

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Arrays can be declared and initialized in a single step, instead of in two steps as shown here.
For details, see Chapter 12.

Variable scope

Every variable has an associated scope—the extent to which it can be used. The scope of a variable
begins immediately where it is declared, and ends with the closing brace (}) of the block of code in
which it is declared. You can access a variable only within its scope. If you attempt to access a variable
outside its scope, the compiler generates an error.

For instance, the scope of the variables declared in our MediaHelloWorld applet in Listing 10-1 is the
class definition itself. The variables myImage, myAudio, horizontal, vertical, and SoundOn are all declared
immediately following the class signature, and can therefore be accessed inside the scope of that class.
This means that any of the class methods can access these variables. And, as you can see, each of the
methods accesses at least one class variable.

Listing 10-1: Declaring Variables in the MediaHelloWorld applet

public class MediaHelloWorld extends HelloWorldApplet {


Image myImage;
AudioClip myAudio;
int horizontal, vertical;
boolean SoundOn = true;
public void init() {
super.init();
myImage=getImage(getCodeBase(), “images/world.gif”);
myAudio=getAudioClip(getCodeBase(), “audio/hello.au”
}
public void paint(Graphics g)
{

file:///F|/books/java%20books/Java%20Bible/ch10/10-02.html (1 of 5)6/26/2005 7:56:46 PM


Java Bible:Language Fundamentals

if (myImage !: null)
{ // only draw if the variable contains data!
g.drawImage(myImage, horizontal, vertical, this);
}
super.paint(g);
}
public void start()
{
myAudio.loop();
}
public void stop()
{
myAudio.stop();
}
public boolean mouseDown(java.awt.Event event, int x, int y) {
if (SoundOn) {
myAudio.loop(); SoundOn = false;
}
else {
myAudio.stop();
SoundOn = true;
}
return true;
}
public boolean mouseMove(java.awt.Event event, int x, int y) {
horizontal=x;
vertical=y;
repaint();
return true;
}
} /* the variable scope ends here! */

However, suppose the horizontal and vertical integers were declared in the paint( ) method instead of in the
class itself. If this were the case, the scope of these variables would be the paint() method only Any
attempt to access these variables outside paint( ) would generate an error, since they can’t be accessed
outside of their scope:

public void paint(Graphics g) {


int horizontal=100, vertical:50; /* declared inside the
method */
g.drawImage(myImage, horizontal, vertical, this); /* so this

file:///F|/books/java%20books/Java%20Bible/ch10/10-02.html (2 of 5)6/26/2005 7:56:46 PM


Java Bible:Language Fundamentals

is fine */
super.paint(g);
} /* the scope of horizontal and vertical ends here! */
public boolean mouseMove(java.awt.Event event, int x, int y) {
horizontal=x; /* ILLEGAL - attempt to access outside of
scope! */
vertical=y; /* ILLEGAL - attempt to access outside of
scope! */
repaint();
return true;
}

A special situation can occur in which a variable is hidden by the declaration of another variable with
the same name. This happens if the second variable declaration happens within a sub-block of code
residing in the original variable’s scope. For instance, suppose we declared our horizontal and vertical
variables immediately following the class signature, as in Listing 10-1. Clearly, the scope of these
variables would be the entire class itself.

However, if we also declared horizontal and vertical integer variables inside the paint() method, the original
ones would be hidden from that method. In this case, any reference to horizontal or vertical inside paint( )
would refer to the variables declared in that method, instead of to the class variables of the same name:

int horizontal, vertical; /* original variable declaration */


public void paint(Graphics g) {
int horizontal=100, vertical=50; /* method variables of
same
name */
g.drawImage(myImage, horizontal, vertical, this); /*
refers to
paint() method variables, not those declared earlier */
super.paint(g);
} /* the scope of paint() horizontal and vertical ends here! */
public boolean mouseMove (java.awt.Event event, int x, int y) {
horizontal=x; /* refers to original variable */
vertical:y; /* refers to original variable */
repaint();
return true;
}

Expressions

Expressions are statements that, when executed, result in a value. When programming, we use

file:///F|/books/java%20books/Java%20Bible/ch10/10-02.html (3 of 5)6/26/2005 7:56:46 PM


Java Bible:Language Fundamentals

expressions all the time, sometimes without even realizing it. Java expressions are similar in syntax to
those of C and C++. The following are examples of Java expressions:

65 + 5 /* produces a value of 70 */
(i < 10) /* produces true or false, (depending on the value of
i) */
5 * 100 /* produces 500 */
x = 25 - 5; /* subtracts five from 25, then places the result
(20) in the x variable */
(35*5) - 4 /* produces 171 (multiples 35 and 5, then subtracts
4) */

Expressions are typically composed of several smaller expressions, or subexpressions, connected by


operators. For instance, consider the following lines of code:

iht x = 100, y;
y = (x/4) + 3;

The first line of code, where our variables are declared, actually contains an expression in the
assignment of 100 to the x variable. The integer literal 100 is an expression, albeit a simple one. When
the compiler looks at this line, it sees something like “evaluate the expression to the right of the
assignment operator, =, and place its value in the variable on the left.” Since the expression is the integer
literal 100, it evaluates to 100 and is then stored in the x variable. Pretty simple, yet it’s an expression.

Now take a look at the next line. The complete expression would be:

y = (x/4) + 3;

However, this expression is made up of several subexpressions. You might recognize one right off the
bat:

x/4

While you’d be correct, there are even subexpressions inside this simple statement! The x variable is a
subexpression that evaluates to 100, and the integer literal 4 is another subexpression that evaluates to 4.
After each of these is evaluated and the division operation is performed, the result is 25. To this, the
value 3 is added, yet another subexpression! And finally, the entire value (28) is placed inside the y
variable. As you can see, there are many levels of expressions, even in what appear to be simple
statements.

Operators

file:///F|/books/java%20books/Java%20Bible/ch10/10-02.html (4 of 5)6/26/2005 7:56:46 PM


Java Bible:Language Fundamentals

Since Java expressions are typically several subexpressions linked together by operators, it’s important
to understand exactly how operators work. Java supports both unary and binary operators. Unary
operators are those that act on a single operand, while binary operators act on two operands.

The following is an expression using the unary postfix increment operator. As you can see, it requires
only one operand (x, in this case):

X++;

And here is the functional equivalent of the above using the binary addition operator:

x=x+1;

In this case, the binary addition operator acts on two operands (x and 1). Once the right-hand side of the
assignment operator is evaluated, the result is stored in the x variable on the left.

These two expressions do the same thing; they both increase the value of x by one. However, we’ve used
a different operator in each case. In the first example, the unary operator ++ was used. In the second
example, the binary addition operator + was used.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch10/10-02.html (5 of 5)6/26/2005 7:56:46 PM


Java Bible:Language Fundamentals

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Operator precedence

Expressions are evaluated from left to right, according to the precedence of the operators in the
expression—that is, the rules that determine which operators are executed first. By following a
precedence order, Java guarantees that a particular expression will produce the same results every time it
is executed. For instance, take into consideration the following expression:

x = 15 + 3 * 2 - 14;

Without a precedence order, which subexpression is evaluated first? Should it be 15 + 3, 3 * 2, or 2 - 14?


For that matter, once the first subexpression is evaluated, which is next? Clearly, the value of the
expression changes, depending on the order in which its subexpressions are evaluated.

If we couldn’t rely on the order in which operations were performed, it would make our programs about
as consistent as the New York City subway system. Luckily, Java operators are arranged and executed in
order of precedence. Table 10-1 lists all Java operators according to their precedence order. You’ll see
that I’ve placed parentheses first in this table. They aren’t really an operator, since they don’t perform an
operation on data types, but they appear in the table nonetheless to emphasize that they’re given top
priority during evaluation (see “Forcing order” later in this chapter).

Table 10-1
Java Operator Precedence

Precedence Associativity Operator Description

First N/A () parentheses (forcing order)

Second R-to-L ++ pre/post increment (unary)

R-to-L -- pre/post decrement (unary)

file:///F|/books/java%20books/Java%20Bible/ch10/10-03.html (1 of 3)6/26/2005 7:56:46 PM


Java Bible:Language Fundamentals

R-to-L ! logical complement (unary)

R-to-L ~ unary bitwise logical negation

R-to-L + addition (unary)

R-to-L - subtraction (unary) cast object to class


(className) type

Third L-to-R */% multiplication, division, and remainder

Fourth L-to-R +- addition and subtraction

Fifth L-to-R << shift left

L-to-R >> shift right (sign extension)

L-to-R >>> right shift (zero extension)

Sixth L-to-R < <= “less than” and “less than or equal to”

L-to-R >>= “greater than” and “greater than or


equal to”

L-to-R instanceof “is the object an instance of this class?”

Seventh L-to-R == equality

L-to-R != non-equality (not equal)

Eighth L-to-R & bitwise AND, boolean AND

Ninth L-to-R ^ bitwise EXCLUSIVE OR (XOR),


boolean EXCLUSIVE OR (XOR)

file:///F|/books/java%20books/Java%20Bible/ch10/10-03.html (2 of 3)6/26/2005 7:56:46 PM


Java Bible:Language Fundamentals

Tenth L-to-R | bitwise OR, boolean OR

Eleventh L-to-R && AND (boolean conditional “short-


circuit”)

Twelfth L-to-R || OR (boolean conditional “short-


circuit”)

Thirteenth R-to-L ?: ternary conditional

Fourteenth R-to-L = assignment

Last R-to-L *= /= assignment (and operation)


%= += -=
<<= >=
>>>= &=
^=|=

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch10/10-03.html (3 of 3)6/26/2005 7:56:46 PM


Java Bible:Language Fundamentals

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Since all operations are performed according to the precedence of the operators involved, Java
expressions are evaluated in a predictable manner. Operations whose operators have the highest
precedence are performed first, with lower precedence operators following in sequence. When
operations of the same precedence occur within the same expression, they are processed according to
operator associativity.

When two operations of the same precedence are encountered, which is performed first? It all
depends on the order, or associativity, specified for the operators involved. An operator’s
associativity determines whether it is evaluated from right to left (R-to-L) or left to right (L-to-
R). See the next section, “Forcing order,” to learn how to bypass an operator’s natural
associativity.

Now, let’s return to our example:

x = 15 + 3 * 2 - 14;

Thanks to operator precedence, we can see that it evaluates in a very specific order. The middle
operation (3 * 2) is performed first, and then the next two operations are carried out from left to right:

3*2 produces 6, which is used in the next operation


15 + 6 produces 21, which is used in the final operation
21 - 14 produces 7, which is stored in the variable x

Forcing order

If the natural order of evaluation isn’t desired, you can use parentheses to control the order of evaluation.
For instance, suppose you wanted the subexpression 2 - 14 to be evaluated first. You could ensure this by
placing it inside parentheses:

x = 15 + 3 * (2 - 14);

file:///F|/books/java%20books/Java%20Bible/ch10/10-04.html (1 of 2)6/26/2005 7:56:47 PM


Java Bible:Language Fundamentals

In this case, the following steps are taken when the expression is evaluated:

2 - 14 produces -12, which is used in the next operation


3 * - 12 produces -36, which is used in the final operation
15 + -36 produces -21, which is stored in the variable x

Since multiplication operators have precedence over arithmetic ones, this operation is performed after
the subexpression inside parentheses. However, we could have added another pair of parentheses to
force the multiplication operation to take place last:

x = (15 + 3) * (2 - 14);

In this case, the subexpressions inside the parentheses are of the same precedence. As a result, they are
carried out from left to right. The steps are:

15 + 3 produces 18, which is used in the final operation


2 - 14 produces -12, which is used in the final operation
18 * -12 produces -216, which is stored in the variable x

And, of course, parentheses can be nested. We could, for example, group these three subexpressions by
surrounding them with parentheses and add another subexpression to the mix. Here are a few examples,
each producing a different data type:

x = ((15 + 3) * (2 - 14)) + 1; /* produces an integer value */


x = ((15 + 3) * (2 - 14)) + 1.2; /* produces a floating-point
value */
x = ((15 + 3) * (2 - 14)) > 1; /* produces a boolean value */

Types of operators

The types of operators that can be used in an operation depend on the data type of the operands
involved. For instance, the operators used in an integer operation are different from those used in a
boolean operation.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch10/10-04.html (2 of 2)6/26/2005 7:56:47 PM


Java Bible:Language Fundamentals

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Integer operators

The operators used in integer operations are listed in Table 10-2. The result of an integer operation
depends on the data type of the operands involved.

Table 10-2
Arithmetic Operators

Type Operator Operation Notes

Unary - negation

~ bitwise
complement

++ increment postfix and prefix

— decrement postfix and prefix

abs( ) absolute value usage: a = abs(3);

Binary + addition

+= addition ( a =a+b ) is equivalent to ( a+=b )

- subtraction

file:///F|/books/java%20books/Java%20Bible/ch10/10-05.html (1 of 3)6/26/2005 7:56:47 PM


Java Bible:Language Fundamentals

-= subtraction ( a= a - b ) is equivalent to ( a -= b )

* multiplication

*= multiplication ( a=a*b ) is equivalent to ( a*=b )

/ division rounds toward zero; division by zero


throws ArithmeticException

/= division ( a=a/b ) is equivalent to ( a/=b )

% modulo %0 throws ArithmeticException

%= modulo ( a=a%b ) is equivalent to ( a%=b )

>>= right shift ( a=a>>b ) is equivalent to ( a>>=b )


(propagate sign)

<< left shift

> right shift sign is propagated

>>> zero-fill right shift pads with zeros on left

max( ) maximum value of usage: i = max(x,y);


range

min() minimum value of usage: i = min(x,y);


range

For instance, if both operands in an integer operation are int data types, the result will be an int. If one
operand is an int and the other a long, the result will be a long. However, regardless of the operands
involved, an integer operation will always produce either an int or a long value. This is true even in cases
where the operands are byte, short, or char data types.

As mentioned in the previous chapter, an ArithmeticException is thrown if an attempt is made to divide an

file:///F|/books/java%20books/Java%20Bible/ch10/10-05.html (2 of 3)6/26/2005 7:56:47 PM


Java Bible:Language Fundamentals

integer by zero (0). The same holds true for modulo arithmetic: ArithmeticException is thrown whenever %
0 is encountered.

If the result of an integer operation overflows (that is, it is beyond the legal range of the result
type), it will be reduced by modulo arithmetic. It is important, therefore, to ensure that your
variables are capable of storing the range of values that might be returned when assigning the
result of operations to variables.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch10/10-05.html (3 of 3)6/26/2005 7:56:47 PM


Java Bible:Language Fundamentals

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

String operators

As you know, strings in Java are actually String objects. If the arithmetic addition operator (+) is used
when one (or both) of the operands is of type string, the operation is considered a string concatenation. If
only one of the operands is of type string, the other operand is converted into a string before the
concatenation is carried out.

When a nonstring operand is converted to a string, the process is carried out according to the compile-
time type of the operand.

If the value of the operand is null, then the literal string null is used. If the value is other than null, the
toString( ) method of the operand is invoked. This method returns a reference value of type string, which is
used (unless this value is null, in which case the literal string null is used). Since the class Object defines
a toString( ) method, this method is always available when dealing with objects, even if the operand itself
doesn’t implement a toString( ) method.

If the operand is of the primitive integral type, it’s converted into a string representing the value in
decimal notation. If the value of the operand is negative, the string is preceded by a minus sign. If the
value is nonzero, the first digit is nonzero. If the value is zero, the single digit 0 is produced.

If the operand is of type char, it’s converted to a string containing the single character of the char.

If the operand is of type boolean, it’s converted into a string containing the boolean’s value (either the
literal string “true” or the literal string “false”).

Array operators

When operations are performed on arrays, they return the value of a specific element in that array.
However, unlike the data types we’ve been dealing with thus far, an array must be allocated using the
new operator before it can be assigned to a variable:

int a[] = new int[15];

file:///F|/books/java%20books/Java%20Bible/ch10/10-07.html (1 of 4)6/26/2005 7:56:48 PM


Java Bible:Language Fundamentals

In the preceding example, an array of 15 integer elements is created and assigned to the variable a. Once
this operation has taken place, we can store and retrieve values in the array elements using the following
syntax:

arrayVariable[expression]

For instance, each of the following lines of code accesses the same element in our array:

int x = 5, y = 2, z = 10; /* initialize a few integer


variables */
a[10] = 82569; /* store 82569 in 11th element */
a[z] = 4370; /* store 4370 in 11th element */
a[x*y] = 111791; /* store 111791 in 11th element */
a[x+5] = 592; /* store 592 in 11th element */
int i;
i = a[10]; /* retrieve 11th element */
i = a[x+5]; /* retrieve 11th element */
i = a[100/z+l] /* retrieve 11th element */
i = a[a.length - 5]; /* retrieve 11th element */

In the last example, we used the instance variable length in the expression. Since a.length returns the
number of elements in the array, this is a valid expression.

Since Java arrays are zero-based, like C/C++ arrays, using the subscript 10 as we do here
actually accesses the 11th element. For details on zero-based array access, see Chapter 12.

If, in any case, an array index is negative or greater than the number of elements in the array minus one
(14, in our example), an ArrayIndexOutOfBoundsException is thrown. Continuing with our previous
example, the following operations would cause an out-of-bounds exception:

a[x+z]; /* expression evaluates to 15, an illegal index value */


a[x*x]; /* expression evaluates to 25, an illegal index value */
a[a.length]; /* expression evaluates to 15, an illegal index
value */

Array index values can be of byte, short, int, or even char types. However, array indexes of type long are
not permitted. In order to use a long, it must be cast into the int type, as the following example shows:

long myLong = 10;


a[myLong]; // illegal, since array indexes can’t be of type long

file:///F|/books/java%20books/Java%20Bible/ch10/10-07.html (2 of 4)6/26/2005 7:56:48 PM


Java Bible:Language Fundamentals

a[(int) myLong]; // legal, since the long is cast into an int

Keep in mind that array indexing begins at zero, as explained in Chapter 7. In this example, as
with all arrays, the first element is accessed with an index value of zero: a[0]. Since we have 15
elements in this particular array (from index 0 to 14), the last element is referenced with an
index value of 14: a [14]. For details on arrays, see Chapter 12.

Object operators

In Java, a special operator exists that allows you to determine whether an object is an instance of a
particular class, subclass, or interface. Using the instanceof binary operator, you can test objects to
compare them against a specific class or interface type:

if (theObject instanceof ClassName) {


}

Control-Flow Statements

In order to direct the flow of program execution, Java supports several control-flow statements. These
are similar to their C and C++ counterparts, so they look and act as you would expect if you’re already
familiar with one (or both) of these languages. We’ll take a look at each, beginning with the popular if
statement.

if statements

Java supports two types of if statements, both of which require the use of a boolean expression. This is
the syntax for the most basic if statement:

if (boolean expression) { ...


}

Depending on the value of the boolean expression, the body of the if statement may or may not be
executed. If the expression evaluates to true, the body is executed. If the expression evaluates to false, the
body of code is skipped.

Take, for example, the following if statement:

if (x < 10) {
System.out.println (“The if block is being executed.”);
System.out.println (“And the value of x is: ” + x);
}

file:///F|/books/java%20books/Java%20Bible/ch10/10-07.html (3 of 4)6/26/2005 7:56:48 PM


Java Bible:Language Fundamentals

When the preceding statement is encountered, this boolean expression is evaluated:

x<10

The body of code following the if statement executes only in cases where x is less than 10. If x is equal
to (or greater than) 10, the block of code is skipped and program execution continues immediately after
the closing brace (}).

This form of control flow is often called an if-then statement, since it follows the logic of “if the
expression is true, then execute this body of code.”

The second form of if statement makes use of the keyword else, directing program execution along one
of two distinct routes:

if (boolean expression) {
...
}
else {
...
}

If the boolean value evaluates to true, the block of code immediately following is executed. If the
expression evaluates to false, the else block is executed.

This form of control flow is often called an if-then-else statement, since it follows the logic of
“if the expression is true, then execute this body of code, or else execute this one.”

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch10/10-07.html (4 of 4)6/26/2005 7:56:48 PM


Java Bible:Language Fundamentals

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Floating-point operators

Operations on floating-point numbers behave much the same as those on integers, using the same
operands (see Table 10-2). If both operands in an operation are of type float, the result is also of type
float. If one of the operands is of type double, the result will be of type double.

However, there are a few slight differences between integer and floating-point operations. For example,
when the unary increment (++) or decrement (- -) operators are used with a floating-point operand, the
value of 1.0 is added to the operand (when applied to integers, the value of 1 is added).

Another difference occurs with the modulo (%) operator. When applied to integers (such as 10%4), the
remainder of the division operation, 10/4, is returned as an integer (2). When the modulo operator is
applied to a floating-point number, the remainder of the division operation is returned as a floating-point
value.

Floating-point operations will never generate an ArithmeticException error, however, as explained in the
previous chapter. Instead, a special value, NaN (Not-a-Number), is used to represent the result of
operations that don’t return a number.

The presence of a NaN can produce unexpected results when dealing with floating-point data
types. Since NaN is unordered, the result of a <, <=, >, >=, or = = comparison between a NaN
and another value is always false. In fact, == always produces false when both operands are
NaN. On the other hand, the result of a != comparison with a NaN is always true, even if both
operands are NaN.

Boolean operators

When an operation involves the use of a boolean operator, the result of that operation will return a
boolean value of either true or false. This is the case even if the operands are not of the boolean data type,
as the following code snippet shows:

int x = 3: // declare integer variable initialized to 3

file:///F|/books/java%20books/Java%20Bible/ch10/10-06.html (1 of 3)6/26/2005 7:56:49 PM


Java Bible:Language Fundamentals

boolean myBoolean; // declare boolean variable


myBoolean = x < 10; // a boolean expression

Since the expression x <10 uses the “less than” boolean operator, it returns a boolean value which we
store in the variable myBoolean. In this example, myBoolean would be set to true, since x is indeed less than
10.

Table 10-3 contains the boolean operators supported by Java.

Table 10-3
Boolean Operators

Type Operator Operation Notes

Unary ! negation

Binary & logical AND evaluate both operands

&= logical AND (a=a&b) is equivalent to (a&=b)

| logical OR evaluate both operands

|= logical OR ( a=a | b ) is equivalent to ( a | =b )

^ logical XOR evaluate both operands

^= logical XOR ( a=a^b ) is equivalent to ( a^=b )

&& logical AND short-circuit evaluation of operands

|| logical OR short-circuit evaluation of operands

> greater than

< less than

file:///F|/books/java%20books/Java%20Bible/ch10/10-06.html (2 of 3)6/26/2005 7:56:49 PM


Java Bible:Language Fundamentals

>= greater than or


equal to

<= less than or equal


to

== equality

!= inequality

Ternary ?: if, then (if a. then b) is equivalent to (a?:b)

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch10/10-06.html (3 of 3)6/26/2005 7:56:49 PM


Java Bible:Language Fundamentals

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Our previous example looks like this, using the if-then-else statement:

if (x < 10) {
System.out.println (“The if block is being executed.”);
System.out.println (“And the value of x is: ” + x);
}
else {
System.out.println (“The else block is being executed.”);
System.out.println (“And the value of x is: ” + x);
}

At any given time, only one of the above blocks of code will be executed. At no time will both be
executed, since the value of the boolean expression directs flow of execution in only one of two possible
directions, not both.

You can use the else-if construct to add another aspect of control to the if statement:

if (boolean expression) {
...
}
else if (boolean expression)
...
}
else {
...
}

Applying this to our previous example, we can exercise more precise control over the flow of program
execution:

if (x < 10) {
System.out.println (“The if block is being executed.”);
System.out.println (“And the value of x is: ”+ x);

file:///F|/books/java%20books/Java%20Bible/ch10/10-08.html (1 of 5)6/26/2005 7:56:50 PM


Java Bible:Language Fundamentals

}
else if (x == 15) {
System.out.println (“The else-if block is being executed.”);
System.out.println (“And the value of x MUST be 15!”);
}
else {
System.out.println (“The else block is being executed.”);
System.out.println (“And the value of x is: ”+ x);
}

Unlike if statements in C, Java if statement expressions must return a boolean value. In C, a


value of 0 (zero) is treated as false and a value of 1 is treated as true. This is not the case with
Java, where only boolean expressions can be used in an if statement.

switch statement

The switch statement is similar in nature to the if-then-else statement, although it makes the programmer’s
job a lot easier when a number of else clauses are needed:

switch (expression) {
case Constant1:
...
break ;
case Constant2:
...
break;
case Constant3:
...
break;
.
.
.
default:
...
break;
}

Upon entering a switch statement, the expression is evaluated.

The data type of the expression must be either char, byte, short, or int. Boolean expressions aren’t allowed,
although they are used in all other control-flow mechanisms.

file:///F|/books/java%20books/Java%20Bible/ch10/10-08.html (2 of 5)6/26/2005 7:56:50 PM


Java Bible:Language Fundamentals

The value of the expression is then converted to the int type, as are all the case constants. Beginning with
the first case statement, the value of the expression is compared to the value of the case constant. If the
two values are equal, any code following the colon is executed, until the break statement is reached. If the
expression doesn’t match the case constant, it is compared to the next one. This process continues until
the default case is reached, at which point the code for this case is executed.

When a case is executed, the break statement is used to stop the flow of execution. When a break
statement is reached, execution stops immediately and resumes after the closing brace (}) of the switch
body. Since execution terminates when the first break is encountered, the default case will only be
executed if no match is found between the value of the switch expression and all other cases.

The switch statement is particularly useful when a number of cases exist. If you were to try and write
more than half a dozen else clauses in an if-else statement, you’d find the process more than a bit tedious.
It would be even more difficult to read the code, since if-else statements containing more than a handful
of clauses are typically messy when compared with a switch statement of the same length. With a switch
statement, lengthy code is clean and easy to read by comparison. You can use as many cases as you
need, without making a mess of the code. And, if none of the cases match the value of your expression,
you can rely on the default case being executed.

Be certain to end each case with a break statement. If you don’t, all cases following the
matching one will be tested as well! This is an undesirable condition known as fall-through,
which you can avoid by matching a break statement with every case.

Loops

Control-flow statements include a number of loops:

• while loops
• do-while loops
• for loops

while and do-while loops

Java while and do-while loops are identical to those in C:

while (boolean expression) {


...
}
do {
...
} while (boolean expression);

file:///F|/books/java%20books/Java%20Bible/ch10/10-08.html (3 of 5)6/26/2005 7:56:50 PM


Java Bible:Language Fundamentals

In the while loop, the boolean expression is evaluated. The value of this expression determines whether
or not the body of the loop is executed. If the expression evaluates to true, the loop is executed. If
expression value is false, it does not execute. Each time through the body of the while loop, the
expression is re-evaluated. The loop continues until the expression evaluates to false:

int x = 0;
while (x++ < 10) {
System.out.println (“The while loop is being executed.”);
System.out.println (“And the value of x is: ” + x);
}

In the preceding example, the body of the loop continues executing as long as x is less than 10. Since we
increment the value of x by one (x++) in the expression itself, the loop is executed 10 times.

Note that the increment could also have taken place in the body of the loop itself, as follows:

while (x < 10) {


X++;
System.out.println (“The while loop is being executed.”);
System.out.println (“And the value of x is: ” + x);
}

With the do-while loop, the body of the loop executes once before the expression is ever evaluated. This
ensures that your loop code is executed at least once, regardless of how the expression evaluates:

do {
System.out.println (“The while loop is being executed.”);
System.out.println (“And the value of x is: ” + x);
} while (x++ < 10);

As with the while loop, we could have incremented our expression inside the loop body, rather than
inside the expression:

do {
System.out.println (“The while loop is being executed.”);
System.out.println (“And the value of x is: ” + x);
X++;
} while (x < 10);

The while loop is by far the most popular of the two, although the do-while loop has the advantage of
executing your code at least once, no matter what the expression evaluates to.

file:///F|/books/java%20books/Java%20Bible/ch10/10-08.html (4 of 5)6/26/2005 7:56:50 PM


Java Bible:Language Fundamentals

Be sure to change your expression value either inside the body of the while or do-while loop, or
in the expression itself. If the value never changes, the expression always remains true and the
loop executes indefinitely!

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch10/10-08.html (5 of 5)6/26/2005 7:56:50 PM


Java Bible:Language Fundamentals

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

for loop

The for loop repeats program execution as controlled through a series of expressions, terminating when a
certain condition is no longer met. It continues looping until the specified boolean condition evaluates to
false, at which point the loop is broken and execution resumes after the loop body:

for (expression; booleanExpression; expression) {


...
}

The first expression initializes the loop variable. The second is a boolean expression that specifies the
condition that must be met in order for the loop body to be executed. The third and final expression
specifies how the loop variable is to change each time through the loop.

Consider the following example:

int x;
for (x=0; x<10; x++) {
System.out.println (“The for loop is being executed.”);
System.out.println (“And the value of x is: ” + x);
}

The first expression, x=0, sets our loop variable to zero. The loop executes until the second expression, x
<10, evaluates to true. And the final expression, x++, increments our loop variable by one every time
through the loop.

Unlike C, Java supports the declaration of loop variables inside the initialization portion of the loop
statement:

for (int x=0; x<10; x++) {


System.out.println (“The for loop is being executed.”);
System.out.println (“And the value of x is: ” + x);

file:///F|/books/java%20books/Java%20Bible/ch10/10-09.html (1 of 4)6/26/2005 7:56:51 PM


Java Bible:Language Fundamentals

In this case, the scope of the loop variable is the loop itself. You’re free to access x, as long as you do so
in the body of the for loop. However, you can’t use x outside the closing loop brace (}), since access
outside the loop is beyond the scope of this variable.

break and continue statements

In addition to the if, switch, while, and do-while control-flow constructs, Java supports two additional
statements: break and continue. These are considered “jump” statements, because they allow the flow of
program execution to branch out in directions not seen with the standard control-flow statements we’ve
already discussed.

As you’ve seen, the switch statement makes use of the break statement to terminate a specific case’s
execution. However, those break statements were used without labels. Both break and continue can be used
with an optional label that specifies exactly where the execution will be transferred. Without a label,
break and continue behave exactly as they do in C.

Take a look at the following example of a labeled break statement in a switch occurring in a while loop:

int x=0;
enterLoop:
while (x++<10) {
System.out.println (“Inside the while loop, iteration:” + x);
switch (x) {
case 0: System.out.println (“Inside switch, x
equals: ” +
x);
break;
case 1: System.out.println (“Inside switch, x equals: ” +
x);
break;
case 2: System.out.println (“Inside switch, x equals: ” +
x);
break;
default:
if (x==5) {
System.out.println (“Break out of switch, and while loop
too!”);
break enterLoop; /* break to enterLoop label */
}
break;

file:///F|/books/java%20books/Java%20Bible/ch10/10-09.html (2 of 4)6/26/2005 7:56:51 PM


Java Bible:Language Fundamentals

}
System.out.println (“Out of switch, back in while loop.”);
}

Each time through the while loop, the switch statement is encountered. Up until the time x is equal to 5,
standard break statements are used to break out of the switch statement and back into the while loop.
However, when x is equal to 5, the following line of code is executed:

break enterLoop

When this happens, not only does the break occur for the switch statement, but also for the entire while
loop! If this labeled break were not present, the while loop would execute ten times. However, it only
executes five times, since the labeled break kicks the flow of control out of both the switch and while loop.

While the break statement is used to break out of the loop, a labeled continue statement redirects it to the
label itself.

Unlike break, the labeled continue statement transfers control of program execution to the iteration
following the label:

int x=0;
enterLoop:
while (x++<5) {
System.out.println (“Inside the while loop, iteration: ” + x);
for (int i=0; i<10;i++) {
System.out.println (“Inside the for loop, iteration: ” +
i);
if (i == 5) {
System.out.println (“Transferring flow out of for
loop!”);
continue enterLoop; /* jump to enterLoop label when i
is 5*/
}
}
System.out.println (“Out of for loop, back in while.”);
}

Here, we’ve created a for loop inside a while loop. Each time through the while loop, the for loop is
executed until i equals 5, at which point program execution jumps out of the for loop and goes to the first
statement inside the while loop:

System.out.println (“Inside the while loop, iteration: ” + x);

file:///F|/books/java%20books/Java%20Bible/ch10/10-09.html (3 of 4)6/26/2005 7:56:51 PM


Java Bible:Language Fundamentals

When this happens, the final output line in our while loop isn’t executed, since the flow of execution has
been rerouted to its beginning. However, if we hadn’t included a label, the break statement alone would
have rerouted the execution to the first line of code following the for loop. In that case, the final output
line would have been executed.

In Java, there are actually four jump statements:

• break
• continue
• return
• throw

The return statement is used to return program execution to the caller of a code segment, such as when a
method has been invoked. At any point in the method, a return statement can return the flow of control
back to the caller of that method.

The throw statement is used to signal a runtime exception, as described below, which interrupts the flow
of program execution while a hander is sought to deal with that exception.

Exceptions

Java features a general-purpose error processing system known as an exception mechanism. The
exception mechanism is composed of two parts: throwing exceptions and catching them. To throw an
exception means to signal an error, while to catch one is to trap and handle an error that has been
thrown. While new to C programmers, exceptions provide a uniform approach to signaling and
processing errors, removing much of the burden of traditional error processing.

The term exception is short for “exceptional event.” Exceptional events are those that disrupt
the normal flow of program execution. C++ programmers will find Java’s exception
mechanism very similar to that of C++, and will be throwing and catching exceptions in no
time. If you’re a C programmer, you’ll find learning to use Java’s exception mechanism well
worth the effort.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch10/10-09.html (4 of 4)6/26/2005 7:56:51 PM


Java Bible:Language Fundamentals

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

In languages other than Java, such as C, each function is responsible for signaling success or failure
during its execution. In many cases, this is done by returning an integer value that the caller can test.
Typically, if the return value of a function is zero, the function has been executed without error. If a
nonzero value is returned instead, an error may have occurred during execution.

However, not all routines return error codes, and those that do don’t necessarily report errors in the same
way. Some may return an error code, others might return a null value, and still others might set a global
error variable. Such inconsistencies place a substantial burden on the programmer, who must learn the
error-reporting mechanism employed by each routine and write the appropriate code to test for such
errors.

As a result, many programmers save time by testing only for errors generated by critical routines, not
bothering with the others. In some cases, the programmer may not fully understand the routine in
question and handle errors incorrectly, in both cases, the integrity of the program suffers and error
checking becomes a nuisance, if not a nightmare.

Using exceptions, Java provides developers with a consistent and relatively simple mechanism for
signaling and dealing with errors. Exceptions provide methods with a way to stop program execution
when an error is encountered, while allowing the method to notify its caller that a problem has occurred.
If the caller chooses, it may ignore, or “duck” the exception, in which case the exception is passed down
the call stack until it is dealt with. However, exceptions only allow you to temporarily pass the buck
when an error is encountered, since you must deal with it eventually.

Call stack

A call stack is nothing more than the sequence of methods that have been invoked. For instance, if a
method named drawShape( ) calls another method named drawCircle( ), we’d have a pretty simple call
stack, as shown in Figure 10-1. Here, we can see that drawShape( ) called the drawCircle( ) method. The
drawShape( ) method is said to be at the “bottom” of the stack, while drawCircle( ) is at the “top.”

file:///F|/books/java%20books/Java%20Bible/ch10/10-10.html (1 of 4)6/26/2005 7:56:51 PM


Java Bible:Language Fundamentals

Figure 10-1: A very simple call stack, having only two method calls

However, drawCircle( ) might invoke another method named draw(). This would then sit at the top of the
call stack. And draw( ) might call another method, named paint( ), as the call stack continued to grow. If
an exception occurred in paint( ), it could possibly be ignored by every method. As a result, the exception
would be passed all the way down the call stack, as illustrated in Figure 10-2.

Figure 10-2: An exception is passed down the call stack until it’s handled by a method.

If an exception isn’t handled by a method, it’s passed down the call stack to the method below it. If none
of the methods in the call stack catch the exception by the time it reaches the bottom, and the method at
the bottom doesn’t catch it either, the program is aborted!

Somewhere along the way, the exception has to be caught and dealt with. If it isn’t, the program is
aborted. If you attempt to write a Java program that would result in such a situation, the compiler warns
you about it.

In the last rendition of our HelloWorld applet, FlexibleMediaHello, we were forced to catch the
exception that might have resulted when converting strings into URLs. Since the compiler recognized
that the URL( ) method had the potential to throw an error (such as when the method is passed an invalid
string), it refused to compile our program until we wrote an exception handler to catch such errors. In
Java, all non-runtime exceptions must be caught or declared, as described below. If they are not, the
compiler spits out an error message (see Figure 10-3) and refuses to compile the program.

Figure 10-3: If a non-runtime exception is not caught or declared, Java throws out an error message.

If the compiler realizes that a non-runtime error hasn’t been properly handled, it refuses to compile the
code. When this is the case, you must either catch or declare the exception (see the section “Catch or
declare: It’s the law,” later in this chapter).

Throwing exceptions

Before an exception can be caught, it must be thrown. Exceptions can be thrown by any Java code: Your

file:///F|/books/java%20books/Java%20Bible/ch10/10-10.html (2 of 4)6/26/2005 7:56:51 PM


Java Bible:Language Fundamentals

own code, code in the packages that come with the Java development environment, or code in packages
written by others. Even the Java runtime system can throw exceptions that your programs must catch.

When an exception is thrown, the Java runtime system receives a signal that an error has been generated.
Exceptions are thrown to flag errors, which is something you would do in your own programs to notify
the system that an error has occurred. As soon as an exception is thrown, the runtime system searches
for the matching catch clause to handle it.

Exceptions are thrown using the following Java syntax:

throw new AnyExceptionObject( );

Regardless of what code raises an exception, it’s always done using the throw statement. It takes a single
argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class
defined in the java.lang package. In our example above, we instantiated a throwable object:

new AnyExceptionObject(); /* instantiate a throwable object */

If you attempt to throw an object that isn’t throwable, the compiler emits an error message and
refuses to complete the compilation process. Most exception objects you’ll encounter are
derived from either the Exception class, the RuntimeException class, or the Error class. Each of
these classes is a subclass of Throwable (java.lang.Throwable), and therefore produces objects (or
is extended by other classes) that are considered throwable.

Consider for a moment the following method declaration:

public static int myDivide(int x, int y) throws


ArithmeticException {
if (y==0)
throw new ArithmeticException( );
else
return (x/y);
}

In the method signature we declare this method as being capable of throwing ArithmeticException:

throws ArithmeticException

The Java language requires that methods either catch or declare all non-runtime exceptions they can
throw. With the line above, we declare that our myDivide( ) method throws the ArithmeticException,
satisfying this requirement.

file:///F|/books/java%20books/Java%20Bible/ch10/10-10.html (3 of 4)6/26/2005 7:56:51 PM


Java Bible:Language Fundamentals

In cases where you wish to define your own methods, you simply create a new class that is a subclass of
Exception. Here is the same program, but using a custom exception:

class MyOwnException extends Exception {


}
public static int myDivide(int x, int y) throws MyOwnException
{
if (y==0)
throw new MyOwnException();
else
return (x/y);
}

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch10/10-10.html (4 of 4)6/26/2005 7:56:51 PM


Java Bible:Language Fundamentals

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

However, throwing exceptions is only half the battle. In order to write effective Java programs, you must
be able to catch exceptions as well.

For detailed information on creating your own exceptions, refer to the Java Language Tutorial.
This step-by-step guide to learning the Java language is available in the documentation section
of the JavaSoft Web site:
http://java.sun.com/docs/books/tutorial/index.html.

Catching exceptions

When an exception is thrown, the Java runtime system immediately stops the current flow of program
execution and looks for an exception handler to catch it. Searching backward through the call stack
(refer to Figure 10-2), a corresponding handler is sought starting with the method where the error
occurred.

The search continues down the call stack until a method containing an appropriate exception handler is
found. The first handler encountered that has the same type as the thrown object is the one chosen to
deal with the exception.

If the exception travels all the way down the call stack with no handler catching it, the program aborts
execution. Typically, an error message is output to the terminal display in such cases. This, of course,
assumes the exception is a runtime exception that can’t be seen by the compiler.

Dividing a number by a variable that happens to be zero, accessing an array element using an index
value (subscript) that is beyond the legal range, accessing null objects, and similar dynamic activities
produce runtime exceptions that aren’t recognized at compile time. As a result, the compiler can’t force
you to catch such exceptions, since it doesn’t even realize they exist. And, in cases where a runtime
exception propagates to the bottom of the call stack, your program is aborted.

try-catch clause

In order to catch an exception, you must write an exception handler using the try-catch clause. For

file:///F|/books/java%20books/Java%20Bible/ch10/10-11.html (1 of 4)6/26/2005 7:56:52 PM


Java Bible:Language Fundamentals

instance, suppose we wanted to use the original myDivide( ) method created earlier. In order to catch the
exception that might result, we’d write the following try-catch clause:

try {
int y = myDivide(10,0);
} catch (ArithmeticException e) {
System.out.println(“Whoops There it is!”);
}

try block

The first part of a try-catch clause, the try block, encloses those statements that may throw an exception.
Here is the syntax of a typical try block:

try {
...
/* statements capable of throwing an exception */
...
}

The only code in our example capable of throwing an exception is the myDivide ( ) method. However, you
can include in the try block any number of legal Java statements that have the potential to throw an
exception. As you can see, we intentionally supply myDivide( ) with parameters that will cause an
exception to be thrown. Specifically, the second integer passed to the method is zero.

If we had additional lines of code following myDivide (10, 0), they wouldn’t be executed. Instead, myDivide
( ) would throw an exception that would immediately stop program execution at that point, which would
then drop into the catch portion of the try-catch clause.

catch block

Following the try block are one or more catch blocks that you can use to trap and process exceptions. This
is the catch block syntax:

catch (ThrowableClassName variable) {


...
}

Although we only supplied one catch block in the myDivide( ) exception handler, any number could have
been provided. However, since the myDivide( ) method throws only one exception, we have to catch that
one. In our example, we merely output a line of text to prove that our exception was indeed caught. In
the case of multiple catches, the try-catch clause has this syntax:

file:///F|/books/java%20books/Java%20Bible/ch10/10-11.html (2 of 4)6/26/2005 7:56:52 PM


Java Bible:Language Fundamentals

try {
...
} catch (ThrowableClassName variable) {
...
} catch (ThrowableClassName variable) {
...
} catch (ThrowableClassName variable) {
...
} catch (ThrowableClassName variable) {
...
}

For instance, suppose myDivide( ) was capable of throwing two different exceptions. In this case, we
would provide a catch block for each of the possible exceptions:

try {
int y = myDivide(10,0);
} catch (ArithmeticException e) {
System.out.println(“Have caught an ArithmeticException.”);
} catch (MyOwnException e) {
System.out.println(“Have caught MyOwnException.”);
}

The exception that is thrown is compared to the argument for each catch block in order (the catch
argument can be an object or an interface type). When a match is found, that catch block is executed. If
no match is found, the exception propagates down the call stack, where it is compared against potential
exception handlers until a match is found. And, as always, if no match is found, the program is aborted.

You can access the instance variables and methods of exceptions, just as for any other object.
With this in mind, you can invoke the exception’s getMessage( ) method to get information on
the exception—get Message( ) is a method defined in the Throwable class:

System.out.ptintln(e.getMessage());

The Throwable class also implements several methods for dealing with the call stack when an
exception occurs (such as ptintStackTrace( ), which outputs the call stack to the display). The
Throwable subclass that you, or anyone else, creates can implement additional methods and
instance variables. To find out what methods an exception implements, look at its class and
superclass definitions.

file:///F|/books/java%20books/Java%20Bible/ch10/10-11.html (3 of 4)6/26/2005 7:56:52 PM


Java Bible:Language Fundamentals

finally block

Unlike C++, Java’s try-catch clause supports the use of an optional finally block. If defined, this is
guaranteed to execute, regardless of whether or not an exception is thrown. As a result, you can use it to
perform any necessary clean-up operation (closing files and streams, releasing system resources, and so
on) that your methods require before the flow of control is transferred to another part of the program.
This is the syntax of the finally block:

finally {
...
/* statements here are executed before control transfers */
...
}

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch10/10-11.html (4 of 4)6/26/2005 7:56:52 PM


file:///F|/books/java%20books/Java%20Bible/ch10/images/10-01.jpg

file:///F|/books/java%20books/Java%20Bible/ch10/images/10-01.jpg6/26/2005 7:56:52 PM
file:///F|/books/java%20books/Java%20Bible/ch10/images/10-02.jpg

file:///F|/books/java%20books/Java%20Bible/ch10/images/10-02.jpg6/26/2005 7:56:52 PM
file:///F|/books/java%20books/Java%20Bible/ch10/images/10-03.jpg

file:///F|/books/java%20books/Java%20Bible/ch10/images/10-03.jpg6/26/2005 7:56:53 PM
Java Bible:Language Fundamentals

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

In the context of our myDivide( ) example, a finally block might look like this:

try {
int y = myDivide(10,0);
} catch (ArithmeticException e) {
System.out.println(“Have caught an ArithmeticException.”);
} catch (MyOwnException e) {
System.out.println(“Have caught MyOwnException.”);
} finally {
System.out.println(“cleaning up...”);
// do any clean-up work here
}

Upon executing the finally block, control is transferred out of the try-catch clause. Typically, whatever
event caused the try statement to terminate (fall-through; the execution of a break, continue, or return
statement; or the propagation of an exception) dictates where the flow of control will resume.

The finally block could also execute a jump statement. This would cause another unconditional control
transfer outside its block, or cause another uncaught exception to be thrown. In either case, the original
jump statement is abandoned, and the new unconditional control transfer (or exception) is processed.

All jump statements (break, continue, return, and throw) transfer control unconditionally.
Whenever one causes control to bypass a finally block, the control transfer pauses while the
finally part is executed, and continues if the finally part finishes normally.

Catch or declare: It’s the law

Java requires that methods either catch or declare all non-runtime exceptions that can be thrown within
the method’s scope. This means that if a method chooses not to catch an exception, it must declare that it
can throw it.

Sometimes, it’s not a good idea to catch exceptions. For example, if you catch an exception deep down

file:///F|/books/java%20books/Java%20Bible/ch10/10-12.html (1 of 3)6/26/2005 7:56:54 PM


Java Bible:Language Fundamentals

in the call stack, you might not know how or why your method is being called. What would you do with
the exception, once caught?

Since you don’t know enough about what caused your method to be called, you might not be able to
adequately handle the exception. In that case, it would be better to pass the exception back down the call
stack: You should declare the exception rather than catch it.

To declare an exception, simply add the throw statement to your method signature, followed by the
exception name. To declare more than one exception, separate each name by a comma.

Suppose, for example, we wanted to define a new method that calls the myDivide( ) method we created
earlier. Instead of implementing an exception handler for myDivide( ) in our new method, we can declare
the potential exceptions in order to pass them down the call stack:

public void myMath() throws ArithmeticException, MyOwnException


{
...
}

Some programmers realize that it takes a lot less time to declare an exception than it does to
write an appropriate exception handler, and are often tempted to simply pass the buck rather
than deal with it. As a general rule, this is a bad idea. However, there are times when it is
appropriate to declare an exception rather than handle it. For a detailed discussion of this topic,
see “Handling Errors Using Exceptions” in the Java Language Tutorial (available on the
JavaSoft Web site at http://java.sun.com/docs/books/tutorial/index.html), specifically the
section named “Runtime Exceptions—The Controversy.”

Finally

In this chapter, as in the last one, we’ve covered the fundamentals of Java programming. Between the
two, we’ve dealt with the “nuts and bolts” of the language. As a programmer, you’ll be using these
elements on a regular basis. Without them, you won’t be able to write Java software.

As with the last chapter, there’s no pressing need to memorize all the material presented here. Simply
return when you need a refresher. With time, you’ll become comfortable with each of the subjects we’ve
covered.

At some point, you may have questions or issues regarding a specific facet or nuance of the language. In
that case, you can always turn to the Java Language Specification. This document covers all aspects of
the language in considerable detail. You can find it on Sun’s JavaSoft Web site: http://java.sun.com/
docs/ books/jls/.

file:///F|/books/java%20books/Java%20Bible/ch10/10-12.html (2 of 3)6/26/2005 7:56:54 PM


Java Bible:Language Fundamentals

Summary

Well, this chapter gave you more of the puzzle pieces you need to start building your own Java
applications. With the knowledge you have gained in this chapter and Chapter 9, you should be well on
your way to creating simple applications using Java. Key points to remember about this chapter include:

• Variables are used to store values in Java. When a value is stored in a variable, you can use it
for a wide range of purposes. One such purpose is to represent an object’s state. Variables are
also used to perform calculations, control the flow of program execution, and effect the overall
state of a program. They are a fundamental part of programming languages; without them we’d
be hard pressed to develop software.
• Any variable that you declare of type byte, short, int, long, float, double, char, or boolean is a
primitive variable. Reference variables are used to store references, or pointers, to objects (which
can be class instances, class instances that implement interfaces, or arrays).
• Expressions are statements that result in a value when executed. When programming, we use
expressions all the time, sometimes without even realizing it. Java expressions are similar in
syntax to those of C and C++.
• The types of operators that can be used in an operation depend on the data type of the operands
involved. For instance, the operators used in an integer operation are different from those used in
a boolean operation.
• In order to direct the flow of program execution, Java supports several control-flow statements.
These are similar to their C and C++ counterparts, so they look and act as you would expect if
you’re already familiar with one (or both) of these languages. Control-flow statements include: if,
switch, while/do, for, and break/continue.
• Java features a general-purpose error processing system known as an exception mechanism.
The exception mechanism is composed of two parts: throwing exceptions and catching them. To
throw an exception means to signal an error, while to catch one is to trap and handle an error that
has been thrown. While new to C programmers, exceptions provide a uniform approach to
signaling and processing errors, removing much of the burden of traditional error processing.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch10/10-12.html (3 of 3)6/26/2005 7:56:54 PM


Java Bible:Classes, Interfaces, and Packages

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

CHAPTER 11
Classes, Interfaces, and Packages
In This Chapter

Creating and using objects in java applications

Implementing methods and interfaces in your java Object classes

Organizing object collections in packages

Adding packages and classes to JAR (Java Archive) files — for easier and faster distribution

In order to write Java programs, must be able to create and manage objects. As you know, objects are
instantiations of classes, which you can think of as the code templates or blueprints for objects.

In this chapter, we get into the nitty-gritty of Java classes. In order to really understand how to create
and use them, we also discuss interfaces. You can think of interfaces as classes whose methods are not
actually implemented. Interfaces allow our Java programs to gain the advantages of multiple inheritance
without becoming weighed down by the complexity that goes along with true multiple inheritance.

Lastly, we see how classes and interfaces can be organized into packages. Packages allow us to group
classes and interfaces together as we see fit, helping to manage what might otherwise become
overwhelming, allowing us to create well-organized repositories of Java code.

Classes

You can think of classes as templates, or blueprints, from which objects are created. As such, we often
think of classes as data types. When objects are created or instantiated from the same class, they are
considered to be of the same type.

file:///F|/books/java%20books/Java%20Bible/ch11/11-01.html (1 of 4)6/26/2005 7:56:55 PM


Java Bible:Classes, Interfaces, and Packages

All objects are an instance of a class. The class that an object is instantiated from determines
the type of that object. If two objects are instantiated from the same class, they are considered
to be of the same type. To find out whether an object is instantiated from a particular class, use
the instanceof operator discussed in the two previous chapters.

When writing Java programs, we use a number of classes that are supplied with the Java development
environment. We might also use classes written by fellow developers, and we will certainly create our
own. In fact, if you’ve been following the examples presented in the preceding chapters, you’ve already
created several classes based on the HelloWorld program introduced in Chapter 5.

In order to create a class, we must declare it and code the body of the class:

class declaration {
...
/* class body (typically variables and methods) */
...
}

Although this is an over-simplified example, it helps us see the two parts of a class implementation
clearly. The class declaration specifies such things as the name of the class, what type of access other
objects will have to it, and what superclasses (and interfaces) it inherits state and behavior from.

However, the real meat of the class is in its body. This is where the specific state and behavior of the
class are defined, through the implementation of variables and methods· Before getting into the class
body, let’s take a closer look at the class declaration.

In Java, only one public class declaration is allowed in each source file (you’ll learn about
public classes later). You can, however, have any number of nonpublic classes in one file.
Although this is technically possible, it’s not recommended. It’s best to create a separate
source file for each class and use the package mechanism, discussed in detail at the end of this
chapter, to organize and use them.

Class Declaration

The class declaration, which is followed by a block of code known as the class body, probably isn’t new
to you at this point. Yet the exact syntax of the class declaration demands another look:

[modifiers] class ClassName [extends superClass] [implements


interfaces]

As you can see, three elements in the class declaration, those in brackets ([]), are optional. You can

file:///F|/books/java%20books/Java%20Bible/ch11/11-01.html (2 of 4)6/26/2005 7:56:55 PM


Java Bible:Classes, Interfaces, and Packages

declare a class by simply providing the keyword class, followed by a name, as shown in the next piece of
code. Here we have declared SimpleClass, an example of the simplest class signature you can declare:

class SimpleClass(){
}

Even so, you’ll need to learn and use each of the optional portions of the declaration in order to get the
most out of Java. Let’s take a look at them individually.

The class name you specify must be a valid identifier (see Chapter 9 for information on Java
identifiers). Although you can begin your class names with a lowercase letter, the convention
is to begin them with a capital letter. Variables, on the other hand, typically begin with a
lowercase letter.

Modifiers

Class modifiers declare whether a class is abstract, final, or public. If an access modifier such as final or
public isn’t specified, the class is abstract,

abstract

The abstract modifier specifies a class that has at least one abstract method in it. An abstract method is
one that has no implementation (see “Abstract classes and methods” later in this chapter for details).

The purpose of having an abstract class is to allow it to declare methods, yet leave them unimplemented.
As such, the subclasses of an abstract class are required to provide implementation for the abstract
methods.

You should declare a class as abstract when you know that its subclasses will implement a certain method
differently. Take, for instance, a method such as draw(). In a drawing program, several of the program’s
classes (such as Circ1e, Rectangle, Triangle, and others) will implement a draw() method, but each will
implement it differently. It makes sense in this case to declare the parent class as abstract, allowing all
subclasses to implement the abstract methods declared in the parent classes they wish:

abstract class MyGraphics {


...
}

In the preceding example, only the class declaration is shown. To be a complete and valid class
implementation, we’d also need to declare at least one abstract method such as draw(). Since we’re
concentrating only on the class declaration here, I’ve omitted the abstract method declaration.

file:///F|/books/java%20books/Java%20Bible/ch11/11-01.html (3 of 4)6/26/2005 7:56:55 PM


Java Bible:Classes, Interfaces, and Packages

If you declare a class as abstract, at least one of the methods in that class must also be abstract.
The compiler kicks out an error message and refuses to compile an abstract class that has no
abstract methods in it.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch11/11-01.html (4 of 4)6/26/2005 7:56:55 PM


Java Bible:Classes, Interfaces, and Packages

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

final

The final modifier specifies a class that can have no subclasses. Declaring a class as final ensures that any
objects instantiated from it are not created from a subclass that might introduce new and inconsistent
properties. Since final classes can’t be subclassed, additional variables and methods can’t be added, and
more importantly, methods can’t be overridden and implemented differently from the way the author of
the class intended.

For example, Java’s String class (see Chapter 12) is a final class. Whenever you use a string, you’re
dealing with an object that is instantiated directly from the String class, as defined in the java.lang
package. As a final class, you can be certain you’re always dealing with objects defined in the String
class, not something that is defined by a subclass of the String class.

To specify a final class, use the keyword final just before the keyword class. For example, the String class
defined in java.lang.String is declared as follows:

public final class String {


...
}

As you can see, the final modifier is preceded by yet another modifier: public. The public modifier,
discussed next, specifies the scope of the String class; it specifies what other objects can access it. The
public and associated modifiers are sometimes called access modifiers; they specify the access for a class.

Since it doesn’t make sense for a class to be both final and abstract, don’t bother trying it!
When a class is abstract, it leaves implementation of certain methods up to its subclasses.
However, because a final class can’t be subclassed, the two can’t coexist. The compiler
generates an error any time an attempt is made to declare a class as both abstract and final.

public

The public modifier specifies that a class can be used by objects outside the current package (see the

file:///F|/books/java%20books/Java%20Bible/ch11/11-02.html (1 of 4)6/26/2005 7:56:55 PM


Java Bible:Classes, Interfaces, and Packages

“Packages” section later in this chapter). By default, when no access modifier is specified, classes can
only be used within the package in which they are declared.

For example, the String class is declared public because other classes and objects outside its package, such
as classes and methods in your programs, need to have access to it. Thus, Java’s String class is declared
as public:

public final class String {


...
}

When specifying a class as public, you should provide the public keyword first in the
declaration, as shown here. If your public classes also happen to be final or abstract, be sure
these words come after public. Although you don’t have to follow this convention, doing so
will make your class declarations consistent with Sun’s and those of your fellow developers.

Superclass

Arguably, the most powerful feature of any object-oriented programming (OOP) language is the ability
to reuse existing code through inheritance. For instance, rather than writing a class from scratch, we can
benefit greatly by inheriting the variables and methods defined in another class that has the basic
properties we require. When we do this, we create what’s known as a subclass of the original class. The
class we inherit from is known as the superclass. This relationship, described in detail in Chapter 2, is
illustrated in Figure 11-1.

Figure 11-1: A subclass descends from a superclass, inheriting the state (variables) and behavior
(methods) of that superclass.

In Java, all classes are descendants of the Object class. The Object class is at the top of the inheritance
tree, or class hierarchy, as illustrated in Figure 11-2. Every other class, either directly or indirectly,
subclasses the Object class. Even those classes at the bottom of the hierarchy are descendants of the
Object class; they subclass any class which, through a long chain of subclasses, can eventually be traced
back to the top of the tree.

file:///F|/books/java%20books/Java%20Bible/ch11/11-02.html (2 of 4)6/26/2005 7:56:55 PM


Java Bible:Classes, Interfaces, and Packages

Figure 11-2: All classes are descendants of the Object class, which sits at the top of the Java class
hierarchy.

If it helps, you can think of the class hierarchy as a family tree for objects, in this sense, Object
is the great, great, great, great, great (well, you get the picture) grandparent of all other objects.
The further down the inheritance tree, or class hierarchy, a class is defined, the more
specialized it is. Classes at the top of the hierarchy are more general, with more specific state
and behavior being added with every subclass.

As you now know, almost any class can be subclassed as long as it’s not specified as final. The process
of subclassing is a natural and powerful feature of Java, allowing your classes to inherit functionality
that you would otherwise have to write yourself.

In order to inherit properties from an existing class, that class must be explicitly specified using the
extends keyword. In Java parlance, our subclass is said to “extend a superclass.” As you’ve seen in earlier
chapters, our applet version of “Hello World!” inherited a great deal of functionality by simply
extending the Applet class:

public class HelloWorldApplet extends java.applet.Applet {


...
}

In this case, we specified java.applet.Applet; the Applet class is defined in the java.applet package. However,
if the Applet class wasn’t part of a package, we would have used the following syntax:

public class HelloWorldApplet extends Applet {


...
}

In this case, the Applet class is expected to reside in the same directory as the HelloWorldApplet class itself.
Since a package wasn’t specified (such as java.applet), the Java compiler doesn’t have a clue where to
look for the superclass. As a result, it expects to find the class inside the same directory as the program
itself.

If you don’t explicitly extend a class, the compiler assumes the superclass to be Object. For instance,
consider the following class declaration, which omits the extends keyword and a superclass altogether:

file:///F|/books/java%20books/Java%20Bible/ch11/11-02.html (3 of 4)6/26/2005 7:56:55 PM


Java Bible:Classes, Interfaces, and Packages

public class MyClassName {


...
}

This is functionally equivalent to:

public class MyClassName extends Object {


...
}

Of course, you don’t have to explicitly extend the Object class as just shown. The compiler does it for
you whenever you leave the “extends” portion blank in a class declaration.

Classes and interfaces

In addition to specifying a superclass, you can specify one or more interfaces in your class declaration.
An interface, discussed in more detail later in this chapter, declares a set of constants and methods but
doesn’t actually implement any of the methods. Similar to an abstract class, an interface requires other
classes to provide the implementation for its methods; it does not provide them itself.

However, with an abstract class, only one of the methods in it is required to be abstract. The remaining
methods can be fully functional, meaning your class inherits the functionality of all methods except the
ones defined as abstract. With an interface, none of the methods are implemented, leaving this
responsibility up to the classes that use it.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch11/11-02.html (4 of 4)6/26/2005 7:56:55 PM


Java Bible:Classes, Interfaces, and Packages

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

When a class implements an interface, it must provide implementations for all of the methods declared
in that interface. And, unlike the act of subclassing an abstract class, a class can implement any number
of interfaces. In other words, Java supports only single inheritance (meaning you can’t subclass more
than one class), whereas you can implement any number of interfaces to achieve a result similar to the
multiple inheritance found in C++.

To implement an interface, declare your class as usual with the keyword implements followed by the
name of the interface. The implements clause should come after the extends clause, if one exists, or
immediately following the class name otherwise:

class Triangle extends MyGraphics implements Brushes {


...
/* each method declared in Brushes must be implemented here */
...
}

The preceding example illustrates the declaration of a class named Triang1e, which is a subclass of
MyGraphics, and implements the Brushes interface. Since Triangle specifies the use of the Brushes interface,
it must also override and implement each of the methods declared in that interface.

Following is the same example, this time without explicitly specifying a superclass:

class Triangle implements Brushes {


...
/* each method declared in Brushes must be implemented here */
...
}

In this case, Triangle is a direct descendant of the Object class; it is said to be a subclass of Object.
However, it specifies the same interface and so must provide the implementation for each of Brushes’
methods.

In the case of multiple interfaces, a comma is used to separate the names of the interfaces:

file:///F|/books/java%20books/Java%20Bible/ch11/11-03.html (1 of 4)6/26/2005 7:56:56 PM


Java Bible:Classes, Interfaces, and Packages

class Triangle implements Brushes, Paints, Surfaces {


...
/* every method in Brushes, Paints, and Surfaces must
be implemented in Triangle */
...
}

And, just as with a single interface, the Triangle class must implement the methods of each one it
specifies. In this case, Triangle must implement all the methods declared in Brushes, Paints, and Surfaces.

For a hands-on example of using interfaces, see the “LivingLinks Software Developers Kit”
provided on the CD-ROM. LivingLinks is a multipurpose animation applet that supports
special-effects plug-ins. To create your own LivingLinks special-effects plug-ins, you must
also use the “Effect” interface provided with the SDK. This ensures that each plug-in
implements the methods required by the LivingLinks applet. Check out the various
LivingLinks special-effects source-code examples provided on disc to see how easy it is to use
interfaces.

Class Body

So far, we’ve only discussed the class declaration. However, the real meat of a class is found in its body.
It is here that the variables and methods of a class are declared and defined, bringing it to life with
variables (state) and methods (behavior).

Variables

In Java classes, there are two types of variables:

• Non-member variables: These are not associated with the class (such as local variables used in
methods and variables used as parameters for methods).
• Member variables: These are directly associated with the class and objects made from it.

Non-member variables

Variables that are part of a method parameter list, or that are declared inside a class method, are not
considered member variables (see “Methods” later in this chapter). Although they may be critical to the
object, they aren’t considered part of the object’s formal state.

Member variables

file:///F|/books/java%20books/Java%20Bible/ch11/11-03.html (2 of 4)6/26/2005 7:56:56 PM


Java Bible:Classes, Interfaces, and Packages

All member variables are declared within the body of the class, not inside a method or as a parameter to
a method. Member variables come in two flavors:

• Class variables
• Instance variables

Following is a summary of the possible member variable declarations (items in square brackets are
optional):

[accessSpecifier] [static] [final] [transient] [volatile] type


variablename

Transient is meant to specify variables that are not part of the persistent state of the class, it is
used to indicate a field that is not part of an object’s persistent state and needs to be serialized
with the object. Volatile specifies a variable whose value is vulnerable to thread access (and is
therefore read from memory each time it is used, and stored to memory after each occasion, to
ensure data integrity. (See Chapter 14 for information about threads.)

The keyword that has the most significant impact on the behavior of variables is static, which specifies
that a variable is either a class variable or an instance variable.

Access Control

Java supports five levels of access for variables and methods:

• Private
• Private protected
• Protected
• Public
• Friendly (if left unspecified)

Table 11-1 gives a breakdown of the access level each specifier provides.

A check mark in the first column indicates that the class in which the variable or method is declared has
access to use the variable or call the method.

A check mark in the second column indicates that subclasses of the class (regardless of which package
they are in) have access to the variable or method.

A check mark in the third column indicates that classes in the same package (regardless of their

file:///F|/books/java%20books/Java%20Bible/ch11/11-03.html (3 of 4)6/26/2005 7:56:56 PM


Java Bible:Classes, Interfaces, and Packages

parentage) as the class in which the variable or method is declared have access.

A check mark in the fourth column indicates that all classes have access to the variable or method.

For an example of each specifier, as applied to both variables and methods, refer to the Java Language
Tutorial (specifically, “Controlling Access to a Class’s Variables” and “Controlling Access to a Class’s
Methods,” both of which are under the section entitled “Creating Your Own Class”). This step-by-step
guide to learning the Java language is available on Sun’s Java Web site: http://sun.java.com.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch11/11-03.html (4 of 4)6/26/2005 7:56:56 PM


file:///F|/books/java%20books/Java%20Bible/ch11/images/11-01.jpg

file:///F|/books/java%20books/Java%20Bible/ch11/images/11-01.jpg6/26/2005 7:56:56 PM
file:///F|/books/java%20books/Java%20Bible/ch11/images/11-02.jpg

file:///F|/books/java%20books/Java%20Bible/ch11/images/11-02.jpg6/26/2005 7:56:56 PM
Java Bible:Classes, Interfaces, and Packages

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Table 11-1
Variable and Method Access Specifiers

Specifier Class Subclass Package World

private ü ü ü ü

private protected ü ü ü ü

protected ü ü ü ü

public ü ü ü ü

<blank> (“friendly”) ü ü ü ü

For details on controlling access to member variables, be sure to read the previous sidebar entitled
“Access Control” before moving on to methods. In the meantime, we’ll focus on the difference between
class variables and instance variables.

Class variables occur only once per class, no matter how many instances of that class are created.
Memory for class variables is allocated by the Java runtime system the first time a class is encountered,
and only then.

In contrast, instance variables are allocated once for every instance of a class. Whenever an instance of a
class is created, the system allocates memory for all instance variables in that class. In essence, class
variables are shared by all instances of a class while each object gets its own copy of instance variables.
So, how are class variables distinguished from instance variables? With the keyword static, as the
following example illustrates:

file:///F|/books/java%20books/Java%20Bible/ch11/11-04.html (1 of 3)6/26/2005 7:56:57 PM


Java Bible:Classes, Interfaces, and Packages

class Bogus {
static int myClassVar; // declare class variable of type int
int myInstanceVar; // declare instance variable of type int
...
/*Method Declarations would follow... */
...
}

When the keyword static precedes the data type in a variable declaration, that variable becomes a class
variable. In this example, memory for myClassVar is allocated only once, regardless of how many
instances of class Bogus are created. In contrast, myInstanceVar is created anew each time an instance of
Bogus is created.

As a result, the variable myClassVar is the same, no matter what object of type Bogus accesses it. For
example, suppose the value 3 were stored in myClassVar. Every time this variable was retrieved,
regardless of when or how, it would contain 3 in all cases (at least until a value other than 3 was stored
in it). When a class variable is altered (that is, changing myClassVar to 15), all instances of that class see
the change, it can be said that all instances of a particular class share the same class variables.

Since all the instances of a particular class share the static variables that are declared in that class, these
variables can be referenced directly without requiring that an object first be instantiated. For example, to
access the static variable declared in our Bogus class, we can simply do the following:

int i = Bogus.myClassVar; // set i equal to the class variable

As you can see, we’ve accessed the class variable directly and assigned it to i without first having to
instantiate a Bogus object using the new operator. While this may seem new to you, in truth we’ve been
dealing with class variables all along. Remember outputting data via System.out.println()? Since out is a
static variable declared in the System class, we don’t have to bother creating an instance of that class
before accessing this variable. Instead, we conveniently access the out class variable directly.

System’s out class variable is a PrintStrearm object, which implements the println() method. All
along we’ve been invoking this method, without concern for exactly what it is or how it does
what it does. To learn more about the System class, its out class variable, and PrintStreams, see
Chapter 13.

In contrast, because a new myInstanceVar variable is created with each instantiation, each Bogus object has
its own copy. This means the value of myInstanceVar is different from object to object; each has its own
copy of the variable, unlike myClassVar, which is shared by all. You have to access an instance variable
through an instance of the class:

file:///F|/books/java%20books/Java%20Bible/ch11/11-04.html (2 of 3)6/26/2005 7:56:57 PM


Java Bible:Classes, Interfaces, and Packages

Bogus freshBogus = new Bogus(); // create an instance of Bogus


// set i equal to an instance variable:
int i = freshBogus.myInstanceVar;

Here we’ve created a Bogus object, through which we access the instance variable myInstanceVar. In this
case, the instance variable was available directly. In some cases, however, instance variables may be
declared private. If this is the case, the only way to access them is through an object’s methods. Such
data hiding is vital to an object-oriented language such as Java, as it prevents direct access to the internal
representation of an object and enforces a “black box” approach to software development (see Chapter 2
for details).

Constant variables (final variables)

Regardless of whether a variable is a class or instance variable, it can also be declared as final. A
variable that has been declared as final can never be changed once a value is assigned to it. You can
think of final variables as constants: Once they’re set, they can’t be altered. As such, they can be used
like #define statements are in C/C++. (Remember, Java doesn’t support #define statements, so this is the
closest you’ll get!) Attempting to alter the value of a final variable is illegal, and invokes an error
message from the compiler.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch11/11-04.html (3 of 3)6/26/2005 7:56:57 PM


Java Bible:Classes, Interfaces, and Packages

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

If we did this with the two lines of code in HighNoon that reference the SHERIFF variable, the output of
the program would be radically different. Rather than comparing numbers to 100, as SHERIFF is defined
in HighNoon, they would be compared to 60000, as defined in ShowDown. As a result, all the numbers
would pass the test, as shown in Figure 11-4.

Figure 11-4: Using the super keyword allows you to access variables and methods that reside in the
superclass.

Methods

Variables are used to maintain an object’s state; methods provide the behavior. For those of you who are
new to object-oriented programming, you can think of a method as a function. However, unlike
procedural programming where functions sit out in the open (or, more accurately, are organized into
files) to be called upon at any point, a method is encapsulated inside the class in which it is defined,
along with the variables of that class.

In Java, every method must reside inside a class declaration. If you create a method outside the
body of a class declaration, the code will not compile.

Together, a class’s variables and methods give objects their state and behavior. The bulk of Java
programming is spent creating methods, just as the bulk of most software implementation efforts is spent
writing functions. It’s these code routines that really form the meat of a program, with variables (data)
being used to keep track of state.

Declaring methods

To create a method you must write a method declaration and then implement the body of it. At the least,

file:///F|/books/java%20books/Java%20Bible/ch11/11-07.html (1 of 5)6/26/2005 7:56:58 PM


Java Bible:Classes, Interfaces, and Packages

a method is made up of

• A return type
• The method name
• A method body

You can see these three elements in this code:

returnType name() {
...
/* method body */
...
}

The preceding example is a simple skeleton of a method declaration, which has many optional parts. In
the following method declaration summary, each of the items in square brackets is optional:

[accessSpecifier] [static] [abstract] [final] [native]


[synchronized] returnValue methodname ([paramlist]) [throws
exceptionsList]

At a minimum, a method declaration must include a return type and a name for the method.
Beyond that, each option allows you to control how your method will act and to what extent it
may be used. As with variables, Java supports five distinct access levels for methods (see the
“Access Control” sidebar earlier in this chapter, for details).

As you’ve seen in our HighNoon example, the return type specified in the method declaration doesn’t
have to be an actual data type. In the case where a method does not return a data type, you must specify
void as the return type:

void SizeUp(int dude) { // void specifies method returns no


data
...
}

However, if the method does return a value, you must specify that data type in the method declaration.
Following are several variations of the SizeUp() method, each returning a different data type:

int SizeUp(int dude) { // specifies that method returns an int


...
return (anInt): // an int value must be returned!

file:///F|/books/java%20books/Java%20Bible/ch11/11-07.html (2 of 5)6/26/2005 7:56:58 PM


Java Bible:Classes, Interfaces, and Packages

boolean SizeUp(int dude) { // returns a boolean


...
return (aBoolean); // a boolean value must be returned!
}

double SizeUp(int dude) { // returns a double


...
return (aDouble); // a double value must be returned!
}

String SizeUp(int dude) { // returns a String


...
return (aString); // a String value must be returned!
}

As you can see, when a return type is specified in the method declaration, a value of that data type must
be returned. When a return statement is executed, control transfers out of the method and back to the
caller of that method. Before the transfer of control is complete, the data being returned is placed on the
stack, where the calling method can retrieve it.

Any Java data type can be returned by a method. Data types in the Java language fall into two
categories:

• Primitive types: These comprise a single value and include integer and floatingpoint numbers,
boolean values, and single characters (such as a, b, and c).
• Composite types (also known as reference types): These comprise multiple values and include
classes, interfaces, strings, and arrays.

For instance, if SizeUp() were to return an int data type, a call to it might look something like this:

int x;
x = SizeUp(235); // call SizeUp, set x to whatever it returns

Since the return statement terminates the execution of a method, it is often the last line of code in the
body of a method (although it may occur elsewhere in the body). There follow two ways in which SizeUp
() might return a value:

boolean SizeUp(int dude) {


boolean beenWarned; // declare a variable to hold return value

file:///F|/books/java%20books/Java%20Bible/ch11/11-07.html (3 of 5)6/26/2005 7:56:58 PM


Java Bible:Classes, Interfaces, and Packages

System.out.print(dude + “:”):
if (dude > SHERIFF) {
System.out.print1n(warning);
beenWarned = true; // set variable to true
}
else {
System.out.print1n(welcome);
beenWarned = false; // set variable to false
}
return (beenWarned);
}

In the preceding example, we declared a boolean variable to hold a value which changes, depending on
what happens inside the body of the method that is eventually returned. However, we could have also
used the following technique:

boolean SizeUp(int dude) {


System.out.print(dude + “;”);
if (dude > SHERIFF) {
System.out.print1n(warning);
return (true); // return true
}
else {
System.out.print1n(welcome);
return (false); // return false
}
}

Although these two code snippets are functionally the same, the latter can be contusing to follow since
more than one return statement is present. For ease of reading, it’s best to use a variable to hold and
manipulate the value to be returned, and only use one return statement whenever possible.

Even though a return statement is required if the method declaration specifies a return type, the
value returned doesn’t have to be what you might consider a “valid” value. For instance, when
a string return type is specified, a value of null can be returned. Likewise, zero (0) and
negative values can be returned for integral data types. Although you must return a data type if
one is declared, any value in the legal range for that type is acceptable.

The data type a method returns must match the data type in the method declaration. As a case in point, in
the two examples we are considering the data type declared is a boolean, so we can’t return anything but
a boolean value. To return an int, float, string, or anything other than a boolean would result in a compiler
error.

file:///F|/books/java%20books/Java%20Bible/ch11/11-07.html (4 of 5)6/26/2005 7:56:58 PM


Java Bible:Classes, Interfaces, and Packages

However, when returning an object, that object’s class must either be the same as the class specified in
the method declaration or a subclass of it. If a method returns an interface, the object returned must
implement that interface.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch11/11-07.html (5 of 5)6/26/2005 7:56:58 PM


Java Bible:Classes, Interfaces, and Packages

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

this

Whenever we’re dealing with member variables in the body of a class, we refer to them by name. Take a
Nook at the following code, which declares two classes (ShowDown and HighNoon):

class ShowDown {
final static int SHERIFF = 50000; // constant class variable
}

public class HighNoon extends ShowDown {


int good=20, bad=125, ugly=53256; // a few instance variables
final static int SHERIFF = 100; // constant class variable
static String welcome = “Have a pleasant stay.”; //class
variable
static String warning = “Get outta town!”; //class variable
public static void main (String args[]) {
System.out.println(“It’s a showdown...”);
HighNoon test = new HighNoon(); // instantiate object
test.Encounter(); // invoke Encounter() method
}

void Encounter() {
System.out.println(“Anything greater than ” + SHERIFF +
“ is out.”);
SizeUp(good);
SizeUp(bad);
SizeUp(ugly);
}

void SizeUp(int dude) {


System.out.print(dude + “:”);
if (dude > SHERIFF) { // is it bigger than SHERIFF?
System.out.println(warning); // Yes? Run ’em out of town

file:///F|/books/java%20books/Java%20Bible/ch11/11-06.html (1 of 5)6/26/2005 7:56:58 PM


Java Bible:Classes, Interfaces, and Packages

}
else {
System.out.println(welcome); // No? welcome to
numberville!
}
}
}

In this example, our use of variables is pretty straightforward. We declare them, then use them. Since
we’re only referring to variables within the scope of HighNoon, there’s no problem. Although you might
not realize it, the this variable is implied each time we use a variable. Since this is a reference to the
current instance of an object, HighNoon in this case, we could have explicitly specified so in our code:

class ShowDown {
final static int SHERIFF = 50000; // constant class variable
}

public class HighNoon extends ShowDown {


int good=20, bad=125, ugly=53256; // a few instance variables
final static int SHERIFF = 100; // constant class variable
static String welcome = “Have a pleasant stay.”; /*class
variable */
static String warning = “Get outta town!”; //class variable
public static void main (String args[]) {
System.out.println(“It’s a showdown...”);
HighNoon test = new HighNoon(); // instantiate object
this.test.Encounter(); // invoke Encounter() method
}

void Encounter() {
System.out.println(“Anything greater than ” + this.SHERIFF +
“is out.”);
SizeUp(this.good);
SizeUp(this.bad);
SizeUp(this.ugly);
}

void SizeUp(int dude) {


System.out.print(dude + “:”);
if (dude > this.SHERIFF) / // is it bigger than SHERIFF?
System.out.println(this.warning);/* Yes? Run ’em out
of town! */
}

file:///F|/books/java%20books/Java%20Bible/ch11/11-06.html (2 of 5)6/26/2005 7:56:58 PM


Java Bible:Classes, Interfaces, and Packages

else {
System.out.println(this.welcome); /* No? Welcome to
numberville */
}
}
}

In each of the variable references shown, with the exception of the parameter dude, we’re saying, “Give
me the variable declared in this class.” In either case, the program produces the same results when
executed (see Figure 11-3).

Figure 11-3: The this keyword is used to reference the current object.

Since all variables in a class are implicitly preceded with this, you aren’t required to explicitly
use it in your code. However, feel free to use it to clarify your code when dealing with
shadowed and hidden variables and overridden methods.

The this variable is used to reference an object’s instance variables, or pass the object as a parameter to a
method (more on that later).

Although it’s not necessary to explicitly use this in our example program, it comes in handy when you
need to access a member variable that has been hidden by a method (in other words, when a local
method variable of the same name exists). For example, suppose our Encounter() method were to hide one
(or more) of the member variables:

void Encounter() {
int ugly = 23; //declared here hides member variable of same
name
System.out.println(“Anything greater than ” + this.SHERIFF +
“ is out.”);
SizeUp(good);
SizeUp(bad);
SizeUp(ugly); // >- refers to the “ugly” method variable
declared above!
}

In this case, we need a way to refer to the member variable, as opposed to the one declared inside

file:///F|/books/java%20books/Java%20Bible/ch11/11-06.html (3 of 5)6/26/2005 7:56:58 PM


Java Bible:Classes, Interfaces, and Packages

Encounter(). And thanks to this, we can do that (pardon the play on words):

void Encounter() {
int ugly = 23; // declared in method, hiding member
SizeUp(good);
SizeUp(bad);
SizeUp(this.ugly); // now refers to the member variable!
}

Since this refers to the object, the preceding example uses the member variable instead of the local one
declared in Encounter(). You might recall our MediaHelloWorldpaint() method, which also made use of the
variable this:

public void paint(Graphics g) {


g.drawImage(myImage, horizontal, vertical, this);
super.paint(g);
}

Here we needed to provide the drawImage() method with four parameters: an image, the horizontal and
vertical coordinates, and an ImageObserver object. An ImageObserver object receives information about an
image as it is being constructed, such as when it is being downloaded from the Web. Since our program
didn’t explicitly create an ImageObserver object, we simply passed it a reference to our MediaHelloWorld
class using this. (We were able to pass a reference to MediaHelloWorld because all applets are able to act
as ImageObserver objects — if applets didn’t have this ability, passing this would have caused the
compiler to choke.)

super

Another special Java variable is super, which refers to the parent class, or superclass, of an object. This is
useful in many cases, such as in MediaHelloWorld’s paint() method shown in the previous section. Since
we wanted to pass some of the responsibility for drawing to the MediaHelloWorld’s superclass, we used
the keyword super to invoke that class’s paint() method:

super.paint(g);

While this is an example of using super to invoke methods in an object’s parent class, it’s also helpful
when you need to access a member variable in a superclass that has been shadowed by a variable in the
subclass.

Suppose, for example, that we wanted to use the SHERIFF variable declared in ShowDown rather than the
one declared in HighNoon. All we’d have to do is replace references to SHERIFF or this . SHERIFF with:

file:///F|/books/java%20books/Java%20Bible/ch11/11-06.html (4 of 5)6/26/2005 7:56:58 PM


Java Bible:Classes, Interfaces, and Packages

super. SHERIFF

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch11/11-06.html (5 of 5)6/26/2005 7:56:58 PM


Java Bible:Classes, Interfaces, and Packages

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Overloading methods

When choosing a name for your method, any valid Java identifier will do. However, if you choose the
same name as another method in the class, you’ll have to supply a different parameter list to differentiate
between the two. Having more than one method with the same name is known as method overloading,
and it is permissible only so long as the parameter list for each method is unique.

Suppose we wanted to create a few variations of our SizeUp() method. In C, we’d create a unique name
for each function: SizeUp(), SizeUpArray(), SizeUpCompare(), and so on. In Java, however, we can overload
the SizeUp() method by simply providing a different parameter list for each one:

void SizeUp(int dude) {


...
}

void SizeUp(int dude[]) {


...
}

void SizeUp(int dude, int dude2) {


...
}

Since each of these method declarations has a different set of parameters, they can all be included in the
same class file. When one of them is called, Java checks the type and number of parameters and invokes
the appropriate method.

file:///F|/books/java%20books/Java%20Bible/ch11/11-08.html (1 of 4)6/26/2005 7:56:59 PM


Java Bible:Classes, Interfaces, and Packages

Overloading is not the same as overriding! When overloading a method, you create more than
one method with the same name (each having a distinct parameter list) in a class. When
overriding a method, you create a method in a class that has the same name and parameter list
as a method in the superclass. In this way, the method in the superclass is overridden by the
one in your class. For instance, when we declared a paint() method in our FlexibleMediaHello
program, we were overriding the paint() method declared in its superclass. However, we can
always use the super variable to execute the method in the superclass:

super.paint();

Class and instance methods

Just as there are class variables and instance variables, there are class methods and instance methods. By
default, all methods are instance methods, unless one is specified as a class method using the static
keyword:

static void SizeUp(int dude) {


...
}

As with class variables, class methods are shared by all objects instantiated via that class. And, just as
with class variables, they can be used at any time without first instantiating an object of that class. An
example of this is seen in the Math class, where all variables and methods are declared static. You can use
any of Math’s methods without first creating an object of that class:

int maxOfTwoNumbers = Math.max(x,y); // returns maximum of x


and y
double myRandomNumber = Math.random(); // returns random number
double mySine = Math.sin(45.56); /* returns trigonometric sine
of
the angle passed in */

The Math class is part of the java.lang package, and has a large number of mathematical
methods you may find useful. Before writing your own mathematics methods, check the Math
class first to see if the work has already been done for you.

Aside from this convenience, class methods operate on class variables. In contrast, an instance method
operates on instance variables: When an instance method accesses an instance variable, it is accessing
the one for that particular object. Since each object shares the same class variables, it makes sense to
declare methods as static if they operate on class variables, or have no need to operate on instances of a
class.

file:///F|/books/java%20books/Java%20Bible/ch11/11-08.html (2 of 4)6/26/2005 7:56:59 PM


Java Bible:Classes, Interfaces, and Packages

final methods

The final keyword can be used to declare a final method. Final methods can’t be overridden by
subclasses. If you have a method that should never be overridden, declare it as final:

final void SizeUp(int dude) {


...
}

Method constructors

A constructor is a method that has the same name as the class in which it is declared. The purpose of a
constructor is to provide a way for new objects to be initialized in a special way. If a constructor isn’t
provided, as in the case of HighNoon, an object of that class can still be created. However, we would have
to set the good, bad, and ugly variables manually, if they weren’t already initialized. And we also had to
invoke the Encounter() method explicitly.

If a constructor had been provided, the variables could have been automatically initialized. In fact, a
constructor can even call methods:

HighNoon (int a, int b, int c) {


good = a; // initialize good to value of a
bad = b; // initialize bad to value of b
ugly = c; // initialize ugly to value of c
Encounter(); // now invoke the Encounter() method!
}

Now, rather than having to rely on the internal initialization of these variables, we can provide our own
values when creating a new HighNoon object:

// instantiate using constructor:


HighNoon test = new HighNoon(15, 25, 460);

When our new HighNoon object is created, the constructor is called. Not only are the good, bad, and ugly
instance variables set to the values we specify, but the Encounter() method is automatically invoked,
saving us from doing it explicitly.

Just as with regular methods, constructors can be overloaded. We can create as many constructors as
needed, provided they each have a unique parameter list. And if you ever need to invoke one constructor
from within another, you can do so using the this variable.

file:///F|/books/java%20books/Java%20Bible/ch11/11-08.html (3 of 4)6/26/2005 7:56:59 PM


Java Bible:Classes, Interfaces, and Packages

For example, suppose we create another HighNoon constructor that takes an array as a parameter. Rather
than set the variables and call Encounter() here as well, we can simply invoke the original HighNoon
constructor and let it do all the work:

HighNoon (int dudeArray[]) {


// using “this” to invoke original constructor:
this(dudeArray[0],dudeArray[1],dudeArray[2]);
}

As with standard methods, you can invoke a constructor in the class’s superclass using the
super keyword.

finalize() method

While a constructor method initializes an object, a fina1ize() method may be created that is used to help
optimize the disposing of an object. It is called just before Java’s automatic garbage collection
mechanism reclaims an unused object, allowing your object to close any files or streams it has opened,
and perform similar housekeeping tasks:

finalize() {
...
}

When an object is no longer used, meaning there are no longer references to it, it is marked for garbage
collection. Unfortunately, you have no guarantee of exactly when an object will be garbage collected or
if your finalize() method will ever be called!

As a result, you should only use a finalize() method to optimize the disposing of your object. But you
should never depend on it to be executed, and your programs should never rely on it to work properly.
Use finalize() methods for optimization of your code only, if at all, and you’ll save yourself a great deal of
anxiety—since Java’s garbage collector isn’t guaranteed to invoke this method, mission-critical code
shouldn’t be placed in finalize().

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch11/11-08.html (4 of 4)6/26/2005 7:56:59 PM


file:///F|/books/java%20books/Java%20Bible/ch11/images/11-04.jpg

file:///F|/books/java%20books/Java%20Bible/ch11/images/11-04.jpg6/26/2005 7:57:00 PM
Java Bible:Classes, Interfaces, and Packages

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

It’s interesting to note that you can manually invoke an object’s finalize() method just as you would call
any other method. However, calling this method does not force garbage collection for that object.
Instead, you can force garbage collection for the entire program using this System method:

System.gc( );

You can also invoke the finalize() method for all recently released objects by calling this System method:

System.runFinalization();

These methods are particularly useful if a Java program is being run with the garbage collector disabled.
This is done by invoking an application at the command line with the -noasynchgc flag, as follows:

c> java -noasynchgc ProgramName

Method exceptions

As you learned in the previous chapter, methods can throw exceptions. In order to do so, the method
declaration must list each exception that the method can throw:

public static int myDivide(int x, int y) throws


ArithmeticException {
if (y==0)
throw new ArithmeticException();
else
return (x/y);
}

If more than one exception may be thrown, they are listed one after another and separated by commas.

Abstract classes and methods

file:///F|/books/java%20books/Java%20Bible/ch11/11-09.html (1 of 5)6/26/2005 7:57:00 PM


Java Bible:Classes, Interfaces, and Packages

Java supports both abstract classes and abstract methods, which are similar in nature to interfaces. As
you know from our earlier discussion, interfaces declare a set of constants and methods but don’t
actually implement any of the methods. The class that implements an interface is responsible for
providing the implementation for each of its methods.

With an abstract class, only one of the methods it declares is required to be abstract. The remaining
methods can be fully functional, meaning the subclass inherits the functional methods but must provide
the implementation for those that are abstract. For example, we might have declared our ShowDown class
as abstract, in addition to one or more of the methods in that class, as shown here:

public abstract class ShowDown {


int aVar; // an instance variable
public abstract void Encounter(); // abstract method
public abstract void SizeUp(int dude); // abstract method
void aRegularMethod() { // a standard method, not abstract
... // implementation here...
}
}

In this case, an object of type ShowDown could never be instantiated. As an abstract class, it can only be
subclassed. And whenever subclassed, the two abstract methods, Encounter() and SizeUp(), must be
implemented by the subclass.

An abstract class is a nice intermediate between a standard class and an interface. Since it can actually
implement methods, it is useful when a class must be created that needs to rely on the subclass for the
implementation of one or more methods. Other than containing abstract methods, and the fact that an
object can’t be created directly from them since one or more of the methods are empty, abstract classes
behave like standard classes.

Inner Classes

file:///F|/books/java%20books/Java%20Bible/ch11/11-09.html (2 of 5)6/26/2005 7:57:00 PM


Java Bible:Classes, Interfaces, and Packages

New in the JDK 1.1 is the concept of inner classes. Inner classes are primarily used for
defining simple helper classes, which are intended to be used for a specific function in a
particular place in a Java program. Inner classes are not for use as top-level, general-purpose
classes. With inner classes, you can define these specific-use classes right where they are
utilized—helping to make your application more understandable. There are three different
types of inner classes: nested top-level classes, member classes, and local classes. There is also
a fourth type of inner class—an anonymous class—which is actually an extension of the local
class type. OK, so that’s great. You know the different types of inner classes, but what does it
actually all mean? Well, let’s review each of the inner class types in detail. For even more
information about inner classes, visit the Inner Classes Specification Web page on the JavaSoft
Web site at
http://java.sun.com/ products/jdk/1.1/docs/guide/innerclasses/index.html.

Nested top-level classes and interfaces

A nested class is just what it sounds like—a class within another class. Nested top-level classes must be
declared as static, and they can only be nested within other top-level classes; the same applies. You
define a nested class like this:

public class TopClass {


public static class NestedClass {
...
}
...
}

As you can see, you can now define classes within other classes. Why would you want to do this? Well,
if the nested class is only used within the top class, defining it as a nested class makes it clear that this is
the only place this class is used.

Nested classes can be nested to any depth, which just means that you can keep nesting classes
as many times as you want! Don’t go too crazy with this capability—nesting your classes too
deep can make your code nearly impossible to understand. I recommend that you only nest
classes one level deep, unless you have a compelling reason to do otherwise.

Member classes

Nested classes are defined within top-level classes. Because they are essentially static classes, however,
they really aren’t any different from top-level classes. Member classes are different though, because they
aren’t declared as static. Member classes are truly members of the containing class; they are defined in
the same manner as nested classes, except the static option is omitted. Member classes can be defined as

file:///F|/books/java%20books/Java%20Bible/ch11/11-09.html (3 of 5)6/26/2005 7:57:00 PM


Java Bible:Classes, Interfaces, and Packages

public, protected, or private. Methods of a member class can access the fields or methods of enclosing
classes—even private fields and methods.

There are two important restrictions to remember when using member classes:

• They cannot have the same name as any containing class or package.
• They cannot contain any static fields, members, or classes.

Local classes

Local classes are classes defined within a block of code. They are only visible within the block of code
in which they are defined. Local classes are analogous to local variables—they are defined just where
they are used. There are two important features of local classes:

• They are only visible in the block of code where they have been defined.
• They can use any final local variable or method parameters in the block of code where they are
defined.

The most common use of local classes is with event listeners and the new AWT model found
in the JDK 1.1. I discuss the Abstract Windowing Toolkit in Part IV.

A local class is defined as follows:

public class TopClass {


public void methodA {
class LocalClass {
...
}
...
}
...
}

This is a trivial example of a local class. I have omitted the class bodies for simplicity. As illustrated in
this example, the LocalClass class is only visible within the methodA method. LocalClass can access any
met hods and fields of the TopClass class.

file:///F|/books/java%20books/Java%20Bible/ch11/11-09.html (4 of 5)6/26/2005 7:57:00 PM


Java Bible:Classes, Interfaces, and Packages

Like member classes, local classes cannot contain any static fields, methods, or classes.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch11/11-09.html (5 of 5)6/26/2005 7:57:00 PM


Java Bible:Classes, Interfaces, and Packages

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Anonymous classes

Finally, the last type of inner classes are anonymous classes—a special case of local classes. The main
difference between local and anonymous classes is that anonymous classes are shy—they don’t have any
name. So, how can a class without a name be useful and used? Let’s take a closer look at how an
anonymous class is defined:

class A {
AnonymousClass method1 {
return new AnonymousClass() {
iht i = 0;
public int increment() { return(i++); };
public int decrement() {return(i-); };
};
};
}

In this example, method1 creates and returns the anonymous class—AnonymousClass. Anonymous classes
are created by calling following a class body definition after the new command. In this case, an
anonymous class is created that defines two methods, increment() and decrement().

Another important feature of anonymous classes is their use as instance initializers, which are similar to
static initializers found in the 1.0 JDK. An instance initializer is simply a block of code that is embedded
inside a class definition. Here is an example of an instance initializer:

class A {
// Example of an instance initializer...
int[] array1 = new int[5]; { for(int i=0; i<5; i++)
array1[i] = i * 100; }
}

Instance initializers are executed in the order they appear. They are run after any superclass constructors,
but before the constructor of the current class.

file:///F|/books/java%20books/Java%20Bible/ch11/11-10.html (1 of 4)6/26/2005 7:57:01 PM


Java Bible:Classes, Interfaces, and Packages

When should you use an anonymous class over a local class? Well, if your class fits any of
these descriptions, it might be appropriate:

• Only one instance of the class is ever used.


• The class is used immediately after it’s defined.
• The class is small.
• Naming the class doesn’t make your code easier to understand.

There are four important restrictions to keep in mind when you’re using anonymous classes:

• Anonymous classes can’t have constructors.


• Anonymous classes cannot define any static fields, methods, or classes.
• Anonymous classes cannot be public, private, protected, or static.
• You can only ever create one instance of an anonymous class.

Reflection

Also new to JDK 1.1/1.2 is the reflection API. Reflection allows a Java class to look inside
itself. The java.lang. Class class has been enhanced to include methods that now return the fields,
methods, and constructors defined by a class. The java.lang.reflect package defines the Field,
Method, and Constructor classes that are returned by the reflection methods. Reflection allows
your applications to obtain complete and detailed information about any class during runtime.
The most prevalent use of reflection is with JavaBeans, which is discussed in more detail in
Chapter 28. For further information about class reflection, consult the Reflection Web page on
the JavaSoft Web site at http://java.sun.com/products/jdk/1.1/docs/reflection/index.html.
In JDK 1.2, a Field, Method, or Constructor object may be explicitly flagged as suppressing
default Java language access control. When the reflective object is used, this flag—a new
instance field—is consulted as part of access checking. If the flag is true, access checks are
disabled and the requested operation proceeds; otherwise, normal access checks are performed
as in JDK 1.1. The flag is false by default in a reflected member or constructor. Thus, in JDK
1.2 each concrete reflected class (Field, Method and Constructor) extends a new base class,
AccessibleObject.

Interfaces

file:///F|/books/java%20books/Java%20Bible/ch11/11-10.html (2 of 4)6/26/2005 7:57:01 PM


Java Bible:Classes, Interfaces, and Packages

By this point in the chapter, you’re probably pretty comfortable with the concept of an interface. After
all, you’ve seen how to declare interfaces in a class using the implements keyword. And you’ve seen how
to declare abstract classes and abstract methods, which are similar in nature to an interface.

You might also realize that an interface is an entirely abstract class; not a single method declared in an
interface can be implemented by the interface. All methods in an interface must be implemented by the
class that claims to use them. (Refer to the “Classes and Interfaces” section earlier in this chapter to see
how your classes can claim to use an interface.)

And so it’s time to see how an interface is created. Let’s begin by looking at the declaration syntax for
an interface. Following is the syntax for declaring an interface (items in square brackets are optional):

[public] interface name [extends interface1, interface2, ...] {


...
}

As you can see, an interface can extend any number of other interfaces. And, if you recall, a class can
extend any number of interfaces. This allows for an extremely powerful capability, similar to multiple
inheritance found in C++.

In an interface, all variables are automatically treated as public, static, and final. You can explicitly specify
each, if you want, but it really doesn’t matter. However, you aren’t allowed to use anything other than
public, static, and final variables. If you were to specify a variable as protected, for instance, the compiler
would generate an error.

The same is true for an interface’s methods, which are automatically treated as public and abstract. You
can explicitly declare your interface methods as public and abstract, but it really doesn’t matter since the
system will do it for you automatically. However, just try to specify a private method, and see what the
compiler has to say about it!

Consider for a moment our ShowDown class, rewritten as an interface:

public interface ShowDown {


int SHERIFF = 60000; // all variables are public, static,
final
void Encounter(); // all methods are public and abstract
void SizeUp(int dude); // all methods are public and
abstract
}

You’ll notice that I didn’t bother to declare the constant variable SHERIFF as being final and static, as I did
when ShowDown was implemented as a standard class earlier in this chapter. I didn’t have to because it’s

file:///F|/books/java%20books/Java%20Bible/ch11/11-10.html (3 of 4)6/26/2005 7:57:01 PM


Java Bible:Classes, Interfaces, and Packages

automatically treated as public, static, and fina1 when implemented as an interface. The same goes for
ShowDown’s methods. There’s no need to declare them as public because they already are when
implemented as an interface. And since each method is also abstract, we’re relying on the subclass to do
the implementation—don’t even bother with the body of methods declared in an interface.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch11/11-10.html (4 of 4)6/26/2005 7:57:01 PM


Java Bible:Classes, Interfaces, and Packages

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

We only need to provide the name and parameter list of interface methods. The curly braces ({ }) of the
body block aren’t even needed. In fact, if you included them, the compiler would generate an error,
regardless of whether or not you actually provided code for the body:

void SizeUp(int dude){ // illegal! Can’t include braces!


}

With interfaces, you need to remove the method block entirely and replace it with a semicolon, as
follows:

void SizeUp(int dude); // this is fine

Even though all the variables and methods in an interface are implicitly prefixed with access specifiers
and modifiers, the same is not true with the interface declaration itself. If you don’t specify your
interface as being public, Java doesn’t automatically make it public. Instead, the scope of your interface is
“friendly,” making it available only in the package in which it is created. As a result, you may want to
explicitly declare a package for your interfaces (see the next section, “Packages,” for more details):

package numberville; // make part of numberville package

interface ShowDown { /* not public; making class available


only to the numberville package */
int SHERIFF = 60000;
void Encounter();
void SizeUp(int dude);
}

Since all variables in an interface are automatically considered public, static, and final (whether
or not you supply the keywords yourself), be sure to initialize them. If you don’t, the compiler
tells you to get your act together. Save yourself the embarrassment, and initialize all interface
variables before the compiler has a chance to give off attitude.

file:///F|/books/java%20books/Java%20Bible/ch11/11-11.html (1 of 4)6/26/2005 7:57:01 PM


Java Bible:Classes, Interfaces, and Packages

Packages

After writing a few Java programs and creating a number of classes in the process, you’ll probably find
yourself wanting to reuse some of the classes in new projects. And this is exactly what you’re supposed
to do: Why rewrite when you can reuse?

To make it easier to reuse code and organize classes, Java supports a mechanism called packages.
Packages allow classes to be grouped according to their purpose, much like you might group files inside
a directory on your computer’s hard drive.

Actually, you’re already familiar with packages on a basic level; we’ve been importing them for use
with our HelloWorld programs in previous chapters. However, to really make use of them, we need to
explore packages in more detail. First we’ll learn how to fully use existing packages. Then we’ll see how
to create and manage our own packages.

Although I refer to packages in terms of classes, they can also contain interfaces. Rather than
having to say “classes and interfaces” every time I talk about packages, I’ll simply use the
term classes, with the understanding that interfaces are implied.

Using packages

As you know, packages are used to organize and categorize classes. In fact, the Java Developer’s Kit
(JDK) comes with eight packages that contain the Java Application Programmer’s Interface (API)
classes, and one that contains Sun’s debugging tool classes (see Table 11-2).

Table 11-2
Standard Java Packages

API Packages Description

java.applet Applet classes and interfaces

java.awt Abstract Windowing Toolkit (AWT) classes and interfaces

java.awt.image (Subpackage of AWT) Bitmap image classes and interfaces

java.awt.peer (Subpackage of AWT) Platform-specific AWT classes and interfaces


(such as Windows, Sun, and Macintosh)

file:///F|/books/java%20books/Java%20Bible/ch11/11-11.html (2 of 4)6/26/2005 7:57:01 PM


Java Bible:Classes, Interfaces, and Packages

java.io Input/Output classes and interfaces

java.lang Core Java language classes and interfaces

java.net Network classes and interfaces

java.util Utility classes and interfaces

Other Packages Description

sun.tools.debug Debugging classes and interfaces

At the time this book went to print, the Macintosh JDK did not include a debugger or Sun’s
debugging classes.

Importing packages

There are a few ways to access classes that are in packages. The most basic method is to import a
package in the beginning of your programs, as we did in our FlexibleMediaHello applet. In this case,
you simply provide the import statement(s) before any other code in your program. (It’s okay if they
come after comments and white space such as character returns and linefeeds):

import java.applet.*;
import java.awt.*;
import java.net.URL;
import java.net.MalformedURLException;

As you can see, we have imported four packages (or, more precisely, the public classes of four
packages) using two different techniques. In the first two lines of code, we used the asterisk (*) to
effectively tell the compiler to “Give me access to all of the public classes in this package”:

import java.applet.*; // import all public classes in


java.applet package
import java.awt.*; // import all public classes in java.awt
package

In the second two lines, we explicitly state the name of the public classes to import:

file:///F|/books/java%20books/Java%20Bible/ch11/11-11.html (3 of 4)6/26/2005 7:57:01 PM


Java Bible:Classes, Interfaces, and Packages

// import URL class in the java.net package:


import java.net.URL;
// import MalformedURLException class in the java.net
package:

import java.net.MalformedURLException;

A Note About Importing Public Classes

You can only import the public classes in a package, and only those public classes that are directly part
of that package. You can’t, for example, import the java.awt subpackages, java.awt.image and java.awt.peer,
using the following import statement:

import java.awt.*; // import public classes in java.awt, but not


subpackages!

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch11/11-11.html (4 of 4)6/26/2005 7:57:01 PM


Java Bible:Classes, Interfaces, and Packages

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

This example imports only the public classes that are directly part of the java.awt package. If you want to
import the classes in a subpackage, you have to specify each subpackage explicitly:

import java.awt.image.*; // import public classes in image


subpackage of java.awt
import java.awt.peer.*; // import public classes in peer
subpackage of java.awt

We could just as easily have used the asterisk to import all the classes in the java.net package, instead of
specifying the specific classes, as we just did:

import java.net.*; // import all public classes in the entire


java.net package

Although you might initially think this is excessive, since we only use the URL and
MalformedURLException classes, ifs really not. Even though it seems that the entire java.net class is
imported, in truth, only those classes that are used in the program are imported; Java links in classes
only when they are actually used.

Although I could have used asterisk notation to import all public classes in the java.net package (import
java.net.*), I explicitly specified the URL and MalformedURLException classes to make it clear to the reader
of this program what portions of the java.net package are used. In general, it’s better programming style
to explicitly import the classes you use in a program (as I’ve done with URL and MalformedURLException)
rather than using the asterisk approach. Clearly identifying the classes you import in this way makes it
much easier for others to maintain your code; they won’t have to search through your program to find
out which classes in a package you use.

Any time you want to use a class, you need to import the package it is part of (or reference it explicitly
in your code, as described shortly). However, you don’t need to import the java.lang package; these
classes are fundamental to Java and are automatically imported regardless of whether you explicitly
import them or not.

file:///F|/books/java%20books/Java%20Bible/ch11/11-12.html (1 of 4)6/26/2005 7:57:02 PM


Java Bible:Classes, Interfaces, and Packages

Explicit class references in imported packages

Once a package has been imported, the public classes in it can be used as often as desired in your code.
This is all well and good, but what if you only need to use a class once? In this case, you can explicitly
reference the class, without having to import the package it is part of. For example, suppose we didn’t
want to bother importing the URL class in our earlier example. If we precede all references to URL with
the java.net package, we wouldn’t have to:

java.net.URL imageURL=null; // explicitly reference to declare


variable...
try {
imageURL = new java.net.URL(imageString); // and once again
in the code
} catch (MalformedURLException e) { ; }

Since we’ve explicitly specified the java.net package immediately before the URL class name, Java knows
exactly what package the URL class is part of. And, as a result, we don’t have to import the java.net
package at all. Contrast the preceding code snippet with how it was written originally:

import java.net.URL; // import the URL class


URL imageURL=null;
try {
imageURL = new URL(imageString);
} catch (MalformedURLException e) { ; }

If it weren’t for the fact that the URL class name is pretty descriptive, we wouldn’t have any idea where
it comes from just looking at the implementation: You can’t tell that URL is part of the java.net package
by merely looking at the code. This is a downside to importing packages; you can’t easily see where a
class is coming from by looking at the code alone. Instead, you have to have an understanding of what
classes are in each package and make an educated guess whenever a class name appears in code.

Unless you have a large number of references to a particular class in a program, it’s often more helpful
to precede the class with its package rather than import that package. In fact, our FlexibleMediaHello
program would be more readable in general if we discarded all of the import statements and explicitly
referenced the entire package each time a class is used. However, there is a trade-off between readability
and ease of coding. It’s much easier to simply type “URL” than it is to type “java.net.URL.” As result,
you may prefer to import packages, rather than reference them explicitly.

Naming conflicts

One of the main benefits of explicitly referencing packages, apart from the clarity of code produced as a

file:///F|/books/java%20books/Java%20Bible/ch11/11-12.html (2 of 4)6/26/2005 7:57:02 PM


Java Bible:Classes, Interfaces, and Packages

result, is the fact that class names won’t conflict, as they could when using an import statement. At some
point, you’re going to create a class with the same name as one that exists in another class. For example,
how many understandable yet unique identifiers can you come up with for a Sort class?

Suppose, for a moment, that your Sort class is part of a package called uti1ityPackage. Now, what if you
imported that package and another one that happens to also have a class named Sort?

import utilityPackage; // contains your Sort class


import anyOtherPackage; // also contains a Sort class
Sort mySort = new Sort(); // which Sort class is instantiated?

As you can see, we’ve got a problem here. Which Sort class is instantiated when this code is executed?
Since that can’t be determined, the compiler kicks out an error and refuses to compile the code. You can
avoid this, however, by using an explicit class reference directly in the code:

utilityPackage.Sort mySort = new utilityPackage.Sort();

Here we resolved any potential conflict by explicitly declaring the package name along with the class.
There will be no confusion to a person reading your code, or when the compiler tries to create a Sort
object. It’s clear just by looking at the code that the object we’re talking about comes from uti1ityPackage.

Package levels

Package names are arranged in levels, with each level separated from the next with a period. Consider,
for example, the java.applet package. It’s comprised of two levels: The first level is java and the second is
applet. The java.awt.image package, on the other hand, is made up of three levels, with image being the
third level.

When you create your own packages, it’s up to you to decide upon the names and number of levels.
However, creating your own package isn’t as simple as merely dreaming up a nifty package name.
Packages are directly related to the directory structure containing the classes they’re composed
of—when you create your own packages, you do so based on the directory layout containing the classes
to be included in these packages.

Creating packages

It’s easy to create your own packages, something you’ll almost certainly want to do at some time or
another. To create a package (that is, to add a class to a package), simply use the following statement as
the first line of code in your source code file:

package packageName;

file:///F|/books/java%20books/Java%20Bible/ch11/11-12.html (3 of 4)6/26/2005 7:57:02 PM


Java Bible:Classes, Interfaces, and Packages

Suppose, for example, we wanted to create a new package called numbervi1le to organize all the classes
that might be used to simulate a bunch of numbers living together in harmony. (Hey, even numbers need
a home!) We could easily do this by placing the following statement in every class file that we wanted to
be part of the package:

package numberville;

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch11/11-12.html (4 of 4)6/26/2005 7:57:02 PM


Java Bible:Classes, Interfaces, and Packages

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

For instance, our ShowDown superclass would look like this:

package numberville; // make ShowDown part of numberville package


class ShowDown {
...
}

The HighNoon class file would look like this:

package numberville; // make HighNoon part of numberville package


public class HighNoon extends ShowDown {

... /* member variables */


void Encounter() {
...
}

void SizeUp(int dude) {


...
}
}

Now, whenever we need to use the HighNoon or ShowDown classes, we need only import the numberville
package or explicitly specify it when creating a HighNoon or ShowDown object. Furthermore, we could
continue to create classes that operate on numbers, as these two classes do, and easily add them to the
numberville package using only one line of code:

package numberville; // make this class part of numberville


package

file:///F|/books/java%20books/Java%20Bible/ch11/11-13.html (1 of 4)6/26/2005 7:57:02 PM


Java Bible:Classes, Interfaces, and Packages

Be sure to place your package statements first, before all other statements in your program. A
package statement should come before all other code, including import statements.

Unique names

The naming convention used when creating packages is designed to provide unique packages that can be
made universally available without causing a name conflict. Any packages that you create, and that will
be made available outside your organization, should use your organization’s Internet domain name in
reverse order to ensure a unique name.

For example, if I wanted to make an animation package available to the world, I’d use my company’s
mantiscorp.com domain name in reverse when creating the package:

COM.mantiscorp.animation: // this package is unique

As you can see, the first portion of a unique name must be in uppercase letters. The remainder of the
name should be in lowercase letters, with only the classes having a capital letter. For example, suppose
we needed to specify a Sprite class in the previous package:

COM.mantiscorp.animation.Sprite;

Due to the naming convention of unique packages, we can immediately tell that animation comes from
the mantiscorp.com domain. And since only classes begin with a capital letter (with the exception of the
first level in a unique name, in which all letters are capitalized), we know right off the bat that Sprite is a
class and not another level of the package.

JAR Files

Just as you can use a glass jar to can your tomatoes and peaches, you can use JAR (Java
Archive) files to can your Java packages. JAR files store Java packages, classes, and resources
in a compressed form. It takes time to download information over the Internet, so if you can
cram more information into less space, things will run faster. When adding applets to your
HTML files, you use the <ARCHIVE> tag to specify a JAR file. A more complete discussion on
the <ARCHIVE> tag and adding Java applets to your HTML can be found in Chapter 17. For
now, I review how to create JAR files.

If you’ve used any file-zipping utility, you should feel quite at home when creating JAR files. You use
the jar.exe tool to create a JAR file. If you want to create one that contains the COM.mantiscorp.animation
package, simply execute this command from the directory that contains the package:

file:///F|/books/java%20books/Java%20Bible/ch11/11-13.html (2 of 4)6/26/2005 7:57:02 PM


Java Bible:Classes, Interfaces, and Packages

jar cvf mantiscorp *

The * causes all the files in the current directory to be added to the JAR file. The c, v, and f are
command-line options, and they are detailed in Table 11-3.

Table 11-3
JAR Tool Command-Line Options

Option Description

c Creates a new or empty archive.

T Lists the contents of the JAR file.

x [file] Extracts all files, or just the filenames specified.

f [jar-file] Specifies the name of the JAR file to work with. Without the f option, output will
be sent to standard output.

V Generates verbose output.

Summary

This chapter introduced the concept of creating and using objects in your Java applications. This is the
final big puzzle piece required to start developing your own Java applications. The upcoming chapters
will continue to take a closer look at fundamentals required to develop your own Java applications. Key
concepts to remember about this chapter include:

• Classes are templates, or blueprints, from which objects are created. As such, we often think of
classes as data types. When objects are created or instantiated from the same class, they are
considered to be of the same type. All objects are an instance of a class. The class that an object
is instantiated from determines the type of that object. If two objects are instantiated from the
same class, they are considered to be of the same type.
• All member variables are declared within the body of the class, not inside a method or as a
parameter to a method. They are used to maintain the state of an object.
• While variables are used to maintain an object’s state, methods provide the behavior. For those
of you who are new to object-oriented programming, you can think of a method as a function.

file:///F|/books/java%20books/Java%20Bible/ch11/11-13.html (3 of 4)6/26/2005 7:57:02 PM


Java Bible:Classes, Interfaces, and Packages

However, unlike procedural programming where functions sit out in the open (or, more
accurately, are organized into files) to be called upon at any point, a method is encapsulated
inside the class in which it is defined, along with the variables of that class.
• An interface is an entirely abstract class; not a single method declared in an interface can be
implemented by the interface. Ail methods in an interface must be implemented by the class that
claims to use them.
• To make it easier to reuse code and organize classes, Java supports a mechanism called
packages. Packages allow classes to be grouped according to their purpose, much like you might
group files inside a directory on your computer hard drive.
• It’s easy to create your own packages, something you’ll almost certainly want to do at some
time or another. To create a package (that is, to add a class to a package), simply use the package
statement as the first line of code in your source code file.
• JAR files store Java packages, classes, and resources in a compressed form. It takes time to
download information over the Internet, so if you can cram more information into less space,
things will run faster. When adding applets to your HTML files, you use the <ARCHIVE> tag to
specify a JAR file.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch11/11-13.html (4 of 4)6/26/2005 7:57:02 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

CHAPTER 12
Strings and Arrays
In This Chapter

Adding strings to your Java applications

Understanding arrays

Using the Java utility classes

By now you know that in Java strings aren’t merely arrays of characters; they’re first-class objects
(meaning they can’t be subclassed). In fact, Java offers two classes for dealing with strings: String and
StringBuffer.

In this chapter, we’ll learn about the String and StringBuffer classes, and find out what it means to be a
first-class object. We’ll also take a closer look at arrays, which are also first-class objects, and their
loosely related relatives, Vector and Hashtable.

As you’ll soon see, Java provides several ways to store, retrieve, and utilize data. In the next chapter,
we’ll take a look at streams, which give us an abstract ability to read and write to a flowing buffer of
data. However, streams are often overkill for many programming tasks, and so we need to look at easier
ways of storing and retrieving data.

With the String and StringBuffer classes, we can create objects that utilize character data. With arrays, we
can store and retrieve any type of data we’d like in each element, even other arrays. However, since we
create arrays with an explicit dimension, there’s no way of extending their size when we run out of
elements. As a result, we turn to the Vector class, which provides us with growable arrays.

Once the concept of arrays has been covered in detail, we’ll take a look at the Hashtable class. Here, we’ll
see how to create objects in which we can store values that are retrieved through a key, rather than an
index. In addition, we’ll see how the Stack class extends Hashtable to implement this familiar data

file:///F|/books/java%20books/Java%20Bible/ch12/12-01.html (1 of 8)6/26/2005 7:57:03 PM


Java Bible:Strings and Arrays

structure.

And, since Vector, Hashtable, and Stack are all part of the java.util package, we’ll take this opportunity to
explore that package as well. We’ll see how out strings can be tokenized using StringTokenizer, allowing
us to break these objects into their discrete pieces. Finally, we’ll look at the purely utilitarian classes
found in this package, specifically Date, Calendar, TimeZone, Random, and the ResourceBundle classes.

But, before we get too far ahead of ourselves, let’s pull back and take a closer look at the String and
StringBuffer classes.

Strings (Java.lang.String)

As we learned in Chapter 7, Java strings aren’t like the ones we’re accustomed to in C and C++. In those
languages, strings are simply a null-terminated array of characters. Java strings, however, are actually
objects defined by the String class. As a result, they feature a number of methods that are used to access
(and, in the case of StringBuffer objects, manipulate) their contents.

Additionally, bounds checking is performed on Java strings at both compile and runtime. If we attempt
to access portions of a string outside the legal bounds, an exception is thrown, which we can catch and
handle (see Chapter 10 for details on exceptions).

C and C++ strings, in contrast, don’t support such well-defined behavior. In these languages, it’s quite
easy to overrun the boundaries of the array in which our characters are stored. Sometimes, the error is
immediately apparent, sometimes it’s not.

At best, we manage to identify the problem early in the development cycle and fix it. At worst, the
problem slips through our bug-hunting efforts and makes its way to the customer and surfaces
sporadically, perhaps causing the program to behave unexpectedly, or even crash.

Since the program’s behavior is normal for the most part, it can be difficult to track down and eliminate
the programming error. Often, the problem can be traced to an improper use of strings, such as
overshooting the string array boundary and accessing data in memory, rather than the contents of the
array.

Since no error checking is performed with C/C++ strings, we’re free to go right past the end of the array.
Of course, we don’t do this intentionally, but it tends to happen from time to time. Unfortunately, the
result is often a slippery bug that doesn’t rear its ugly-buggish head consistently. Such errors are
extremely tough to track down.

Java strings are first-class objects

file:///F|/books/java%20books/Java%20Bible/ch12/12-01.html (2 of 8)6/26/2005 7:57:03 PM


Java Bible:Strings and Arrays

With Java, strings are first-class objects that support a well-defined set of methods, as shown in Table
12-1. Using these methods, out relationship with strings becomes one of trust and reliance, as opposed to
the paranoia C and C++ programmers sometimes develop after a few bad string experiences.

Table 12-1
java.lang.String

Constructor Signature Description

String public String() Constructs a new, empty string.

Constructs a new string that is a copy of


String public String (String value)
the specified string.

Constructs a new string whose initial


String public String (Char value)
value is the specified array of characters.

Constructs a new string whose initial


value is the specified subarray of
String public String (char value[], int offset, int count) characters. The length of the string will
be count characters, beginning at offset
within the specified character array.

Constructs a new string whose initial


value is the specified subarray of bytes.
public String (byte ascii[], int hibyte, int offset, int
count) count characters starting at offset within the
The high-byte of each character can be
String
string specified, although it is usually 0. The
length of the string will be the specified
character array.

Constructs a new string whose value is


the specified array of bytes. The byte
String public String (byte[] ascii, int hibyte) array will be transformed into Unicode
chars using hibyte as the upper byte of
each character.

file:///F|/books/java%20books/Java%20Bible/ch12/12-01.html (3 of 8)6/26/2005 7:57:03 PM


Java Bible:Strings and Arrays

Constructs a new string whose value is


String public String (StringBuffer buffer) the current contents of the given string
buffer.

Returns the length of the string. The


length of the string is equal to the
length public int length()
number of 16-bit Unicode characters in
it.

Returns the character at the specified


charAt public char charAt(int index) index (index values range from 0 to length
() - 1).

Copies characters from this string into


the specified character array. The
public void getChars(int scrBegin, int scrEnd, char characters of the substring (as defined by
getChars
dst[], int dstBegin) scrBegin and scrEnd) are copied into the
array, starting at the array’s dstBegin
location.

Copies characters from this string into


the specified byte array. Copies the
public void getBytes(int srcBegin, int srcEnd, byte
getBytes characters of the substring (as defined by
dst[], int dstBegin)
scrBegin and scrEnd) into the byte array
starting at array’s dstBegin location.

Compares this string to the specified


object. Returns true if they are equal
equals public boolean equals(Object anObject)
(have the same length and the same
characters in the same sequence).

Compares this string to another object.


Returns true if the object is equal to this
string; that is, has the same length and
equals public boolean equalsIgnoreCase (String
the same characters in the same
IgnoreCase anotherString)
sequence. Uppercase characters are
folded to lowercase before they are
compared.

file:///F|/books/java%20books/Java%20Bible/ch12/12-01.html (4 of 8)6/26/2005 7:57:03 PM


Java Bible:Strings and Arrays

Compares this string to another specified


string. Returns an integer that is less
than, equal to, or greater than zero. The
compareTo public int compareTo (String anotherString)
integer’s value depends on whether this
string is less than, equal to, or greater
than the anotherString.

Determines whether a region of this


public boolean regionMatches (int toffset, String
regionMatches string matches the specified region of the
other, int ooffset, int len)
specified string.

Determines whether a region of this


string matches the specified region of the
public boolean regionMatches (boolean ignoreCase, specified string. If the boolean ignoreCase
regionMatches
int toffset, String other, int ooffset, int len) is true, uppercase characters are
considered equivalent to lowercase
letters.

Determines whether this string starts


startsWith public boolean startsWith (String prefix, int toffset)
with some prefix, starting at toffset.

Determines whether this string starts


startsWith public boolean startsWith (String prefix)
with some prefix.

Determines whether the string ends with


endsWith public boolean endsWith(String suffix)
some suffix.

Returns a hash code for this string. This


hashCode public int hashCode() is a large number composed of the
character values in the string.

Returns the index within this string of


the first occurrence of the specified
indexOf public int indexOf(int ch)
character. This method returns - 1 if the
index is not found.

file:///F|/books/java%20books/Java%20Bible/ch12/12-01.html (5 of 8)6/26/2005 7:57:03 PM


Java Bible:Strings and Arrays

Returns the index within this string of


the first occurrence of the specified
indexOf public int indexOf(int ch, int fromIndex) character, starting the search at
fromIndex. This method returns - 1 if the
index is not found.

Returns the index within this string of


the last occurrence of the specified
character. The string is searched
lastIndexOf public int LastIndexOf(int ch)
backwards, starting at the last character.
This method returns - 1 if the index is
not found.

Returns the index within this string of


the last occurrence of the specified
character. The string is searched
lastIndexOf public int lastIndexOf(int ch, int fromIndex)
backwards, starting at fromIndex. This
method returns - 1 if the index is not
found.

Returns the substring of this string. The


public String substring(int beginIndex, int
substring substring is specified by a beginIndex
endIndex)
(inclusive) and the end of the string.

Converts this string by replacing all


replace public String replace(char oldChar, char newChar)
occurrences of old String with newString).

Converts all the characters in this string


toLowerCase public String toLowerCase()
to lowercase.

Converts all the characters in this string


toupperCase public String to upperCase()
to uppercase.

Trims leading and trailing white space


trim public String trim()
from this string.

Converts a character array to a String


toString public String toString()
object.

file:///F|/books/java%20books/Java%20Bible/ch12/12-01.html (6 of 8)6/26/2005 7:57:03 PM


Java Bible:Strings and Arrays

Converts this String object into a


toCharArray public char[] toCharArray(
character array.

Returns a string that represents the string


value of the object. The object may
valueOf public static String valueOf (Object obj)
choose how to represent itself by
implementing the toString method.

Returns a string that is equivalent to the


specified character array. Uses the
valueOf public static String valueOf (char data[]) original array as the body of the string
(in other words, it doesn’t copy it to a
new array).

public static String valueOf (char data[], int offset, Returns a string that is equivalent to the
valueOf
int count) specified character array.

Returns a string that is equivalent to the


public static String copyValueOf (char data[], int specified character array. It creates a
copyValueOf
offset, int count) new array and copies the characters into
it.

Returns a string that is equivalent to the


specified character array. It creates a
copyValueOf public static String copyValueOf (char data[])
new array and copies the characters into
it.

Returns a String object that represents the


valueOf public static String valueOf (boolean b)
state of the specified boolean.

Returns a String object that contains a


valueOf public static String valueOf (char c)
single character.

Returns a String object that represents the


valueOf public static String vatueOf (int I)
value of the specified int.

Returns a String object that represents the


valueOf public static String valueOf (long 1)
value of the specified long.

file:///F|/books/java%20books/Java%20Bible/ch12/12-01.html (7 of 8)6/26/2005 7:57:03 PM


Java Bible:Strings and Arrays

Returns a String object that represents the


valueOf public static String valueOf (float f)
value of the specified float.

Returns a String object that represents the


valueOf public static String valueOf (double d)
value of the specified double.

Returns a string that is equal to this


intern public String Intern() string. but is guaranteed to be from the
unique string pool

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-01.html (8 of 8)6/26/2005 7:57:03 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

With first-class objects, you can only use the String class to create new String objects, as we’ve been
doing all along. But since String is a final class, we can’t create our own subclasses:

class MyStrings extends String { // ILLEGAL!


. . .
}

If we try to extend String, as shown, the compiler spits out a “Can’t subclass Final Objects” message and
refuses to go on. Of course, we’re still free to use the String class to create String objects. We’ve been
doing that all along. However, attempting to create a subclass of String is forbidden.

String versus StringBuffer

As you’re now aware, Java provides two distinct string classes: String and StringBuffer. The String class is
used to create String objects which are immutable; their contents can’t be altered once characters have
been stored in them. StringBuffer, on the other hand, is specifically for strings that are mutable, or able to
be changed even after characters have been stored in them. We’ll get to StringBuffer in a moment, but for
now, let’s take a closer look at the String class.

In Java, the char data type is twice the size C/C++ developers might expect. Instead of being 8
bits, the Java char is a 16-bit unsigned type, capable of holding tens of thousands of values
associated with Unicode characters. However, if you are using standard ASCII or Latin-1
characters, there is no way to tell the difference between Java char values and their C/C++
counterparts. Due to char’s 16-bit size, the byte is actually the smallest of all integral data types
in Java, weighing in at a lean 8 bits.

Suppose we created a String object and then tried to change its value later in the program:

String myString = “There once was a mouse from Nantucket”;


myString = “Hickory, Dickory, Dock”; // legal?

Is this legal? Sure it is, even though you might think otherwise. In this case, we’re not attempting to alter

file:///F|/books/java%20books/Java%20Bible/ch12/12-02.html (1 of 4)6/26/2005 7:57:03 PM


Java Bible:Strings and Arrays

the contents of the string; that is, we’re not trying to change the individual characters in the String object.
Instead, we’re storing a brand new set of characters into it, which is perfectly legal. The original string is
replaced entirely by “Hickory, Dickory, Dock”—the whole string is replaced, lock, stock, and barrel.

However, if we attempted to change the individual characters in a String object, we’d be in for a rude
awakening:

String myString = “There once was a mouse from Nantucket”;


myString[0] = ‘Z’; // ILLEGAL!

In this example, we’re trying to treat the Java String object as we would a standard C/C++ string.
However, when it attempted to set the first character in the String array to the character “Z”, the compiler
screamed bloody murder:

StringTest.java:8: [] can only be applied to arrays. It can’t


be applied to java.lang.String.
myString[0] = “Z”;
^
1 error

We’ve been told in no uncertain terms that a String object isn’t an array (we’ll get to arrays later), and so
we’d better not treat it as such. “No problem,” you might think to yourself, “I’ll just use the handy
setCharAt() method defined in StringBuffer.” But:

myString.setCharAt (0,‘Z’) ; // ILLEGAL!

A fine thought, except for the fact that the compiler will clutch its heart and gasp for air as you try to
manhandle an immutable String object. Remember, you can’t change the contents of a String object, only
StringBuffer objects. And, since setChar() isn’t defined in the String class, you can’t use it.

As you can see from the methods listed in Table 12-1, you can find out a lot about String objects, hut you
can’t change their contents. The closest you can get Is to blow away the entire string representation and
replace it with another, as we did earlier. But, no matter how hard you try, you can’t twiddle the contents
of a String object.

Creating strings

Although our programs have been giving birth to String objects all along, the process bears a closer look.
Clearly, one way they can be created is by assigning a string literal (we’ll get to literals in a moment) to
a String object variable:

String myString = “Whose whiskers were so strong”;

file:///F|/books/java%20books/Java%20Bible/ch12/12-02.html (2 of 4)6/26/2005 7:57:03 PM


Java Bible:Strings and Arrays

This is the easiest way to create a string, as we’ve been doing for some time. However, you’ll notice that
the String class gives us seven different constructors as well. The previous statement is functionally
equivalent to the following:

String myString = new String (“Whose whiskers were so strong”);

And, for that matter, these are both functionally equivalent to creating an array of characters that are
then supplied to the constructor capable of converting arrays into String objects:

char myChars[] = {‘W’, ‘h’, ‘o’, ‘s’, ‘e’, ‘ ’, ‘w’, ‘h’, ‘i’,
‘s’, ‘k’, ‘e’, ‘r’, ‘s’, ‘ ’, ‘w’, ‘e’, ‘r’, ‘e’, ‘ ’, ‘s’,
‘o’, ‘ ’, ‘s’, ‘t’, ‘r’, ‘o’, ‘n’, ‘g’} // create array of
characters
String myString = new String(myChars); /* use array to create
new String object */

Of course, we can also create String objects from arrays of bytes, and even subsections of arrays. Using
the same character array declared in the previous example, we can grab a portion of it for use as a string:

String myString = new String(myChars,6,8);

Here, we create a String object using a slice of the myChars array. By providing the index in the array at
which to start, together with the number of elements to use, we can create a string from a subsection of
that array. In the current example, the String object would now contain “whiskers.”

Perhaps you noticed that the beginning index I provided for a slice of the array, 6, seems to
indicate the String object should include a space and drop the last character(s) in the word
“whiskers?”

Although this seems like a mistake, it’s not. You might recall from Chapter 7 that array indexing begins
at zero (0), and not at one (1), as you’d think. While C and C++ programmers are already familiar with
such zero-based array indexing, we’ll revisit the topic later, when we talk about arrays.

As it stands, this line of code creates a string using the characters “whiskers” not “hisker”.
However, if you happen upon a mouse from Nantucket having strong hiskers, be sure to drop
me a line; I’d be most curious to see such a creature.

Depending on your needs, there’s likely to be a constructor to fit the bill. As you can see, arrays and
strings work hand in hand; indeed, four of the seven constructors accept array parameters.

file:///F|/books/java%20books/Java%20Bible/ch12/12-02.html (3 of 4)6/26/2005 7:57:03 PM


Java Bible:Strings and Arrays

You’ll also note that we can create an empty String object, which we can fill with characters later:

String myString = new String(); // create empty string object


myString = “Whose whiskers were so strong”; // fill with
characters

If you tried to print the empty myString before it was filled with characters, nothing would actually print.
Keep in mind that myString isn’t null, it’s simply empty—sort of like a mug of coffee without any coffee
in it. Sort of.

The null keyword has no meaningful value associated with it; it simply means an object is not
referenced anywhere. To determine if an object has a reference, you can test it against null:

if (anyObject = = null){
. . . // if true, object has no reference
}

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-02.html (4 of 4)6/26/2005 7:57:03 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

This is particularly helpful when dealing with String objects, and in fact is how you determine if an
applet’s PARAM tag is provided. When an HTML document doesn’t contain a particular PARAM tag,
you’ll know by testing for null. In this case, you can supply a default value:

soundFile = getParameter(“sound”); // get sound PARAM


if (soundFile = = null){
soundFile = “audio\welcome.au”; // set default if not
provided
}E

Once we have a String object, it’s easy to make a copy of it using the appropriate constructor:

String anotherString = new String(myString); /* create copy of


myString */

Of course, we can also assign one String object to another. The following assignment is the functional
equivalent of the preceding constructor:

anotherString = myString; // copy myString into anotherString

Finally, we can create a String object from a StringBuffer object:

String myString = new String (anyStringBufferObject);

The contents of the StringBuffer object are copied into the new String object, effectively creating an
immutable copy of a once-mutable string.

Accessor methods

Once you’ve created a String object, chances are you’ll want to do something with it. This stands to
reason; why would you bother creating an object if you didn’t want to do something with it? As luck
would have it, we can do a lot with String objects.

file:///F|/books/java%20books/Java%20Bible/ch12/12-03.html (1 of 5)6/26/2005 7:57:04 PM


Java Bible:Strings and Arrays

We’re already sent String objects to the standard output stream, which typically writes the contents to the
display (although they may be redirected, for example to a file):

System.out.print(myString);
System.out.println(myString);

We also use String objects in a variety of other methods, a few of which we’re already familiar with:

drawString(myString, 100, 100); // draw the string on screen


getImage(getCodeBase(), myString); // get an image file
getAudioClip(getCodeBase(), myString); // get an audio file
setTitle(myString); // set window/frame title
new Menu(myString); // create new menu with this name
new Button(myString); // create button with this name

However, aside from being used as parameters in method calls, there area number of methods that
operate on String objects, as seen in Table 12-1.

We might, for example, want to change a few characters in an existing String object. This we ran do
easily by using the replace () method, specifying the characters to be replaced, and specifying the
character to replace them with. However, since we can’t alter a String as we ran a StringBuffer, the result is
returned as a new String:

String myString = “Hickory, Dickory, Dock”;


String alterString = myString.replace(‘k’, ’c’); /* creates a
brand new string, an exact copy of the original with one major
exception — this one has all occurrences of k replaced with c
*/

After executing, alterString would contain “Hiccory, Diccory, Docc,“ and myString would remain
unchanged.

As you can see, the methods that would normally alter the contents of the string-such as replace()
—don’t. Instead, they return a new String object, since they can’t physically alter the one they are given.
While you may not make much use of such methods, depending on your needs, it’s nice to know they
exist, giving us a way to work around the restriction of Java strings being immutable.

One of the string methods you’re likely to use on a regular basis, on the other hand, is length(). This
method returns the number of characters in a String object, which you’ll need if you do any type of work
that requires a tun through each of the characters.

file:///F|/books/java%20books/Java%20Bible/ch12/12-03.html (2 of 5)6/26/2005 7:57:04 PM


Java Bible:Strings and Arrays

For example, suppose you wanted to output a string in reverse, I’m not certain why you might want to
do such a thing, but you ran do it as long as you know the length of the string:

String myString = “Hickory, Dickory, Dock”;


int len = myString.length(); // get number of chars in array
for (; len>O; len—) {
System.out.print(myString.charAt(len-1)); // output a
character
}
System.out.println(); // flush output

Notice the parameter to charAt()? Again, since String objects are stored in the same fashion as arrays, you
need to be aware that the first character begins at zero (0), and the last character is at the position “length
of the array minus one.” If the concept of beginning at zero throws you off, you might want to revisit
Chapter 9 for a few moments.

A particularly handy method when gathering user input is trim(), which takes a string and returns a copy
of it without any preceding or trailing white space. For example, if you prompt the user for input, he or
she might enter spaces before and/or after the string.

Suppose, for instance, that you developed a spreadsheet applet that required valid numeric input. If,
instead of entering only the numerals 23415, the user added a few spaces, the result would need to be
trimmed:

String origString = “ 23415 ”;


String trimmedString = origString.trim();

When executed, the preceding code copies the characters “23415” into the trimmedString object.
However, all the whitespace before and after the characters is left out. We now have a nice, freshly
trimmed string. You’ll notice, however, that it’s still a String object, not a numeric value such as an int or
long. If we attempted to use this string in a loop, for example, the compiler would laugh out loud (if it
could):

for (int i=0; i<trimmedString; j++) {


System.out.println(“Iteration: ”+ j);
}
Survey says:
Incompatible type for <. Can’t convert java.lang. String to int.
for (int i=O; i<trimmedString; i++) {
^
1 error

file:///F|/books/java%20books/Java%20Bible/ch12/12-03.html (3 of 5)6/26/2005 7:57:04 PM


Java Bible:Strings and Arrays

At first glance, the valueOf() constructors seem like they might do the trick; feed ’em a string and they’ll
return the value of it, right? Nope; they do just the opposite. If you supply valueOf() with a number, it
returns a string containing the character equivalent of those numbers:

String numString = new String().valueOf(“23415”);

For example, if we supplied valueOf () with “23415,” we’d get a string equal to that of trimmedString. In
fact, we can test for equality just to prove it:

String numString = new String().valueOf(23415);


if (trimmedString.equals(numString)) // test for equality
System.out.println(numString +“ and ”+ trimmedString +
“ ARE EQUAL”);
else
System.out.println(numString +“ and ”+ trimmedString +
“ ARE NOT EQUAL”);

But can’t we check for equality using the == operator? Sure, and in most cases you’ll get the result you’d
expect. However, you need to be extremely cautious. When you create a string using valueOf() , as shown
earlier, it won’t evaluate to true when compared with a String object created as usual. For example,
although the preceding snippet of code will tell you the two String objects are equal, try this;

String numString = new String().valueOf(“23415”);


if (numString == trimmedString)
System.out.println(numString + “ and ” + trimmedString +
“ ARE EQUAL”);
else
System.out.println(numString + “ and ” + trimmedString +
“ ARE NOT EQUAL”),

In this case, you’d still expect the evaluation to produce “true.” But it doesn’t. As a matter of fact, if you
want to test the concept of testing for equality, try this:

String numStringl = new String().valueOf(12345);


String numString2 = “12345”;
if (numString1 == numString2)
System.out.prinln(numString1 + “ and ” + numString2 +
“ ARE EQUAL”);
else
System.out.println(numString1 + “ and ” + numString2 +
“ ARE NOT EQUAL”);

file:///F|/books/java%20books/Java%20Bible/ch12/12-03.html (4 of 5)6/26/2005 7:57:04 PM


Java Bible:Strings and Arrays

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-03.html (5 of 5)6/26/2005 7:57:04 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Even though they look equal, and are when using the equals() method, the internal representation of these
two String objects is different. The result is an equality evaluation of “false,” which can really throw you
off the mark, since you’d expect them to evaluate to “true.” The reason is that we’ve supplied an int to
valueOf(), which is different from supplying characters:

String numString1 = new String().valueOf(“12345”);


String numString2 = “12345”;
if (numStringl == numString2)
System.out.println(numStringl + “ and ” + numString2 +
” ARE EQUAL”);
else
System.out.println(numStringl + “ and ” + numString2 +
“ ARE NOT EQUAL”);

Now, this would indeed evaluate to “true.” We didn’t supply valueOf() with an int this time around; we
supplied a string literal. As a result, the == operator recognizes these as being the same. However, no
matter which way you create a string using valueOf(), it won’t be the same as one returned as the result of
the trim() method, as far as the == operator is concerned. To be safe, it’s best to use the equals() method
whenever you’re evaluating String objects for equality.

As you can see, I didn’t supply curly braces ( { } ) in the if statements here. Since only one line
of code is to be executed in both cases (that is, only one line of code follows the if clause, and
only one follows else), we aren’t required to use them.

In such cases, where you only have one line of code to execute following an evaluation, you don’t have
to bother surrounding it with curly braces. For example,

if (boolean) {
System.out.println (“Blah, Blah, Blah ”);
}

is functionally equivalent to:

file:///F|/books/java%20books/Java%20Bible/ch12/12-04.html (1 of 4)6/26/2005 7:57:04 PM


Java Bible:Strings and Arrays

if (boolean)
System.out.println (“Blah, Blah, Blah ”);

This is all useful, but it doesn’t solve our original problem of wanting to use a String object such as
trimmedString as an actual number. Remember, the compiler won’t let us use a string in our loops, even if
that string is a set of digit characters. And since valueOf() converts values to String objects, not the other
way around as we originally thought, it’s of no help. So what do we do? Brace yourself; we wrap.

Type wrappers

I’d be willing to bet that most new programmers are drawn to their field because of the cool names used
for everything. We have “protocols,” “stacks,” “bits,” “bytes,” “RAM,” and “ROM.” On a good day, we
“push,” “poke,” “tunnel,” “loop,” and “bitblit.” On a bad day, we crawl through the “stack,” “trap”
errors, and hunt “bugs.”

And now we “wrap to the beat of primitive data types.” (This is, of course, a joke. Keep your flamemail
out of my inbox. Hmmm ... fiamemail... there’s another one.)

Aside from providing a nifty new term, type wrappers give us exactly what we’re looking for: a way to
extract numerical values from String objects.

And they do much more.

Since most Java methods expect objects as parameters, many don’t know how to deal with true numeric
data types such as int, long, float, double, and so on. You may recall that these are actually primitive data
types that can’t be reduced any further; in order to use them as objects, we must first wrap an object
around them.

For example, if we have an int value of 235, that value isn’t an object; it’s a primitive data type. In order
to treat it as an object, we must first wrap an Integer object around it. Now, don’t confuse the Integer class
(java. lang. Integer) with an int data type: they’re two different beasts. The Integer class defines the methods
we’ll use to treat an int as an object. As such, it’s known as a type wrapper; it allows us to wrap an
object around numeric data types. To be even more specific, the Integer class can be called an integral
type wrapper.

In order to use a type wrapper, you supply it with a value. What you receive in return is an object that
may be treated like any other object. You can send it messages to invoke methods and pass it as a
parameter to other methods:

Object myIntObject = new Integer(235); // create Integer object

file:///F|/books/java%20books/Java%20Bible/ch12/12-04.html (2 of 4)6/26/2005 7:57:04 PM


Java Bible:Strings and Arrays

Now we have an object that can be treated like any other object. However, this still doesn’t help us use
our original triminedString variable as part of the for loop condition. It just allows us to create an Integer
object from an int data type. We need to do the reverse; we need to create an int data type from a String
object!

Wrapper classes allow us to do just that. First, we use the Integer constructor that takes as its parameter a
string. Once we’ve created an object using this type wrapper, we can use the intValue() method to retrieve
from it the int value we need:

int theInt = new Integer (trimmedString).intValue(); // get that


int!
for (int i=0; i<theInt; i++) { // and use it .
System.out.println(“Iteration: ” + i);
}

We’ve finally solved our problem of treating a String object as a primitive data type: We don’t actually
treat it as a primitive. Instead, we wrap an Integer object around the String object, then use the intValue()
method to extract the primitive.

At this point, you might ask, “Hey, why not just cast the String object into an Integer object instead of
instantiating a brand new object?” That’s a good question, since it would save three keystrokes by not
requiring us to type new code:

int theInt = ((Integer) trimmedString).intValue(); // ILLEGAL!

Unfortunately, this doesn’t fly. The compiler beats it to the ground, as if to make up for all the time it
spends sorting out your uninitialized variables (perhaps, if it didn’t bother assigning default values to
your uninitialized variables, the compiler would have the wherewithal to perform this cast). Instead, you
must instantiate an Integer object, as we did earlier. Anyway, if you take into account the extra
parentheses needed to perform the cast and make the statement readable, you would only save one
keystroke.

Although we’ve been wrapped up in integral type wrappers, you’ll be happy to know there are many
other wrapper flavors—one to satisfy every primitive data type need. Since there are several primitive
data types, there are several type wrapper classes. These are listed here, with the appropriate tables for
their constructors, methods, and variables:

• Boolean (java. lang. Boolean) (see Tables 12-2, 12-3, and 12-4)
• Character (java. lang. Character) (see Tables 12-5, 12-6, and 12-7)
• Integer (java. lang. Integer) (see Tables 12-8, 12-9, and 12-10)
• Float (java. lang. Float) (see Tables 12-11, 12-12, and 12-13)
• Double (java. lang. Double) (see Tables 12-14-, 12-15, and 12-16)

file:///F|/books/java%20books/Java%20Bible/ch12/12-04.html (3 of 4)6/26/2005 7:57:04 PM


Java Bible:Strings and Arrays

• Long (java. lang. Long) (see Tables 12-17, 12-18, and 12-19)

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-04.html (4 of 4)6/26/2005 7:57:04 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Table 12-2
java.lang.Boolean Constructors

Signature Description

Boolean(boolean) Constructs a Boolean object initialized to the specified boolean value.

Constructs a Boolean object initialized to the value specified by the String


Boolean(String)
parameter.

Table 12-3
java.lang.Boolean Methods

Method Signature Description

Returns the value of this Boolean object as a


booleanValue public boolean booleanValue()
boolean.

equals public boolean equals (Object obj) Compares this object against the specified object.

public static boolean getBoolean (String


getBoolean Gets a boolean from the properties.
name)

hashCode public int hashCode() Returns a hash code for this boolean.

Returns a new String object representing this


toString public String toString()
boolean’s value.

file:///F|/books/java%20books/Java%20Bible/ch12/12-05.html (1 of 4)6/26/2005 7:57:05 PM


Java Bible:Strings and Arrays

Returns the boolean value represented by the


valueOf public static boolean valueOf (String s)
specified string.

Table 12-4
java.lang, BOolean Variables

Variable Signature Description

FALSE public final static Boolearl FALSE Assigns this boolean to be false.

MAX_VALUE public final static char MAX_VALUE The maximum value a character can have.

MIN_VALUE public final static char MI N_VALUE The minimum value a character can have.

TRUE public final static Boolean TRUE Assigns this boolean to be true.

Table 12-5
java.lang.Character Constructors

Signature Description

public Character(char value) Constructs a Character object with the specified value.

Table 12-6
java.lang.Character Methods

Method Signature Description

charValue public char charValue() Returns the value of this Character object.

Returns the numeric value of the character digit


digit public static int digit(char ch int radix) *
using the specified radix.

file:///F|/books/java%20books/Java%20Bible/ch12/12-05.html (2 of 4)6/26/2005 7:57:05 PM


Java Bible:Strings and Arrays

equals public boolean equals Object obj) Compares this object against the specified object.

public static char forDigit (int digit, iht Returns the character value for the specified digit
forDigit *
radix) in the specified radix.

hashCode public int hashCode() Returns a hash code for this character.

Determines whether the specified character is an


isDigit public static boolean is Digit(char ch)
ISO-LATIN-1 digit.

Determines whether the specified character is ISO-


isLowerCase public static boolean isLowerCase(char ch)
LATIN-1 lowercase.

Determines whether the specified character is ISO-


isSpace public static boolean isSpace (char ch)
LATIN-1 whitespace, according to Java.

Determines whether the specified character is ISO-


isUpperCase public static boolean isUpperCase(char ch)
LATIN-1 uppercase.

Returns the lowercase character value of the ISO-


toLowerCase public static char toLowerCase (char ch) LATIN-1 character. Characters that are not
uppercase letters are returned unmodified.

Returns a String object representing this character’s


toString public String toString()
value.

Returns the uppercase character value of the


specified ISO-LATIN- 1 character. Characters that
are not lowercase letters are returned unmodified.
toUpperCase public static char toUpperCase (char ch) Note that the German and Latin ÿ have no
corresponding uppercase letters, even though they
are lowercase. There is a capital numberville ÿ, but
not in ISO-LATIN-1.

*
A positive integer, where the weight of the digit place is multiplied to obtain the weight of the

file:///F|/books/java%20books/Java%20Bible/ch12/12-05.html (3 of 4)6/26/2005 7:57:05 PM


Java Bible:Strings and Arrays

digit place with the next higher weight.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-05.html (4 of 4)6/26/2005 7:57:05 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Table 12-19
java.lang.Long Variables

Variable Signature Description

MAX_VALUE public final static long MAX_VALUE The maximum value a long can have.

MIN_VALUE public final static long MIN_VALUE The minimum value a long can have.

As you can see, each of these primitive data types is part of the java.lang package. Since this package is
automatically available to our programs, we don’t need to bother importing it. You might also be
interested to know that each one, with the exception of Boolean, descends from an abstract class called
java.lang.Number (Boolean is a direct subclass of Object).

Aside from providing the wrapper functionality we’ve just discovered, these classes also allow us to
extract values of different types from the wrapped value. For example, we could have retrieved the value
from our Integer object in the form of a long, a float, or a double, in addition to the int we actually received:

long theLong = new Integer(trimmedString).longValue();


double theDouble = new Integer(trimmedString).doubleValue();
float theFloat = new Integer(trimmedString).floatValue();

String literals

String literals are characters surrounded by double quotation marks (“ ”). We’ve been using them all
along, most obviously when we create a String object:

String myString = “You’re looking at a string literal”;

file:///F|/books/java%20books/Java%20Bible/ch12/12-09.html (1 of 5)6/26/2005 7:57:05 PM


Java Bible:Strings and Arrays

In fact, we use string literals in method calls all the time:

drawString(“Hello World”, 100, 100);


get Image(getCodeBase(), “images/world.gif”);
getAudioClip(getCodeBase(), “audio/hello.au”);
setTitle(“Widget Window”);
new Menu(“Edit”);
new Button(“Click Me”);

Anywhere a String object is used, we can substitute a string literal. This is because the compiler actually
instantiates a String object from our literal. String literals can be any number of characters surrounded by
double quotation marks, even no characters at all:

“ ”

The example shows an empty string literal. It’s just as valid a string as any others we’ve seen, even
though it happens to be empty.

Concatenation and the + operator

Java supports the use of a concatenation operator that joins two or more strings together to form one
string:

String myString1 = “Hickory”;


String myString2 = “Dickory”;
String myString3 = “Dock”;
String allInOne = myStringl + myString2 + myString3;

We can also concatenate string literals:

String allInOne = “Hickory” + “Dickory” + “Dock”;

The result is one string containing the contents of all three. In this case, we assign the result to a string
variable. If we were to take a peek at the contents of allInOne, it would look like this:

Hickory DickoryDock

Since we didn’t specify any spaces when concatenating these strings, they were placed one right after
the other. If we wanted spaces, we could have provided them in the string literals, or when performing
the concatenating operation:

file:///F|/books/java%20books/Java%20Bible/ch12/12-09.html (2 of 5)6/26/2005 7:57:05 PM


Java Bible:Strings and Arrays

String allInOne = “Hickory ” + “Dickory” + “Dock”;

Or:

String allInOne = “Hickory” + “ ” + “Dickory” + “ ” + “Dock”;

When either of these two approaches is used, the result is a single string with spaces between each set of
characters being joined:

Hickory Dickory Dock

As you now know, we can join both String objects and string literals. In both cases, you are free to break
them up across several lines:

String brokenString = “The string literal you are now” +


“reading has been broken up ” +
“intentionally. In total, it spans ” +
“four lines”;

All four of the preceding string literals are joined as one using the string concatenation operator you’ll
read about in a moment. Using this operator, we can also break up strings inside constructors and
method calls:

String brokenString = new String (“The string literal you are”


+
“now reading has been broken up ” +
“intentionally. In total, it spans ” +
“four lines”);
drawString(“Hello ” +
“World”, 100, 100);

And, although we’ve used string literals already, this applies to String objects as well. In fact, we can
concatenate them both in any fashion we require:

String allInOne = myStringObject + “Here’s a literal” +


anotherStringObject + andAnotherStringObject +
“Plus one more string literal”;

Character constants

When specifying string literals, we can include escape sequences that represent characters such tabs,
carriage returns, and form feeds:

file:///F|/books/java%20books/Java%20Bible/ch12/12-09.html (3 of 5)6/26/2005 7:57:05 PM


Java Bible:Strings and Arrays

String myString = “There is a tab between here and \t there.”;


String myString = “There’s a carriage return between here and \r
there.”;
String myString = “There’s a new line between here and \n
there.”;
String myString = “The word \“mouse\” is in double quotes”;

In addition, we can include Unicode escape sequences:

String myString = “There is a trademark symbol between here and


\u2122 there.”;

When adding Unicode escapes, however, keep in mind that just because you can do it doesn’t
mean users will see what you intend. If the system on which your program is executed doesn’t
support the full suite of Unicode characters, or the font used during output doesn’t support that
character, they’ll never see what you specify. As a result, be frugal with Unicode and test your
programs on as wide a range of systems as possible, if you do utilize it in this way.

StringBuffer (java.lang. StringBuffer)

By now, you’re probably pretty comfortable with immutable String objects. When you want to change
them, you can’t. Instead, you create a completely new String object that receives the result of whatever
you want to do to the original. In this way, the original string is preserved, pristine, untouched.

StringBuffer objects, however, allow you to create mutable strings (see Table 12-20). That is, we can rip
’em up without worrying about the compiler having a stroke. However, we don’t have the plethora of
methods to choose from with StringBuffer as we do with String, as you can see from Table 12-21.

Since StringBuffer objects are typically less efficient than String objects, they are usually used only in the
ultimate creation of String objects. In fact, the Java compiler uses StringBuffer objects to implement the
string concatenation operator we saw earlier:

“The string literal you are now ” +


“reading has been broken up ” +
“intentionally. In total, it spans ” +
“four lines”;

The string concatenation compiles like this:

new StringBuffer().append(“The string literal you are now ”).

file:///F|/books/java%20books/Java%20Bible/ch12/12-09.html (4 of 5)6/26/2005 7:57:05 PM


Java Bible:Strings and Arrays

append(“reading has been broken up”). append(“intentionally. In


total, it spans ”).append(“four lines”).toString();

Although this might be a bit messy at first glance, begin reading carefully from left to right. You’ll see
that a new StringBuffer object is created, to which each string literal is appended using the append()
method. Finally, the results contained in the StringBuffer object are converted into a String object by way
of the toString() method.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-09.html (5 of 5)6/26/2005 7:57:05 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Table 12-15
java.lang.Double Methods

Method Signature Description

public static long doubleToLongBits (double Returns the bit representation of a double
doubleToLongBits
value) float value.

doubleValue public double doubleValue() Returns the double value of this double.

Compares this object against the


equals equals(Object obj)
specified object.

floatValue public float floatValue() Returns the float value this double.

hashCode public int hashCode() Returns a hash code for this double.

Returns the integer value of this double


intValue public int intValue()
(by casting to an int).

Returns true if this double value is infinite


isInfinite public boolean isInfinite()
in magnitude.

Returns true if the specified number is


isInfinite public boolean isInfinite(double v)
infinite in magnitude.

Returns true if this double value is the


isNaN public boolean isNaN()
special Not-a-Number (NaN) value.

file:///F|/books/java%20books/Java%20Bible/ch12/12-08.html (1 of 4)6/26/2005 7:57:06 PM


Java Bible:Strings and Arrays

Returns true if the specified number is


isNaN public static boolean isNaN (double v)
the special Not-a-Number (NaN) value.

Returns the double float corresponding to


longBitsToDouble public static double longBitsToDouble (long bits)
a given bit representation.

Returns the long value of this double (by


longValue public long longValue()
casting to a long).

Returns a string representation of this


toString public String toString()
Double object.

Returns a string representation for the


toString public static String toString (double d)
specified double value.

Returns a new double value initialized to


valueOf valueOf(String) the value represented by the specified
string.

Table 12-16
java.lang.Double Variables

Variable Signature Description

The maximum value a double can


MAX_VALUE public final static double MAX_VALUE
have.

The minimum value a double can


MIN_VALUE public final static double MIN VALUE
have.

NaN public final static double MIN_VALUE Not-a-Number (NaN).

public final static double NEGATIVE_


NEGATIVE_INFINITY Negative infinity.
INFINITY

file:///F|/books/java%20books/Java%20Bible/ch12/12-08.html (2 of 4)6/26/2005 7:57:06 PM


Java Bible:Strings and Arrays

public final static double POSITIVE_


POSITIVE_INFINITY Positive infinity.
INFINITY

Table 12-17
java.lang. Long Constructors

Signature Description

public Long(long value) Constructs a Long object initialized to the specified value.

public long Long(String Constructs a Long object initialized to the value specified by the string
s) parameter.
Throws NumberFormatException if the string does not contain a parsable long.

Table 12-18
java.lang.Long Methods

Method Signature Description

doubleValue public double doubleValue() Returns the value of this long as a double.

equals public boolean equals(Object obj) Compares this object against the specified object.

floatValue public float floatValue() Returns the value of this long as a float.

public static long getLong (String


getLong Gets a long property. Returns zero (0) if it does not exist.
nm)

public static long getLong (String Gets a long property. Returns val if it does not exist. Deals
getLong
nm, long val ) with hexadecimal and octal numbers.

hashCode public int hashCode() Computes a hash code for this long.

intValue public int intValue() Returns the value of this long as an int.

file:///F|/books/java%20books/Java%20Bible/ch12/12-08.html (3 of 4)6/26/2005 7:57:06 PM


Java Bible:Strings and Arrays

longValue public long longValue() Returns the value of this long as a long

public static long parseLong Assuming the specified string represents a long, return that
parseLong
(String s) long’s value.

Throws NumberFormatException if the string cannot be parsed


as a long.

Assuming the specified string represents a long, returns that


public static tong parseLong
parseLong long’s value. Throws NumberFormatException if the string
(String s, int radix)
cannot be parsed as a long.

toString public String toString() Returns a String object representing this long’s value.

public static String toString (long Returns a new String object representing the specified
toString
i) integer.

public static String toString (long Returns a new String object representing the specified long in
toString
i, the specified radix.

Assuming the specified string represents a long, returns a


public static Long valueOf (String new Long object initialized to that value. Throws
valueOf
s) NumberFormatException if the string does not contain a
parsable long.

Assuming the specified string represents a long, returns a


public static Long valueOf (String new Long object initialized to that value.Throws
valueOf
s. int radix) NumberFormatException if the string cannot be parsed as a
parsable long.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-08.html (4 of 4)6/26/2005 7:57:06 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Table 12-20
java.lang.StringBuffer Constructors

Constructor Signature Description

StringBuffer public StringBuffer() Constructs an empty string buffer.

public StringBuffer (int Constructs an empty string buffer with the specified
StringBuffer (int)
length) initial length.

StringBuffer
StringBuffer (String str) Constructs a string buffer with the specified initial value.
(String)

Table 12-21
java.lang.StringBuffer Methods

Method Signature Description

Appends a boolean to the end of this


append public StringBuffer append(boolean b)
buffer.

Appends a char to the end of this


Append public synchronized StringBuffer append (char c )
buffer.

Appends a double to the end of this


Append public StringBuffer append(double d)
buffer.

file:///F|/books/java%20books/Java%20Bible/ch12/12-10.html (1 of 3)6/26/2005 7:57:06 PM


Java Bible:Strings and Arrays

Appends a float to the end of this


Append public StringBuffer append(float f)
buffer.

Append public StringBuffer append(int i) Appends an int to the end of this buffer.

Appends a long to the end of this


Append public StringBuffer append(long l)
buffer.

Appends an object to the end of this


Append public synchronized StringBuffer append (Object obj)
buffer.

Appends a string to the end of this


Append public synchronized StringBuffer append (String str)
buffer.

Appends an array of character strings


Append public synchronized StringBuffer append (char str[])
to the end of this buffer.

public synchronized StringBuffer append (char str[], int Appends part of an array of characters
Append
offset, int len) to the end of this buffer.

Returns the current capacity of the


Capacity public int capacity()
string buffer.

Returns the character at the specified


CharAt public synchronized char charAt(int index)
index.

Ensures that the capacity of the buffer


public synchronized void ensureCapacity (int
capacity is at least equal to the specified
minimumCapacity)
minimum.

Copies the characters of the specified


public synchronized void getChars(int srcBegin, int srcEnd, substring (determined by srcBegin and
GetChars
char dst[], int dstBegin) srcEnd) into the character array, starting
at the array’s dstBegin location.

Insert public StringBuffer insert (int offset, boolean b) Inserts a boolean into the string buffer.

Insert public synchronized StringBuffer insert (int offset, char c) Inserts a char into the string buffer.

file:///F|/books/java%20books/Java%20Bible/ch12/12-10.html (2 of 3)6/26/2005 7:57:06 PM


Java Bible:Strings and Arrays

Inserts an array of characters into the


Insert public synchronized StringBuffer insert
string buffer.

Insert public StringBuffer insert(int offset, double d) Inserts a double into the string buffer.

Insert public StringBuffer insert(int offset, float f) Inserts a float into the string buffer.

Insert public StringBuffer insert(int offset, int i) Inserts an int into the string buffer.

Insert public StringBuffer insert(int offset, long l ) Inserts a long into the string buffer.

public synchronized StringBuffer insert (int offset, Object


Insert Inserts an object into the string buffer.
obj)

Insert public synchronized StringBuffer insert (int offset, String str) Inserts a string into the string buffer.

Returns the length (character count) of


Length public int length()
the buffer.

Changes the character at the specified


SetCharAt public synchronized void setCharAt(int index, char ch)
index to be ch.

SetLength public synchronized void setLength(int newLength) Sets the length of the string.

Converts to a string representing the


ToString() public String toString()
data in the buffer.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-10.html (3 of 3)6/26/2005 7:57:06 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

As you can see, the bulk of StringBuffer methods are variations of append() and insert(). This is because
StringBuffer is specifically built to grow as input is appended to it, and also to allow changes to the data,
as seen with the insert() method.

Creating StringBuffer objects

You’ll also notice three StringBuffer constructors, each of which creates a “buffer of strings.” One
constructor creates an empty string buffer, another creates an empty string buffer set to the initial length
you specify, and the last creates a string buffer from the String object you provide:

StringBuffer myBuffer = new StringBuffer(); // empty


StringBuffer myBuff2 = new StringBuffer(50); /* empty, 50
characters in length */
StringBuffer myBuff3 = new StringBuffer(“Hello”); // using String

Although it may be tempting to create empty buffers of unspecified length, it’s much more efficient to
specify the length if possible. When you don’t, or if you use a String object when creating a string buffer,
memory must be allocated whenever something is appended to the buffer. When the size is known, as in
the last two examples, the buffer allocates the memory in advance and doesn’t need to allocate more,
unless it grows beyond that size.

Thus, the following is discouraged:

StringBuffer myBuffer = new StringBuffer();


myBuffer.append(“There once was a mouse from Nantucket”);

In favor of this:

StringBuffer myBuffer =
new StringBuffer(“There once was a mouse from Nantucket”);

Or this:

file:///F|/books/java%20books/Java%20Bible/ch12/12-11.html (1 of 5)6/26/2005 7:57:07 PM


Java Bible:Strings and Arrays

StringBuffer myBuffer =
new StringBuffer(37); /* exactly what we
need */
myBuffer.append(“There once was a mouse from Nantucket”);

Or even this:

StringBuffer myBuffer = new StringBuffer(50); /* a little more


than we need */
myBuffer.append(“There once was a mouse from Nantucket”);

Modifying StringBuffer objects

Once we’ve created a StringBuffer object, whether of a specified length or empty, we can add data to it or
change data already in it. To append data, we use one of the many append() methods. To change data, we
use one of the various insert() methods.

Although you’ve already seen append() in action, there are a number of other data types you can append.
In the preceding examples, we’ve appended strings. However, as you can see from Tables 12-2 through
12-19, we could add primitive data types (boolean, char, int, long, float, double) and other objects.

For example, assume in each of the following examples that the StringBuffer variable, myBuff, contains
“Hickory” already.

We can append a boolean such as this:

myBuff.append(false); // results in “Hickoryfalse”.

An int such as this:

myBuff.append(13565); // results in “Hickory13565”

What if we append a long?

myBuff.append(35356253565L); // results in “Hickory35356253565”

Perhaps a floating-point value?

myBuff.append(4564.62); // results in “Hickory4564.62”

Let’s not forget the double:

file:///F|/books/java%20books/Java%20Bible/ch12/12-11.html (2 of 5)6/26/2005 7:57:07 PM


Java Bible:Strings and Arrays

myBuff.append(4.76645D); // results in “Hickory4.76645”

However, we might want to append an object, as opposed to these primitive data types:

Button myButton = new Button(“Click Me”);


myBuff.append(myButton); // append the button object

Before the appending takes place, the Button object is converted into a string. As a result, myBuffer would
be:

“Hickoryjava.awt.Button[0,0,0x0,invalid, label=Click Me]”

Since all objects know how to output themselves in string format, you can append them to or
insert them into StringBuffer objects. You can also determine whether String objects are equal to
other objects:

myString.equals(anyObject);

In addition to appending data to the end of a StringBuffer, you can insert data into a specific location. All
you need to do is provide an offset into the buffer:

myBuff.insert(3,true); // results in “Hictruekory”


myBuff.insert(6,13565): // results in “Hickor13565y”
myBuff.insert(2,4564.62); // results in “Hi4564.62ckory”

However, insert() won’t grow the buffer if you mistakenly provide an offset outside its bounds. For
example, suppose we tried to add the last floating-point value with an offset of 8:

myBuff.insert(8,4564.62); // exceeds bounds!

Since the buffer isn’t large enough to accommodate this insertion, the following exception is spit out at
runtime:

java.lang. StringIndexOutOfBoundsException
at java.lang.StringBuffer.insert(StringBuffer.java:333)
at java.lang. StringBuffer.insert(StringBuffer.java:432)
at StringTest.main(StringTest.java:97)

Although StringBuffer objects are most commonly used to create larger strings by appending and
inserting, you can directly change the contents of any of the elements in buffer using setCharat().

file:///F|/books/java%20books/Java%20Bible/ch12/12-11.html (3 of 5)6/26/2005 7:57:07 PM


Java Bible:Strings and Arrays

Although this example, and our previous treatment of String objects, might lead to us believe that both
the String and StringBuffer classes are really arrays, the truth is they are both descendants of Object.
However, they do indeed seem to be arrays at times, especially when accessing or setting contents at a
specific offset.

Yet, they are not arrays. String and StringBuffer are defined in their own distinct classes, and merely
support the type of behavior we’re accustomed to seeing with arrays. To understand the difference, let’s
take a look at arrays.

Arrays

In Java, arrays are truly first-class objects. Not only are they impossible to subclass, you won’t even find
a class definition for them. Instead, Java knows internally about arrays and how to treat them, just as it
knows how to deal with primitive data types without offering a class for each (keep in mind that type
wrappers for primitives are different from the primitives themselves; there are type wrapper classes, but
no primitive classes).

Unlike String and StringBuffer objects, which can contain only character data, arrays are capable of
holding any type of data we need, even other arrays. The only restriction is that each element in the array
must be of the same type. You can’t, for example, have an int in one element of an array, and a char in
another. All of the elements in a given array must be of the same type.

As you might recall from Chapter 7, to declare an array we need specify only two things:

• A variable through which we’ll access the array


• The data type of the elements the array will contain

To signal that this isn’t a standard variable, we use a pair of braces ( [ ] ) to identify the object as an array:

int myIntegers[]; // declare an array of integers


char myCharacters[]; // declare an array of characters
float myFloats[]; // declare an array of floating point numbers
String myStrings[]; // declare an array of String objects
StringBuffer myStringBuffs[]; // declare array of StringBuffers

When you see the braces attached to a variable, you know immediately that it’s actually an array of
elements instead of a single element:

However, there is another way to declare arrays in Java:


int[] myIntegers; // declare an array of integers
char[] myCharacters; // declare an array of characters

file:///F|/books/java%20books/Java%20Bible/ch12/12-11.html (4 of 5)6/26/2005 7:57:07 PM


Java Bible:Strings and Arrays

float[] myFloats; // declare an array of floating point numbers


String[] myStrings; // declare an array of String objects
StringBuffer[] myStringBuffs;// declare array of StringBuffers

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-11.html (5 of 5)6/26/2005 7:57:07 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Here, we’ve declared exactly the same arrays, but used a slightly different notation to do so. Some
programmers prefer this approach because they don’t have to look at the variable name to see that
they’re dealing with an array. Instead, they can quickly scan the data type listing to see which elements
are arrays and which are standard variables.

Although it may not seem like a big deal, consider the following:

int myInt, aInt, myInt, theInt, anotherInt, anyInt; // ints


float myFloat, afloat, myFloater, theFloats[], floating,
anyFloat; // floats
char myChar, aChar, myChar, theChar, character, anyChar; //
chars

Granted, it takes only a moment to scan the list of variables to see that the Floats [ ] is an array. However,
it’s much more apparent in the following variable declaration:

int myInt, aInt, myInt, theInt, anotherInt, anyInt; // ints


float myFloat, afloat, myFloater , floating, anyFloat; // floats
float[] theFloats; // floats
char myChar, aChar, myChar, theChar, character, anyChar; // chars

By scanning the data types, you can see immediately which are arrays, thanks to the pair of brackets
immediately following the data type. Using this notation saves the time of scanning through each
variable in search of brackets· Although insignificant when you’re wide awake and dealing with a
relatively small group of variables, it’s quite significant at the end of a long day, with half a page of
variables to wade through.

Instantiating arrays

Once you’ve declared an array, chances are you’ll want to do something with it. In order to use it, you
must first instantiate an Array object. Without an Array object, you have only an empty array variable.

file:///F|/books/java%20books/Java%20Bible/ch12/12-12.html (1 of 5)6/26/2005 7:57:08 PM


Java Bible:Strings and Arrays

In order to create an Array object, we typically use the new operator:

int myIntegers[]; // array declaration


. . .
myIntegers = new int[25]; // instantiation

While this example illustrates the fact that array declaration and instantiation are two distinct steps, as
with standard Java objects, they’re often more closely associated in practice· Usually, the array
declaration and instantiation happen at the same time:

int myIntegers[] = new int[25]; // declare and instantiate

When creating an Array object, we supply what is known as a dimension for that array. In the preceding
examples, the dimension is 25. As a result, the array has 25 elements in it. If we supplied a dimension of
2483, the array would have 2483 elements.

Auto-initialization

So, when an Array object is instantiated as shown, it contains the number of elements you specify as the
dimension. The array is effectively empty at this time, and each element is initialized to a default value.

With integral arrays, each element is initialized to zero (0). Each element in an array of booleans, on the
other hand, is automatically initialized to false. In all other cases, such as with String objects and other
compound data types (that is, any non-primitive), each element is initialized to null.

In-line initialization

In cases where you already know the elements you’d like to have in an array, you can save the time and
effort of placing each into its position by providing them at the time of declaration:

int[] myIntegers2 = {123, 354, 235, 6255, 1, 35, 42563};

In this case, you don’t have to explicitly dimension the array. We can have a good deal of work done for
us by setting the array equal to the elements surrounded with curly braces, each separated by a comma.

In the last example, the compiler sees that we want to add seven elements, and therefore does the rest of
the work automatically. The array is created and each element is added. We don’t have to dimension the
array and we don’t have to fill it ourselves (more on filling arrays in a moment).

This applies to arrays of any type; as long as you know what elements you want, you can add them in-
line at the time of declaration:

file:///F|/books/java%20books/Java%20Bible/ch12/12-12.html (2 of 5)6/26/2005 7:57:08 PM


Java Bible:Strings and Arrays

String[] myStrings = {“Hickory”, “Dickory”, “ Dock”};


float[] myFloats = {253.35, 2.0, 644.13, 35612., 6.7};
char[] myCharacters = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’};

Of course, as with any array, the data in each element in a given array must be of the same type. For
example, you can’t add a String object to an array of floating-point numbers. If you try, the compiler will
rap your knuckles.

Anonymous arrays

With JDK 1.0, you can only use the curly-braces syntax when you’re defining an array. With
JDK 1.1, however, the usage of the array initializer syntax has been extended. One of the most
important benefits of this is that you can now create an anonymous array, and using the curly
brace syntax, initialize the array when it is allocated. For example:

int[] a;
a = new int[] {1, 2, 3, 4, 5};

This creates an anonymous array a, which is created and initialized when new is called to allocate the
array. When memory for a is allocated, enough space is allocated to hold the initialization items found in
the curly braces—in this example, enough space for five integer array elements. While this new feature
won’t revolutionize your Java applications, it does make the process of creating dynamic arrays just a
little bit easier.

Setting and retrieving array elements

In certain circumstances, we can fill an array in-line at the time it’s declared. Where possible, this is
helpful, since we don’t have to do it ourselves. Unfortunately, it’s not usually possible to do this. Often,
we’re not certain which elements are going to be in an array at the time it’s created. In these cases, we
must fill the array later.

To fill an array, or a portion of an array, we access a particular element in it with an index value and set
it equal to whatever we want to be stored in it. Of course, the data we’re trying to stuff into an array
element must be the same type as the array is declared to hold:

int[] myIntegers = new int[25]; // create array with 25 elements


myIntegers[1] = 2353; // set element at index 1 to 2353

In this code, we’re stuffing the int value of 2353 into index 1 of the array. Because this is an array of
integers, the assignment is legal. To attempt a string assignment, on the other hand, would prevent your
code from compiling.

file:///F|/books/java%20books/Java%20Bible/ch12/12-12.html (3 of 5)6/26/2005 7:57:08 PM


Java Bible:Strings and Arrays

The term index, or subscript, is used to refer to a particular position in an array. If we supply
the value of 5 as an index or subscript for an array, we’re said to be accessing the array at
index 5, yet retrieving the value stored at position 6.

This is because indexing begins at zero (0)! When you supply an index/subscript value of 5, you’ll
actually receive the sixth item in the array.

As you may recall from Chapter 7, array indexing begins at zero (0). C and C++ programmers are
already familiar with this approach, although it can sometimes result in problems. If you’re not careful,
you might attempt to access an element beyond the legal range of index values.

In our example, the legal range of index values is 0 to 24. The first item in the array is set or retrieved
using:

myIntegers[0]

while the last item is available with:

myIntegers[24]

If you attempt to access an element with an index of 25, you’re in for trouble:

myIntegers[25]; // ILLEGAL - INDEX OUT OF RANGE!

Although the compiler will let this pass, the runtime system throws an ArrayIndexOutOfBoundsException
exception. This is one of the particularly nice things about both arrays and strings in Java; the system
catches oversights such as this and throws an exception. Rather than slipping through to the customer’s
hands, this bug is caught the first time the line of code is executed.

At times, you may want all items in an array to be set to the same value. In this case, it’s much
easier to use a loop than to set each manually:

int highScores[] = new int[25]; /* declare array of 25


integers */
for (short i=0; i < 25; i++) {
highScores[i] = 9999; /* initialize each array element
to 9999 */
}

file:///F|/books/java%20books/Java%20Bible/ch12/12-12.html (4 of 5)6/26/2005 7:57:08 PM


Java Bible:Strings and Arrays

This approach can be used even in cases where each element is different. As long as you can get the data
you need for each element while inside the body of the loop, you can fill an array with this technique.
For example, you might fill an array with characters typed by the user:

char keystrokes[] = new char[500]; // declare array of 500


characters
char keyChar; // variable to hold keyboard input
for (short i=0; i < 500; i++) { // load up to 500 characters
keyChar = System.in.read(); /* Get character from standard
input stream */
if (keyChar == -1) /* has user attempted to break out of
the process? */
break; // break out of loop
else
keyStrokes[i] = keyChar; // stuff keyboard input into array
}

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-12.html (5 of 5)6/26/2005 7:57:08 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

To retrieve an element in an array, you do the opposite of setting an element. Rather than stuffing an
item into an element, you set a variable equal to that element:

myVariable = myIntegers[4]; // get 5th item in array


myString = myStrings[10]; // get 11th item in array

When retrieving elements in an array, it’s often helpful to subtract 1 from the value representing the item
you want. For example, if you want to retrieve the tenth item in an array, you can use either of the
following approaches:

theNum = myIntegers[9]; // explicit


theNum = myIntegers[10-1]; // using “off by one” technique

Although the latter is less efficient, since the calculation must take place before the element is accessed,
it’s often easier to understand if you haven’t dealt much with arrays. (For more details on this technique,
see Chapter 7.)

To determine the number of elements in an array, use the length variable:

int len = myArray.length; // get the length and assign to


a variable */

Keep in mind that the length used here is a variable, not a method as seen with String and StringBuffer
objects.

Array of Arrays

Although Java doesn’t support multidimensional arrays, it offers essentially the same capability by
allowing us to create an array of arrays:

file:///F|/books/java%20books/Java%20Bible/ch12/12-13.html (1 of 5)6/26/2005 7:57:08 PM


Java Bible:Strings and Arrays

int grid[][] = new int[10][10];


grid[0][0] = 1230;
grid[0][5] = 4;
grid[9][5] = 355;
System.out.println( “Grid value at 0,0 is ” + grid[0][0] ) ;
System.out.println( “Grid value at 0,5 is ” + grid[0][5] ) ;
System.out.println( “Grid value at 9,5 is ” + grid[9][5] ) ;

In the preceding snippet of code, we created two arrays of integer values, both accessible through the
grid variable. Although we created each array with ten elements, they didn’t have to be of the same
dimension:

int grid[][] = new int[15][10];


grid[14][9] = 2265;
System.out.println( “Grid value at 14,9 is ” + grid[14][9] ) ;

We can create as many arrays as necessary, each accessible through the single variable:

int grid2[][][] = new int[15][10][53];


grid2[0][0][0] = 4630;
grid2[4][5][1] = 7345;
grid2[9][5][0] = 35;
grid2[14][9][0] = 6465;
grid2[14][9][4] = 16547;
System.out.println( “Grid2 value at 0,0,0 is ” +
grid2[0][0][0]);
System.out.println( “Grid2 value at 0,5,1 is ” +
grid2[4][5][1]);
System.out.println( “Grid2 value at 9,5,0 is ” +
grid2[9][5][0]);
System.out.println( “Grid2 value at 14,9,4 is ” +
grid2[14][9][4]);

And we can even use an array of arrays in another array of arrays, to give us as many dimensions as
we’d like.

Exceptions

Thanks to arrays being objects, we’re alerted any time something illegal is done with them. Rather than
allowing such activity to slip through the cracks, Java let’s us know right away when our program is
doing something it shouldn’t.

file:///F|/books/java%20books/Java%20Bible/ch12/12-13.html (2 of 5)6/26/2005 7:57:08 PM


Java Bible:Strings and Arrays

The two exceptions you’re most likely to encounter when dealing with arrays are
ArrayIndexOutOfBoundsException and ArrayStoreException.

Whenever an attempt is made to access an item with an index that is out of the legal range, whether that
index is too Iow (negative) or too high, an ArrayIndexOutOfBoundsException is thrown. If, however, you
attempt to store an element in an array that’s of a type different than was declared for the array, you’ll
receive an ArrayStoreException.

Utility Classes (java.util Package)

In addition to the String, StringBuffer, and Array data storage and retrieval mechanisms provided by Java,
we have a number of additional classes to choose from, thanks to the java.util package. These are shown
in Table 12-22.

Table 12-22
Package java.util Interfaces, Classes, and Exceptions

Interfaces

Enumeration Observer

Classes

BitSet Calendar

Dictionary Hashtable

ListResourceBundle Observable

Properties PropertyResourceBundle

Random ResourceBundle

Stack StringTokenizer

Date Vector

file:///F|/books/java%20books/Java%20Bible/ch12/12-13.html (3 of 5)6/26/2005 7:57:08 PM


Java Bible:Strings and Arrays

TimeZone

Exceptions

EmptyStackException NoSuchElementException

In this package, you’ll find classes for dealing with hash tables, stacks, vectors, and bit sets.
While each of these has a specific function, you’ll find they each provide a mechanism for
storing and retrieving data.

Hashtable

A hash table maps keys to values, values which can be any Java object. Whatever object you use as a
key, however, must implement the hashCode() and equals() methods.

In the following snippet of code, we create a hash table to track the amount of stock a store might have.
We use the names of the items in stock as keys, and give each a value:

Hashtable stockLevels = new Hashtable() ;


stockLevels.put( “Radios”, new Integer(4343) );
stockLevels.put( “Bikes”, new Integer(523) );
stockLevels.put( “Chairs”, new Integer(3563) );
stockLevels.put( “Bananas”, new Integer(646) );

// now retrieve the number of Bananas in stock:


Integer n = (Integer)stockLevels.get(“Bananas”);
if (n != null) {
System.out.println( “Yes, we have ”+ n + “ bananas.”);
}

The Hashtable class (see Tables 12-23 and 12-24) is a descendant of the abstract Dictionary class, which
allows for the association of items using keys and values. A particularly powerful feature of hash tables
is their ability to store more than one type of data. While String and StringBuffer objects can contain only
characters, and arrays can have only elements of the same type, we can mix and match the data types
stored in a hash table.

Even though we stored values of Integer objects in the preceding example, each could have been a
different data type. If, for example, we wanted to store a string as the Banana value, we might have
written the following:

file:///F|/books/java%20books/Java%20Bible/ch12/12-13.html (4 of 5)6/26/2005 7:57:08 PM


Java Bible:Strings and Arrays

stockLevels.put(“ Bananas”, new String( “lots o’ naners”) );

However, when retrieving this element, we’d have to get it as a String object. If we attempted to extract it
as an Integer object, as we did earlier, a ClassCastException would be thrown (since a string can’t be cast
into an int). As a result, we would use something like the following to output the value of the Bananas key:

System.out.println(stockLevels.get( “Bananas”));

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-13.html (5 of 5)6/26/2005 7:57:08 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Table 12-23
java.util.Hashtable Constructors

Signature Description

public Hashtable() Constructs a new, empty hash table.

Constructs a new, empty hash table with the specified initial


public Hashtable (int initial Capacity)
capacity.

Constructs a new, empty hash table with the specified initial


Hashtable(int initialCapacity float capacity and the specified toad factor. Throws
loadFactor) IllegalArgumentException if the initial capacity or load factor is less
than or equal to zero.

Table 12-24
java.util.Hashtable Methods

Method Signature Description

Clears the hash table so that it has no more


clear clear()
elements in it.

Clone clone() Creates a clone of the hash table.

public synchronized boolean contains (Object Returns true if the specified object is an element
Contains
value) of the hash table.

file:///F|/books/java%20books/Java%20Bible/ch12/12-14.html (1 of 3)6/26/2005 7:57:09 PM


Java Bible:Strings and Arrays

public synchronized boolean containsKey Returns true if the collection contains an element
ContainsKey
(Object key) for the key.

Elements public synchronized Enumeration elements() Returns an enumeration of the elements.

Gets the object associated with the specified key


Get public synchronized Object get(Object key)
in the hash table.

Returns true if the hash table contains no


IsEmpty public boolean isEmpty()
elements.

Keys public synchronized Enumeration keys() Returns an enumeration of the hash table’s keys.

public synchronized Object put(Object key, Puts the specified element into the hash table,
Put
Object value) using the specified key.

Rehashes the content of the table into a bigger


Rehash protected void rehash()
table.

public synchronized Object remove(Object


Remove Removes the element corresponding to the key.
key)

Returns the number of elements contained in the


Size public int size()
hash table.

ToString public synchronized String toString() Converts to a rather lengthy string.

Vectors

Although arrays are nice and convenient to use, sometimes you need the ability to grow them. However,
as you know, arrays must be dimensioned to a certain size before they are used. And once set, you can’t
change that dimension.

Vectors, on the other hand (see Tables 12-25, 12-26, and 12-27), are growable arrays. Rather than being
constrained to a specific number of elements, you can expand them as needed. In the following example,
we’ll create an empty Vector and add two elements to it:

file:///F|/books/java%20books/Java%20Bible/ch12/12-14.html (2 of 3)6/26/2005 7:57:09 PM


Java Bible:Strings and Arrays

Vector myVector = new Vector(); // create a vector


String myString = “Obla-de, obla-da”; // any ’ol String
Button myButton = new Button( “life goes on” ); // a Button

/* Add objects to our vector: */


myVector.addElement(myString);
myVector.addElement(myButton);

/* Now retrieve the button (notice the cast): */


anotherButton = (Button) myVector.lastElement();

Notice how we managed to cram a Button object and a String object into the Vector object? Anything you
put into a vector is first converted into a plain vanilla object, meaning you can put anything you’d like
into it. But in order to get something out, you have to know what to cast it to! This is seen in the last line
of the preceding code, where we retrieve the last item as a Button; because it was a Button object going in,
we need to cast it to a Button object coming out.

You can take a great deal of work off the runtime system by creating your vectors with an
initial storage capacity; if you don’t, each new element that is added forces the Vector to
expand—a significant effort on Java’s part and one to avoid if at all possible.

Table 12-25
java.util.Vector Constructors

Signature Description

public Vector() Constructs an empty vector.

Constructs an empty vector with the specified storage


public Vector(int initialCapacity)
capacity.

public Vector(int initialCapacity, int capacity Constructs an empty vector with the specified storage
Increment) capacity and the specified capacity increment.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-14.html (3 of 3)6/26/2005 7:57:09 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Table 12-26
java.util.Vector Methods

Method Signature Description

public final synchronized void addElement(Object Adds the specified object as the last
addElement
obj) element of the vector.

Returns the current capacity of the


Capacity public final int capacity()
vector.

Clones this vector. Elements are not


Clone public synchronized Object clone()
cloned.

Returns true if the specified object is a


Contains public final boolean contains (Object elem)
value of the collection.

public final synchronized void copyInto(Object Copies the elements of this vector
CopyInto
AnArray[] ) into the specified array.

public final synchronized Object elementAt(int Returns the element at the specified
ElementAt
index) index.

Returns an enumeration of the


Elements public final synchronized Enumeration elements()
elements.

public final synchronized void ensureCapacity(int Ensures that the vector has at least
Ensure Capacity
minCapacity) the specified capacity.

file:///F|/books/java%20books/Java%20Bible/ch12/12-15.html (1 of 4)6/26/2005 7:57:09 PM


Java Bible:Strings and Arrays

Returns the first element of the


First Element public final synchronized Object firstElement()
sequence.

Searches for the specified object,


IndexOf public final int indexOf(Object elem) starting from the first position, and
returns an index to it.

Searches for the specified object,


public final synchronized int indexOf(Object elem,
IndexOf starting at the specified position, and
int index)
returns an index to it.

public final synchronized void insertElementAt Inserts the specified object as an


Insert ElementAt
(Object obj, int index) element at the specified index.

Returns true if the collection contains


IsEmpty public final boolean isEmpty()
no values.

Returns the last element of the


LastElement public final synchronized Object lastElement()
sequence.

Searches backwards for the specified


LastIndexOf public final int lastIndexOf(Object elem) object, starting from the last position,
and returns an index to it.

Searches backwards for the specified


public final synchronized int lastIndexOf(Object
LastIndexOf object, starting from the specified
elem, int index)
position, and returns an index to it.

RemoveAll public final synchronized void removeAll Elements


Removes all elements of the vector.
Elements ()

public final synchronized boolean removeElement Removes the element from the
Remove Element
(Object) vector.

public final synchronized void removeElementAt(int Deletes the element at the specified
Remove ElementAt
index) index.

file:///F|/books/java%20books/Java%20Bible/ch12/12-15.html (2 of 4)6/26/2005 7:57:09 PM


Java Bible:Strings and Arrays

public final synchronized void setElementAt(Object Sets the element at the specified
Set ElementAt
obj, int index) index to be the specified object.

SetSize public final synchronized void setSize(int newSize) Sets the size of the vector.

Returns the number of elements in


Size public final int size()
the vector.

ToString public final synchronized String toString() Converts the vector to a string.

Trims the vector’s capacity to the


TrimToSize public final synchronized void trimToSize()
appropriate size.

Table 12-27
java.util.Vector Variables

Variable Signature Description

capacityIncrement protected int capacityIncrement The size of the increment.

ElementCount protected int elementCount The number of elements in the buffer.

ElementData protected Object elementData The buffer where elements are stored.

Stacks

A common data storage mechanism used by many programmers is the stack (see Table 12-28), which
allows you to push() objects onto it and pop() objects off when they need to be retrieved. Stacks follow a
Last-In-First-Out (LIFO) ordering, meaning the last object you push() onto the stack will be the first one
you receive when you call pop().

Table 12-28
java.util.Stack Constructor, Methods, and Variables

file:///F|/books/java%20books/Java%20Bible/ch12/12-15.html (3 of 4)6/26/2005 7:57:09 PM


Java Bible:Strings and Arrays

Constructor Signature Description

Stack public Stack() Creates a new Stack object.

Methods Signature Description

empty public boolean empty() Returns true if the stack is empty.

Peek public Object peek() Peeks at the top of the stack.

Pop public Object pop() Pops an item off the stack.

Push public Object push (Object item) Pushes an item onto the stack.

Search public int search (Object item) Sees if an object is on the stack.

The Stack class is a subclass of Vector, meaning you don’t have to worry about how many items a Stack
object will contain. You can simply create one and begin using it without worrying about how many
items you’ll eventually push() onto it.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-15.html (4 of 4)6/26/2005 7:57:09 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

StringTokenizer

At times, you’ll need to retrieve the chunks of information stored in a String object. Such chunks, or
tokens, must each be separated by a delimiter, such as a comma or a space. When you have such
elements in a string, you can retrieve them using the StringTokenizer class.

For example, suppose you’ve stored a series of words into a string, as we’ve done in earlier examples:

String myString = “There once was a mouse from Nantucket”;

Since each of the words is separated by a space, you could retrieve them as follows:

StringTokenizer tokens = new StringTokenizer(myString);


while (tokens.hasMoreTokens()) {
System.out.println(tokens.nextToken());
}

When executed, the preceding code would output each word in the string on its own line:

There
once
was
a
mouse
from
Nantucket

Since the default delimiter for StringTokenizer is a space, we didn’t have to do anything special to retrieve
these words. If we were dealing with a delimiter other than a space, we could specify that delimiter
when creating the StringTokenizer object, or when reading tokens.

Resource bundles

file:///F|/books/java%20books/Java%20Bible/ch12/12-16.html (1 of 4)6/26/2005 7:57:09 PM


Java Bible:Strings and Arrays

New to the jav.util package in JDK 1.1 is the concept of resource bundles. You use the
ResourceBundle classes to define sets of localized resources that can be loaded dynamically
based on the location the program is running. For example, text, images, and menus can be
stored and retrieved from a resource bundle stream. While a ResourceBundle class is provided, it
is not directly used. The ListResourceBundle and PropertyResourceBundle classes are used to access
resource bundle streams. The ListResourceBundle class (see Table 12-29) is used to access
resources as a list, while the PropertyResourceBundle class (see Table 12-30) is used to access
resources through a property key. I discuss streams and storing objects on streams in more
detail in Chapter 13.

Table 12-29
java.util.ListResourceBundle

Constructor Signature Description

ListResource
ListResourceBundle() Creates a list resource bundle
Bundle

Method Signature Description

Enumerates the keys available in the resource


getKeys Enumeration getKeys()
bundle

Object handleGet Object(String Gets the object with the specified key from the
HandleGet Object
key) resource bundle

Table 12-30
java.util.PropertyResourceBundle

Constructor Signature Description

Property Resource PropertyResource Bundle(InputStream Creates a property resource bundle that


Bundle stream) reads from the specified stream

Method Signature Description

file:///F|/books/java%20books/Java%20Bible/ch12/12-16.html (2 of 4)6/26/2005 7:57:09 PM


Java Bible:Strings and Arrays

Enumerates the keys available in the


getKeys Enumeration getKeys()
resource bundle

Gets the object with the specified key


HandleGet Object Object handleGet Object(String key)
from the resource bundle

Miscellany

In addition to the various data storage and retrieval classes we’ve seen, the java.util package
includes others that may be of use.

For example, you might consider the BitSet class if ever you require a growable storage mechanism for
bits. If you’re dealing with streams and need to include the functionality of a hash table, you’ll want to
take a look at the Properties() class, which allows you to create a hash table that can be saved and loaded
from a stream.

Finally, this package features a few classes that don’t have anything to do with saving and retrieving
your own data: Calendar, Date, Random, and TimeZone. The Calendar and TimeZone classes are new to JDK
1.1. The constructors, methods, and variables for these classes are listed in Tables 12-31 through 12-38.

Table 12-31
Java.util.Date Constructors

Signature Description

publicDate() Creates today’s date/time.

public Date(long date) Creates a date.

public Date(int year, int month, int date) Creates a date.


public Date(int year, int month, int date, int hours, int
Creates a date.
minutes)

public Date(int year, int month, int date, int hours, int
Creates a date.
minutes, int sec)

file:///F|/books/java%20books/Java%20Bible/ch12/12-16.html (3 of 4)6/26/2005 7:57:09 PM


Java Bible:Strings and Arrays

Creates a date from a string, according to the syntax


public Date(String s)
accepted by parse().

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-16.html (4 of 4)6/26/2005 7:57:09 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Table 12-32
java.util.Date Methods

Method Signature Description

public static longUTC (int year, int month, 1 2


UTC Calculates a UTC value from YMDHMS
int date, int hrs, int min, int sec)

Checks whether this date comes after the


After public boolean after (Date when)
specified date.

Checks whether this date comes before the


Before public boolean before (Date when)
specified date.

Compares this object against the specified


Equals public boolean equals (Object obj)
object.

GetDate public int getDate() Returns the day of the month.

GetDay public int getDay() Returns the day of the week.

GetHours public int getHours() Returns the hour.

GetMinutes public int getMinutes() Returns the minute.

GetMonth public int getMonth() Returns the month.

file:///F|/books/java%20books/Java%20Bible/ch12/12-17.html (1 of 4)6/26/2005 7:57:10 PM


Java Bible:Strings and Arrays

GetSeconds public int getSeconds() Returns the second.

Returns the time in milliseconds since the


GetTime public long getTime()
epoch.

GetTimezone Returns the time zone offset in minutes for the


public int getTime zoneOffset()
Offset current locale that is appropriate for this time.

GetYear public int getYear() Returns the year after 1900.

HashCode public int hashCode() Computes a hash code.

Given a string representing a time, parses it


Parse public static long parse(String s)
and returns the time value.

SetDate public void setDate(int date) Sets the date.

SetHours public void setHours (int hours) Sets the hours.

SetMinutes public void setMinutes (int minutes) Sets the minutes.

SetMonth public void setMonth (int month) Sets the month.

SetSeconds public void setSeconds (int Seconds) Sets the seconds.

SetTime public void setTime (long time) Sets the time.

SetYear public void setYear(int year) Sets the year.

Converts a date to a string, using the Internet


ToGMTString public String toGMT String() 3
GMT conventions.

Converts a date to a string, using the locale


ToLocale String public String toLocale String()
conventions.

file:///F|/books/java%20books/Java%20Bible/ch12/12-17.html (2 of 4)6/26/2005 7:57:10 PM


Java Bible:Strings and Arrays

Converts a date to a string, using the UNIX


ToString public String toString()
time conventions.

1
UTC: Coordinated Universal Time
2
ymdhms: Year, Month, Day, Hour, Minute, Second
3
GMT: Greenwich Mean Time

The Date class allows us to retrieve the current date and supports a number of methods for dealing with
dates and times:

Date today = new Date();


System.out.println( “The date today is: ” + today);

In the current release of Java, Date doesn’t properly represent days prior to January 1, 1970.
This is expected to be resolved in a future release of the language.

The Calendar class (see Tables 12-33, 12-34, and 12-35) is used to perform date and time arithmetic. It
also includes methods used to convert dates and times between binary representations used by the Date
class and standard units—such as minutes, hours, days, weeks, months, and years—that are more
understandable to people.

Table 12-33
java.util.Calendar Constructors

Signature Description

Creates an empty Calendar object using the default time zone and
Calendar()
locale.

Calendar (TimeZone zone, Locale


Creates a calendar for a specific time zone and locale.
aLocale)

file:///F|/books/java%20books/Java%20Bible/ch12/12-17.html (3 of 4)6/26/2005 7:57:10 PM


Java Bible:Strings and Arrays

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-17.html (4 of 4)6/26/2005 7:57:10 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Table 12-38
java.util.Random Methods

Methods Signature Description

Generates a pseudorandom, uniformly distributed


nextDouble() public doublenext Double()
double value between 0.0 and 1.0.

Generates a pseudorandom, uniformly distributed


nextFloat() public floatnext Float()
float value between 0.0 and 1.0.

Generates a pseudorandom, Gaussian-distributed


nextGaussian public synchronized doublenext Gaussian
double value with mean 0.0 and standard deviation
() ()
1.0.

Generates a pseudorandom, uniformly distributed


nextInt() public intnextInt()
int value.

Generates a pseudorandom, uniformly distributed


nextLong() public int next Long()
long value.

Sets the seed of the random number generator,


setSeed(long) public int setSeed (long)
using a single long seed.

The nextGaussian() method returns a Gaussian distributed double that is centered at 0.0 with a
standard deviation of 1.0, which is also known as a bell curve.

file:///F|/books/java%20books/Java%20Bible/ch12/12-21.html (1 of 3)6/26/2005 7:57:10 PM


Java Bible:Strings and Arrays

The java.lang.Math class also defines a random-number generator that returns a double-precision
floating-point value between 0.0 and 1.0:

double random();

In both cases, the values returned aren’t considered truly random, since they tend to repeat themselves
after a period of time.

With java.util. Random, you can change the generator’s seed value as needed. By supplying the same seed,
the sequence of generated numbers will be the same.

Summary

Now you understand how to add strings, arrays, and other fundamental programming structures to your
Java applications. You’re well on your way now to creating your own complex Java programs. Key
concepts to remember from this chapter include these:

• Java strings aren’t like the ones we’re accustomed to in C and C++. In those languages, strings
are simply an array of null-terminated characters. Java strings, however, are actually objects
defined by the String class. As a result, they feature a number of methods that are used to access
their contents. With Java, strings are first-class objects that support a well-defined set of methods.
• Java provides two distinct string classes: String and StringBuffer. The String class is used to create
String objects which are immutable; their contents can’t be altered once characters have been
stored in them. StringBuffer, on the other hand, is specifically for strings that are mutable, or able
to be changed even after characters have been stored in them.
• In Java, arrays are truly first-class objects. Not only are they impossible to subclass, you won’t
even find a class definition for them. Instead, Java knows internally about arrays and how to treat
them, just as it knows how to deal with primitive data types without offering a class for each
(keep in mind that type wrappers for primitives are different from the primitives themselves;
there are type wrapper classes, but no primitive classes). Unlike String and StringBuffer objects,
which can contain only character data, arrays are capable of holding any type of data we need,
even other arrays. The only restriction is that each element in the array must be of the same type.
• The Hashtable class is a descendant of the abstract Dictionary class, which allows for the
association of items using keys and values. A particularly powerful feature of hash tables is their
ability to store more than one type of data. While String and StringBuffer objects can contain only
characters, and arrays can have only elements of the same type, we can mix and match the data
types stored in a hash table.
• Vectors are growable arrays. Rather than being constrained to a specific number of elements,
you can expand them as needed.
• A common data storage mechanism used by many programmers is the stack, which allows you
to push() objects onto it and pop() objects off when they need to be retrieved. Stacks follow a Last-
In-First-Out (LIFO) ordering, meaning the last object you push() onto the stack will be the first

file:///F|/books/java%20books/Java%20Bible/ch12/12-21.html (2 of 3)6/26/2005 7:57:10 PM


Java Bible:Strings and Arrays

one you receive when you call pop().


• At times, you’ll need to retrieve the chunks of Information stored in a String object. Such
chunks, or tokens, must each be separated by a delimiter, such as a comma or a space. When you
have such elements in a string, you can retrieve them using the StringTokenizer class.
• New to the jav.util package in JDK 1.1 is the concept of resource bundles. You use the
ResourceBundle classes to define sets of localized resources that can be loaded dynamically based
on the location the program is running. For example, text, images, and menus can be stored and
retrieved from a resource bundle stream.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-21.html (3 of 3)6/26/2005 7:57:10 PM


Java Bible:Strings and Arrays

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

The following example demonstrates how to create a Calendar object, specify a date and time, and
perform some simple arithmetic:

Calendar Date1 = new Calendar();


Date1.set(1998,1,1,11,5); /* Set the date to 1/1/1998
and time to 11:05 */
System.out.println( “The current time is ” +
Date1.get(Date1.HOUR) + “:” +
Date1.get(Date1.MINUTE) );
Date1.add(3, Date1.HOUR); // Add 3 hours to the time
System.out.println(“The new time is ” +
Date1.get(Date1.HOUR) + “:” +
Date1.get(Date1.MINUTE) );

The TimeZone class (see Table 12-36) is used to represent geographical time zones.

Table 12-36
java.util.TimeZone Constructor and Methods

Methods Signature Description

TimeZone TimeZone () Creates a time zone object

getAvailableIDs IDs(int Gets the available time zone IDs for


String[] getAvailable
rawOffset) the given time zone offset

getAvailableIDs String[] getAvailable IDs() Gets all of the IDs supported

getDefault TimeZone getDefault() Gets the current default time zone

file:///F|/books/java%20books/Java%20Bible/ch12/12-20.html (1 of 3)6/26/2005 7:57:11 PM


Java Bible:Strings and Arrays

Gets the TimeZone for the specified


getTimeZone TimeZone getTimeZone (String ID)
ID

setDefault void setDefault(Time Zone zone) Sets the default time zone

clone Object clone() Clones the current TimeZone object

getID String getID() Gets the ID of the current time zone

int getOffset(int era, int year, int month, Gets the time zone offset, for
getOffset int day, int dayOfWeek, int current date, modified in case of
milliseconds) daylight savings time

Gets the unmodified offset, not


getRawOffset int getRawOffset()
modified for daylight savings time

Determines if the date is using


inDayLightTime boolean inDaylight Time(Date date)
daylight savings time

setID void setID(String ID) Sets the current time zone ID

Sets the base time zone offset to


setRawOffset void setRawOffset(int offsetMillis)
GMT (Greenwich Mean Time)

Determines if the time zone uses


useDaylightTime boolean useDaylight Time()
daylight savings time

You can use the TimeZone class to determine the current time zone by calling the getDefault method, or to
enumerate the available time zones. The Calendar class is the primary user of TimeZone objects.

The TimeZone class can be used to retrieve the current time zone and its attributes. The following
example demonstrates how to retrieve the current time zone and determine if it uses daylight savings
time:

TimeZone tz = new TimeZone();


if(tz.useDaylightTime()) {

file:///F|/books/java%20books/Java%20Bible/ch12/12-20.html (2 of 3)6/26/2005 7:57:11 PM


Java Bible:Strings and Arrays

System.out.println(“Daylight savings time is used” );


} else {
System.out.println(“Daylight savings time is NOT” +
“used”);
};

The Random class (see Tables 12-37 and 12-38) is used to create randomly generated numbers:

Random myRand = new Random();


int aRandomint = myRand.nextInt();
long aRandomLong = myRand.nextLong();
float aRandomFloat = myRand.nextFloat();
double aRandomDouble = myRand.nextDouble();
double aRandomGaussian = myRand.nextGaussian();

In this example, we’ve created a Random object and extracted a variety of random values from it.

Table 12-37
java.util.Random Constructors

Signature Description

public Random () Creates a new random-number generator.

public Random(long seed) Creates a new random-number generator using a single long seed.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch12/12-20.html (3 of 3)6/26/2005 7:57:11 PM


Java Bible:Input/Output: Java Streams

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

CHAPTER 13
Input/Output: Java Streams
In This Chapter

About streams

Standard system streams (java.lang.System)

java.io streams

Filtered streams

Object serialization

More I/O

Streams can be thought of as flowing buffers of data, providing our programs with a relatively easy
mechanism for reading and writing data. You may already know of at least one way of sending data
using streams; you’ve been using the system input stream all along. As you’ll see throughout this
chapter, System.out is only a very small way in which to use streams. In this chapter, you’ll also learn
how to create and use input and output (I/O) streams. You will also learn about FilterInputStream and
FilterOutputStream, which provide an enhanced I/O mechanism for streams, and object serialization which
allows any Java object to be written to an output stream, and then recreated later by reading the object
back from the input stream.

About Streams

Streams are a conduit for sending and receiving information in Java programs. When sending a stream
of data, it is said that we are writing a stream. When receiving a stream of data, we are said to be
reading a stream.

file:///F|/books/java%20books/Java%20Bible/ch13/13-01.html (1 of 4)6/26/2005 7:57:12 PM


Java Bible:Input/Output: Java Streams

Whenever a stream is being written or read, it blocks all other threads. This is not a major issue,
however, if you use threads. As you’ll see in Chapter 14, you can place input and output streams in a
separate process to allow other program execution to continue while these processes are reading and
writing. If an error occurs when reading or writing a stream, an IOException is thrown. As a result, you
must surround your stream statements with a try-catch clause, in order to handle any of the potential
exceptions (for details on exceptions, see Chapter 10).

Java has not only a standard system stream, but also a more complex and complete set of streams
dedicated entirely to input/output: the java.io package. Before we get into this package, however, a look
at standard system input/output will set the stage.

Standard System Streams (java.lang. System)

The java.lang.System class defines a standard input and a standard output stream. So far, we’ve been using
output streams to output data to the display monitor in our applications.

There are three types of standard streams:

• The standard output stream (accessed through the System.out class variable); this is typically the
display, or the monitor, of the machine on which your program is running, and is normally used
to communicate textual information with the user.
• The standard input stream (accessed through the System.in class variable); this usually comes
from the keyboard, and is often used for reading character data.
• The standard error stream (accessible through the System.err class variable).

Let’s take a look at each.

System’s class constructor is private, preventing the class from being instantiated. It also cannot
be subclassed, since it has been declared as final (with all methods and variables specified as
static). Since System methods and variables are static, you simply refer to them directly, as
we’ve been doing throughout the book. For details on the private, final, and static modifiers, see
Chapter 11.

Standard output (System.out)

So far, this book has used the standard output in all of its Java applications. You haven’t, however, seen
how to use standard output in applets, since we paint and draw information upon the applet canvas rather
than sending output directly to System.out. Standard out, as you may recall, is often the display or the
monitor, and is used in applications to output information directly to the screen. With applets, we
already have a surface to draw on; with applications, however, we typically output information to the
command line. This is done by sending either a print() or println() method to the System.in variable:

file:///F|/books/java%20books/Java%20Bible/ch13/13-01.html (2 of 4)6/26/2005 7:57:12 PM


Java Bible:Input/Output: Java Streams

System.out.print (“Hello World”); // print


System.out.println(“Hello World”); // print line

The print() method sends information into a buffer. This buffer is not flushed until an end-of-line
character is sent via print(), or the println() method is called. As a result, all of the information is printed
on one line until an end-of-line character is encountered or the println() method is invoked. By contrast,
println() takes the information provided and prints it on a line followed by a carriage-return/line feed.

Standard input (System.in)

The second standard stream is System.in, which hasn’t been used yet in this book; however, there’s no
time like the present.

Let’s assume we wanted to read information from the keyboard. In an applet, we already know how to
do this: We would test for keyDown events in either an action() or handleEvent() method. In an application,
we don’t usually have the luxury of dealing with those types of events (unless a GUI is created for the
application; see Part IV for details). What we do have, however, is access to the standard input stream by
sending the read() method to the System.in variable:

int keyInput;
int i = 0;
while ((keyInput = System.in.read()) != -1)
i++;
System.out.println(i + “ = ” + keyInput);
} catch (IOException e) { . . . }

As you can see, this fragment of code simply reads in character input from the keyboard, incrementing
the counter each time through, outputting the character that is read to standard out, along with the
character count, and then repeating the process. This loop can only be broken when the read returns -1.
With read(), a -1 is returned only when an end-of-line character is received.

End-of-line characters are generated in different ways for UNIX and DOS/Windowsbased
machines. With UNIX, Ctrl+D (AD) must be used (holding down the Control and D keys at
the same time). in DOS/Windows environments, Ctrl+Z (^Z) is used.

Standard error (System.err)

Although you’ll use System.out most of the time, you may wish to use the standard error output stream,
rather than sending output to System.out, as we’ve done above. This is because the system output may be
redirected from the current device (typically the monitor) to another device (such as a file).

file:///F|/books/java%20books/Java%20Bible/ch13/13-01.html (3 of 4)6/26/2005 7:57:12 PM


Java Bible:Input/Output: Java Streams

The difficulty in using this type of stream occurs when you have an error message to display to users; it
may never get to them. After all, how would they be able to look at an error message if it’s being output
to a file instead of the screen? To ensure output goes to the display screen, you could simply send your
data to the system-error variable like this:

System.err.println(“Warning!”);

Now the data doesn’t run the risk of being “hidden” when output; it is always sent to the display.

java.io Streams

Although the system streams are very handy, they really aren’t robust enough to be of much use when
dealing with substantial I/O. For the full power of streams, we need to turn to the java.io package. As you
can see from the diagram in Figure 13-1, this package supports two streams—one input and one output
stream—from which all other streams are subclassed.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch13/13-01.html (4 of 4)6/26/2005 7:57:12 PM


Java Bible:Input/Output: Java Streams

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

java.io.InputStream and java.io.OutputStream are actually abstract classes. They are implemented in the
subclasses shown in Figure 13-1. However, they are the parent classes of all other streams, and as such,
they have a common element that all streams share. To better understand the types of streams that are
supported by the java.io package, we’ll need to take a closer look at the InputStream and OutputStream
classes.

InputStream

InputStream is an abstract class that defines how data is received. Where this data comes from really
doesn’t matter; what’s important is that it is accessible. In fact, the data can come from just about
anywhere. It may come from the keyboard, from a file on your local file system, or from across the
Web—the program doesn’t care. This is the strength of streams: It isn’t necessary to know where the
data is coming from or where it’s going in order to use it.

Figure 13-1: All Java streams descend from one of two parent classes in the java.io package:
InputStream or OutputStream.

InputStream methods

The InputStream object provides a number of methods which allow you to create, read, and process input
streams. Table 13-1 lists a few methods that operate on input streams, and how they might be used.

file:///F|/books/java%20books/Java%20Bible/ch13/13-02.html (1 of 3)6/26/2005 7:57:12 PM


Java Bible:Input/Output: Java Streams

Table 13-1
Class java.io.InputStream

Method Signature Description

read public abstract int read() throws IOException Reads a byte of data. This method blocks
if no input is available.
Returns the byte read, or -1 if the end of
the stream is reached.
Throws IOException if an I/O error has
occurred.

read public int read(byte b[]) throws IOException Reads into an array of bytes. This method
blocks until some input is available.
Returns the actual number of bytes read; is
returned when the end of the stream is
reached. Throws IOException if an I/O error
has occurred.
Parameter: b-buffer into which the data is
read.

read public int read(byte b[], int off, int len) throws Reads into an array of bytes. This method
IOException blocks until some input is available.
Parameters:
b-buffer into which the data is read
off-start offset of the data
len-maximum number of bytes read
Returns the actual number of bytes read; -
1 is returned when the end of the stream is
reached.
Throws IOException if an I/O error has
occurred.

available public int available () throws IOException Returns the number of bytes that can be
read without blocking.
Returns the number of available bytes.

skip public long skip(long n) throws IOException Skips n bytes of input.

file:///F|/books/java%20books/Java%20Bible/ch13/13-02.html (2 of 3)6/26/2005 7:57:12 PM


Java Bible:Input/Output: Java Streams

Parameter: n-number of bytes to be


skipped
Returns the actual number of bytes
skipped.
Throws IOException if an I/O error has
occurred.

mark public synchronized void mark(int readlimit) Marks the current position in the input
stream. A subsequent call to reset()
repositions the stream at the last marked
position so that subsequent reads can re-
read the same bytes. The stream promises
to allow readlimit bytes to be read before
the mark position is invalidated.
Parameter: readlimit-maximum limit of
bytes allowed to be read before the mark
position becomes invalid.

reset public synchronized throws IOException void reset Repositions the stream to the last marked
() position.
Throws IOException if the stream has not
been marked or if the mark has been
invalidated (see note below).

markSupported public boolean markSupported() Returns a boolean indicating whether or not


this stream type supports mark/ reset.
Returns true if this stream type supports
mark/reset; false otherwise.

close public void close() throws IOException Closes the input stream. Must be called to
release any resources associated with the
stream.
Throws IOException if an I/O error has
occurred.

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch13/13-02.html (3 of 3)6/26/2005 7:57:12 PM


Java Bible:Input/Output: Java Streams

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

Stream marks are intended to be used in situations where you need to read ahead a little to see
what’s in the stream. Often, this is most easily done by invoking some general parser. If the
stream is of the type handled by the parser, it just chugs along happily. If the stream is not of
that type, the parser should toss an exception when it fails—which, if it happens within
readlimit bytes, allows the outer code to reset the stream and try another parser.

read()

We see three read() methods, each of which takes a different set of parameters; the most basic is the one
we’ve been using with the system input stream. This read() method simply reads one byte from the input
stream. The other two methods let you specify either an array of bytes or a portion of an array of bytes:

anyStream.read(); // reads one byte


byte byteArray = new byte[2048];
anyStream.read(byteArray[]); // reads into an array of bytes
anyStream.read(byteArray[], 25, 100); // reads into a portion of an
array

In the second example, read() tries to fill up the entire array we’ve passed to it. If it’s not successful,
meaning there were fewer characters in the stream than there were indexes in the array, -1 is returned.

However, -1 doesn’t indicate an error; it simply lets us know that the process didn’t run all the way
through. If an actual error had occurred, an IOException would have been thrown.

In the third example, we specify the location in the array to begin writing the stream, along with how
many positions in the array to actually fill. This is useful when we have an array that we want partially
filled with data. We can begin reading data at any index and continue for the remainder of the array, or
just a portion of it.

available()

The available() method enables you to find out how many bytes there are in a stream that can be read

file:///F|/books/java%20books/Java%20Bible/ch13/13-03.html (1 of 4)6/26/2005 7:57:13 PM


Java Bible:Input/Output: Java Streams

without blocking. Unfortunately, a number of the stream classes don’t support available(). As a result,
unless you’re certain that the stream you’re using supports available(), you can’t guarantee this method
will return a valid number. Sometimes, zero is returned; at other times, the actual number of bytes in the
stream is returned. It’s a good idea to avoid using available(), if possible, unless you’re certain of exactly
what you’re doing.

skip()

At times, you’ll want to skip over a number of bytes in a stream. This is easy enough; just invoke the skip
() method. Supply it with a numeric parameter, telling it how many bytes to skip over, and the stream
begins reading again at the position after that skip. This assumes, of course, that you are in the process
of reading a stream:

anyStream.skip(200); // skip over next 200 bytes

Although you may be tempted to provide an actual long value to the skip() method, you should
keep the range of your values to those of an int. This is because Java actually converts your
long integer into an int. In future releases, skip() may indeed use a long, but for now, assume that
it uses an int.

mark() and reset()

At times, you may want to revisit a particular position in a stream, and return to read there once again.
This is possible by marking that position in the stream using the mark() method. When you want to
return, simply call reset():

anyStream.mark(256); // mark the 256th byte


... do something ...
anyStream.reset(); // return to the 256 byte, and begin from there

As you can see in the preceding example, we’ve marked byte 256 in the stream. When we call reset() on
that stream, we begin reading at position 256. You should note, however, that if we read more than 256
characters between the time that we’ve set the mark() and called reset(), a problem occurs.

This is because the stream must keep track of the number of bytes you supply in mark(). If you read more
than that number, it can’t guarantee you can go back to the same position.

Suppose you read beyond the 256 characters; that is, you read 257 characters after setting the mark. The
memory allocated for that mark may not be available, in which case, when you call reset(), an exception
may be thrown.

file:///F|/books/java%20books/Java%20Bible/ch13/13-03.html (2 of 4)6/26/2005 7:57:13 PM


Java Bible:Input/Output: Java Streams

Keep this in mind whenever you use mark() and reset(). Make certain that, once you mark a stream, you
don’t read more characters than you marked, minus one. For instance, if you set a mark at 1000, read
only up to 999 more characters before calling reset().

Not all stream types support mark(). In order to test whether it can, call the markSupported() method:

anyStream.markSupported(); /* returns true if mark()


is supported */

close()

Streams support the notion of being closed; that is, when you’re done with them, you can close them
down. This is easily done by sending the close() method to a stream:

anyStream.close (); // close this stream

Although the garbage collector in Java is supposed to take care of this for you, it’s a good idea to do it
yourself. Since you can’t guarantee when the garbage collector will come around and close an unused
stream for you, you might attempt to reopen it before the garbage collector has finished with it.

By closing the stream yourself, you guarantee it to be closed. The next time you try to open it, you won’t
run into this potential problem:

try {
... work with the stream ...
} catch (Exception e) {
anyStream.close(); // close this stream
}

From the snippet just given, you can see that the best place to close a stream may be the finally clause in
a try-catch clause. The finally clause is always a good way to close a stream, because it’s the last thing
called in a try-catch clause. And, as you know, since streams may generate or throw off exceptions, you
need the try-catch clause anyway. So, why not simply close a stream in the finally clause when you’re
done using it? It’s a good, safe way to ensure that your stream is closed before going on with the rest of
your program.

In most of these examples, I haven’t bothered to use the try-catch clause. Since working with
streams can result in exceptions being thrown, you’ll need to write your stream code using
exception handlers.

file:///F|/books/java%20books/Java%20Bible/ch13/13-03.html (3 of 4)6/26/2005 7:57:13 PM


Java Bible:Input/Output: Java Streams

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch13/13-03.html (4 of 4)6/26/2005 7:57:13 PM


file:///F|/books/java%20books/Java%20Bible/ch13/images/13-01.jpg

file:///F|/books/java%20books/Java%20Bible/ch13/images/13-01.jpg6/26/2005 7:57:13 PM
Java Bible:Input/Output: Java Streams

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

InputStreamReader

JDK 1.1 has introduced a new set of classes—Reader and Writer—which handle text-based
input/output more efficiently than the byte-stream counterparts. They are used in basically the
same manner as their byte-stream counterparts. The Reader and Writer classes automatically
provide the appropriate Unicode character conversions—making your applications and applets
more portable between locales. The InputStreamReader (see Table 13-2) class reads bytes from a
data source and converts them to their appropriate Unicode character counterparts.

Table 13-2
java.io.InputStreamReader

Constructor Example Description

InputStream public InputStreamReader (InputStream in) Creates an input stream reader that
Reader uses the default character encoding.

InputStream public InputStreamReader (InputStream in, String Creates an input stream that uses the
Reader enc) character encoding specified.

close void close() throws IOException Closes the input stream.

getEncoding String getEncoding() Returns the name of the encoding


currently used.

read int read() throws IOException Reads a single character.

read in read(char[] cbuf. int off, int len) throws Reads len number characters into
IOException buffer cbuf, starting at off.

file:///F|/books/java%20books/Java%20Bible/ch13/13-04.html (1 of 3)6/26/2005 7:57:13 PM


Java Bible:Input/Output: Java Streams

ready boolean ready() throws IOException() Determines whether the input stream
is ready to be read.

OutputStream

The OutputStream class is an abstract class that defines the way in which all streams are written.

OutputStream Methods

The OutputStream object provides methods to create, write, and process output streams. Every type of
stream uses the methods shown in Table 13-3. Let’s take a closer look at each.

Table 13-3
java.io.OutputStream

Methods Example Description

write public abstract void write(int b) throws Writes a byte. This method blocks until the
IOException byte is actually written.
Parameter: b-byte
Throws IOException if an I/O error has occurred.

write public void write(byte b[]) throws IOException Writes an array of bytes. This method blocks
until the bytes are actually written.
Parameter: b-data to be written.
Throws IOException if an I/O error has occurred.

write public void write(byte b[], int off, int len) throws Writes a subarray of bytes.
IOException
Parameters:
b-data to be written.
off-start offset in the data.
len-number of bytes written.
Throws IOException if an I/O error has occurred.

file:///F|/books/java%20books/Java%20Bible/ch13/13-04.html (2 of 3)6/26/2005 7:57:13 PM


Java Bible:Input/Output: Java Streams

flush public void flush() throws IOException Flushes the stream. This writes any buffered
output bytes.
Throws IOException if an I/O error has occurred.

close public void lose() throws IOException Closes the stream. This method must be called
to release any resources associated with the
stream.
Throws IOException if an I/O error has occurred.

write() and flush()

The three write() methods write bytes to a stream. Use the one that makes sense for your program (see the
descriptions in Table 13-3):

• write(int) writes a single byte


• write(byte[]) writes an array of bytes
• write(byte[], int, int) writes a particular section of an array of bytes

You’ll note that these are similar, at least in their parameters, to the read() methods defined in InputStream.
This is no surprise, since OutputStream can be considered the reverse of InputStream: While InputStream
allows you to read bytes in from a stream, OutputStream sends bytes to a stream. Drawing from our
previous InputStream examples, we might use the following to write a stream:

byte myByte = System.in.read(); // read a keyboard character


anOutputStream.write(myByte); // write it to a stream
anOutputStream.write(byteArray); // write array into a stream
anOutputStream.write(byteArray, 25, 100); /* write portion of
an array */
flush()

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch13/13-04.html (3 of 3)6/26/2005 7:57:13 PM


Java Bible:Input/Output: Java Streams

Java Bible
Java by Aaron Walsh, John Fronckowiak
Bible IDG Books, IDG Books Worldwide, Inc.
ISBN: 0764580302 Pub
Date: 05/01/98

Previous Table of Contents Next

The flush() method is used to write bytes that may be in memory to the stream. This may be necessary,
for instance, when a stream is being built up in memory and needs to be flushed out to the disk.

This can also happen when the stream you are creating is being written to the network. In this case,
while the stream may be written to memory, the flush() method will actually send it:

anOutputStream.flush(); // ensure all writing to stream is flushed

close()

After you’ve opened an OutputStream, it’s a good idea to close it. Just as with its InputStream counterpart,
don’t rely on the garbage collector to come around and close it for you. It’s best to explicitly close any
stream you’re using when you’re done:

try {
... work with the stream ...
} finally {
anOutputStream.close(); // close this stream when done
}

OutputStreamWriter

The OutputStreamWriter (see Table 13-4) class writes characters to an output stream, translating the
characters into bytes as specified by the character encoding scheme. This ensures characters are written
in the appropriate format according to the translation scheme specified.

Table 13-4
java.io.OutputStreamWriter

Example Description

file:///F|/books/java%20books/Java%20Bible/ch13/13-05.html (1 of 4)6/26/2005 7:57:14 PM


Java Bible:Input/Output: Java Streams

Public OutputStreamWriter (OutputStream out) Creates an output stream writer that uses the default
character encoding.

Public OutputStreamWriter (OutputStream out, Creates an output stream that used the character encoding
String enc) specified.

Methods Example Description

close void close() throws Closes the output stream.


IOException

flush void flush() throws Flushes the stream.


IOException

write void write(int b) throws Writes a single character.


IOException

write in read(char[] cbuf, int off, int Reads len number characters
len) throws IOException into buffer cbuf, starting at off.

write boolean ready () throws Determines whether the input


IOException() stream is ready to be read.

Special-purpose streams

As you know, the InputStream and OutputStream classes are the parents for all other streams in the java.io
package. They define the basic behavior each stream supports. However, there are a number of special-
purpose streams supported in java.io that allow you to cio specific stream work. Since you already know
how the InputStream and OutputStream methods are used, it’s time to take a look at each of their special-
purpose “children.” (Take a look back at Figure 13-1, where the class hierarchy is laid out.)

File input

One of the most useful things you’ll do with streams is read and write files with them. Two special
classes, FileInputStream and FileOutputStream, make this process a breeze. As you can see in Table 13-5,
there are several constructors — three constructors that allow you to create an input stream from a file.

file:///F|/books/java%20books/Java%20Bible/ch13/13-05.html (2 of 4)6/26/2005 7:57:14 PM


Java Bible:Input/Output: Java Streams

Table 13-5
java.io. FileInputStream Constructors

Signature Description

public FileInputStream (String name) throws Creates input file with the specified name
FileNotFoundException. (name is system-dependent).
Parameter: name - a system-dependent
filename.
Throws IOException if the file is not found.

public FiteInputStream (File fileObj) throws FileNotFoundException Creates input file from the specified file
object.
Parameter: fileObj -file to be opened for
reading.
Throws IOException if the file is not found.

public FileInputStream (FileDescriptor fdescObj) Creates input file from the specified file
descriptor object.
Parameter: fdescObj - valid file descriptor
object.

The first constructor takes a string that is the actual path name of a file. The path name that you provide
is system-dependent. You can use UNIX conventions for UNIX-based files, DOS conventions for DOS
and Windows-based files, and Macintosh conventions for Macintosh-based files; and, as Java is ported
to other platforms, these will each have their own conventions.

However, since Java automatically converts a path to accommodate whatever platform it is running on,
you can use the one most convenient for you (I prefer the UNIX convention, since it requires less typing
and As easy to read):

InputStream myUNIXFile =
newFileInputStream(“/java/aewcode/HelloWorld.java”);

InputStream myDOSFile =
newFileInputStream(“\\java\\aewcode\\HelloWorld.java”);
/* DOS slashes are escaped! (see Files and Directories sidebar) */

file:///F|/books/java%20books/Java%20Bible/ch13/13-05.html (3 of 4)6/26/2005 7:57:14 PM


Java Bible:Input/Output: Java Streams

InputStream myMacFile =
newFileInputStream(“:java:aewcode:HelloWorld.java”);

In addition, you can create a FileInputStream using a FileDescriptor (defined in the java.io.FileDescriptor
class). Once you’ve opened a file, it has what’s known as a descriptor associated with it. You can get the
FileDescriptor for a file you’ve just opened using the getFD() method. Once you have a FileDescriptor, you
can hang onto it and use it to reference the file at a later time:

InputStream myFile =
newFileInputStream(“/java/aewcode/HelloWorld.java”);
FileDescriptor myDesc = myFile.getFD(); // get descriptor
...
inputStream myFile2 = newFileInputStream(myDesc); // new stream

Previous Table of Contents Next

file:///F|/books/java%20books/Java%20Bible/ch13/13-05.html (4 of 4)6/26/2005 7:57:14 PM


Java Bible:Input/Output: Java St