main

Book Cover
SAMS Teach Yourself Programming with Java™ in 24 Hours, FOURTH EDITION
By Rogers Cadenhead
...............................................
Publisher: Sams
Pub Date: September 30, 2005
ISBN: 0-672-32844-5
Pages: 576

Table of Contents | Index
Overview

If you have been wanting to learn Java, check out the newly revised fourth edition of the best-seller Sams Teach Yourself Programming with Java in 24 Hours. This step-by-step tutorial will teach you how to create simple Java programs and applets. Comprised of 24 one-hour lessons, this new edition focuses on key programming concepts and essential Java basics, has been improved by dozens of reader comments, and is reorganized to better cover the latest developments in Java. The book's coverage of core Java programming topics has also been expanded. A great starting point for learning Java, this book is also a great primer to reading sams Teach Yourself Java in 21 Days.


Table of Contents

Book Cover
SAMS Teach Yourself Programming with Java™ in 24 Hours, FOURTH EDITION
By Rogers Cadenhead
...............................................
Publisher: Sams
Pub Date: September 30, 2005
ISBN: 0-672-32844-5
Pages: 576

Table of Contents | Index

Copyright
About the Author
Acknowledgments
Reader Acknowledgements
We Want to Hear from You!
Reader Services
Introduction
Part I. Getting Started
 | Hour 1. Becoming a Programmer
 |  | Choosing a Language
 |  | Telling the Computer What to Do
 |  | How Programs Work
 |  | How Programs Don't Work
 |  | Next Stop: Java
 |  | Workshop: Installing a Java Development Tool
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 2. Writing Your First Program
 |  | What You Need to Write Programs
 |  | Creating the Saluton Program
 |  | Storing Information in a Variable
 |  | Saving the Finished Product
 |  | Compiling the Program into a Class File
 |  | Fixing Errors
 |  | Workshop: Running a Java Program
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 3. Vacationing in Java
 |  | First Stop: Sun Microsystems
 |  | Going to School with Java
 |  | Lunch in JavaWorld
 |  | Watching the Skies at NASA
 |  | Getting Down to Business
 |  | Stopping by Gamelan to Ask Directions
 |  | Workshop: Venturing into Another World
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 4. Understanding How Java Programs Work
 |  | Creating an Application
 |  | Sending Arguments to Applications
 |  | Applet Basics
 |  | Sending Parameters to Applets
 |  | Workshop: Viewing the Code Used to Run Applets
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
Part II. Learning the Basics of Programming
 | Hour 5. Storing and Changing Information in a Program
 |  | Statements and Expressions
 |  | Assigning Variable Types
 |  | Naming Your Variables
 |  | Storing Information in Variables
 |  | Workshop: Using Expressions
 |  | All about Operators
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 6. Using Strings to Communicate
 |  | Storing Text in Strings
 |  | Displaying Strings in Programs
 |  | Using Special Characters in Strings
 |  | Pasting Strings Together
 |  | Using Other Variables with Strings
 |  | Advanced String Handling
 |  | Workshop: Presenting Credits
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 7. Using Conditional Tests to Make Decisions
 |  | Testing a Condition
 |  | if Statements
 |  | if-else Statements
 |  | switch Statements
 |  | The Conditional Operator
 |  | Workshop: Watching the Clock
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 8. Repeating an Action with Loops
 |  | for Loops
 |  | while Loops
 |  | do-while Loops
 |  | Exiting a Loop
 |  | Naming a Loop
 |  | Workshop: Teaching Your Computer a Lesson
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
Part III. WORKING WITH INFORMATION IN NEW WAYS
 | Hour 9. Storing Information with Arrays
 |  | Creating Arrays
 |  | Using Arrays
 |  | Multidimensional Arrays
 |  | Sorting an Array
 |  | Workshop: Array of Prizes, Indeed
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 10. Creating Your First Object
 |  | How Object-Oriented Programming Works
 |  | Objects in Action
 |  | What Objects Are
 |  | Understanding Inheritance
 |  | Building an Inheritance Hierarchy
 |  | Converting Objects and Simple Variables
 |  | Workshop: Creating an Object
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 11. Describing What Your Object Is Like
 |  | Creating Variables
 |  | Creating Class Variables
 |  | Creating Behavior with Methods
 |  | Putting One Class inside Another
 |  | Using the this Keyword
 |  | Workshop: Using Class Methods and Variables
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 12. Making the Most of Existing Objects
 |  | The Power of Inheritance
 |  | Establishing Inheritance
 |  | Working with Existing Objects
 |  | Storing Objects of the Same Class in Vectors
 |  | Workshop: Creating a Subclass
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
Part IV. Programming a Graphical User Interface
 | Hour 13. Building a Simple User Interface
 |  | Swing and the Abstract Windowing Toolkit
 |  | Using Components
 |  | Workshop: Creating Your Own Component
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 14. Laying Out a User Interface
 |  | Using Layout Managers
 |  | Workshop: Laying Out an Application
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 15. Responding to User Input
 |  | Getting Your Programs to Listen
 |  | Setting Up Components to Be Heard
 |  | Handling User Events
 |  | Workshop: A Little Lotto Madness
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 16. Building a Complex User Interface
 |  | Scroll Panes
 |  | Sliders
 |  | Change Listeners
 |  | Menus
 |  | Workshop: Using Image Icons and Toolbars
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
Part V. Creating Multimedia Programs
 | Hour 17. Creating Interactive Web Programs
 |  | Standard Applet Methods
 |  | Putting an Applet on a Web Page
 |  | A Sample Applet
 |  | The Java Plug-in
 |  | Sending Parameters from a Web Page
 |  | Receiving Parameters in the Applet
 |  | Workshop: Handling Parameters in an Applet
 |  | Java Web Start
 |  | Using Java Web Start
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 18. Handling Errors in a Program
 |  | Exceptions
 |  | Assertions
 |  | Workshop: Throwing and Catching Exceptions
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 19. Creating a Threaded Program
 |  | Threads
 |  | Working with Threads
 |  | Starting with init()
 |  | Catching Errors as You Set Up URLs
 |  | Handling Screen Updates in the paint() Method
 |  | Starting the Thread
 |  | Handling Mouse Clicks
 |  | Workshop: Revolving Links
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 20. Reading and Writing Files
 |  | Streams
 |  | Writing Data to a Stream
 |  | Reading and Writing Configuration Properties
 |  | Workshop: Writing Bytes to an MP3 File
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
Part VI. Creating Multimedia Programs
 | Hour 21. Reading and Writing XML Data
 |  | Creating an XML File
 |  | Reading an XML File
 |  | Workshop: Reading RSS Syndication Feeds
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 22. Using Fonts and Color
 |  | Using the Font Class
 |  | Using the Color Class
 |  | Other Ways to Choose Colors
 |  | Workshop: Displaying a Danger Message
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 23. Working with Graphics
 |  | Using Graphics
 |  | Drawing Lines and Shapes
 |  | Workshop: Baking a Pie Graph
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
 | Hour 24. Creating Animation
 |  | Animating a Sequence of Images
 |  | Sending Parameters to the Applet
 |  | Workshop: Follow the Bouncing Ball
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
Part VII. Bonus…
 | Hour 25. Creating Web Services with XML-RPC
 |  | Working with Apache XML-RPC
 |  | Creating an XML-RPC Handler
 |  | Creating an XML-RPC Server
 |  | Creating an XML-RPC Client
 |  | Workshop: Enhancing the LottoMadness Application
 |  | Summary
 |  | Q&A
 |  | Quiz
 |  | Activities
Part VIII. Appendixes
 | Appendix A. Using the Java Development Kit
 |  | Choosing a Java Development Tool
 |  | Configuring the Java Development Kit
 |  | Using a Text Editor
 |  | Creating a Sample Program
 |  | Setting Up the CLASSPATH Variable
 | Appendix B. Programming with the Java Development Kit
 |  | An Overview of the JDK
 |  | The java Interpreter
 |  | The javac Compiler
 |  | The appletviewer Browser
 |  | The javadoc Documentation Tool
 |  | The jar Java File Archival Tool
 |  | The jdb Debugger
 |  | Using System Properties
 |  | Summary
 |  | Q&A
 | Appendix C. Using the NetBeans Integrated Development Environment
 |  | Choosing a Java Development Tool
 |  | Creating a Sample Program
 | Appendix D. Where to Go from Here: Java Resources
 |  | Other Books to Consider
 |  | Sun's Official Java Site
 |  | Other Java Websites
 |  | Java Newsgroups
 |  | Internet Relay Chat
 |  | Job Opportunities
 | Appendix E. This Book's Website
Sun Microsystems, Inc. Binary Code License Agreement
 | JAVA™ DEVELOPMENT TOOLS JAXP.JAR AND PARSER.JAR ARCHIVE FILES FROM JAVA API FOR XML PARSING, VERSION 1.0 SUPPLEMENTAL LICENSE TERMS
 | JAVAHELP™ VERSION 2.0 SUPPLEMENTAL LICENSE TERMS
 | JAVA™ DEVELOPMENT TOOLS JAVAC COMPILER SUPPLEMENTAL LICENSE TERMS
 | JAVA™ INTERFACE CLASSES J2EE™ DEPLOYMENT SPECIFICATION INTERFACE CLASSES 1.1 SUPPLEMENTAL LICENSE TERMS
 | JAVA 2, ENTERPRISE EDITION (J2EE™) MANAGEMENT, VERSION 1.0 JAVA™ INTERFACE CLASSES SUPPLEMENTAL LICENSE TERMS
 | JAVA™ INTERFACE CLASSES ENTERPRISE JAVABEANS™, VERSION 2.0, INTERFACE CLASSES SUPPLEMENTAL LICENSE TERMS
 | JAVA™ OPTIONAL PACKAGE JMX™, VERSION 1.2 SUPPLEMENTAL LICENSE TERMS
 | J2EEeditor.jar SUPPLEMENTAL LICENSE TERMS
 | resolver-1_1_nb.jar Based on Sun's XML Resolver 1.0 Software License Agreement
What's on the CD-ROM
 | Windows Installation Instructions
 | UNIX and UNIX-like Installation Instructions
Index


Copyright

Copyright © 2006 by Sams Publishing

All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein.

Library of Congress Catalog Card Number: 2005928293

Printed in the United States of America

First Printing: October 2005

08 07 06 05 4 3 2 1

Trademarks

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

Warning and Disclaimer

Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an "as is" basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book or from the use of the CD or programs accompanying it.

Bulk Sales

Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact

U.S. Corporate and Government Sales
1-800-382-3419
corpsales@pearsontechgroup.com

For sales outside of the U.S., please contact

International Sales
international@pearsoned.com

Credits

Senior Editor

Scott Meyers

Managing Editor

Charlotte Clapp

Project Editor

Andy Beaster

Indexer

Chris Barrick

Proofreader

Paula Lowell

Technical Editor

John Purdum

Publishing Coordinator

Vanessa Evans

Multimedia Developer

Dan Scherf

Book Designer

Gary Adair

Page Layout

Toi Davis

Nonie Ratcliff

Dedication

To my wife M.C. Moewe for the first 18 years of happily ever after. May this book sell considerably better than the first book I dedicated to you back in 1996, Sams Teach Yourself SunSoft Java Workshop in 21 Days. I'm not implying that your dedication had anything to do with the sales performance of that title, but if this book suffers a similar fate, I might have second thoughts about not dedicating it to my mother. But I digress. Someone was looking out for me when I stumbled drunkenly into the love of my life at a three-keg toga bacchanalia at the University of Texas-Arlington in 1987. I will always cherish the first moment when you stared at me through thick beer goggles and decided I wasn't as weird looking as you originally suspected. —Rogers


About the Author

Rogers Cadenhead is a writer, web application developer, and the most valuable player in an NBA playoff game[*]. He has written 20 books on Internet-related topics, including Sams Teach Yourself Java 2 in 21 Days, Fourth Edition, Sams Teach Yourself Microsoft FrontPage 2003 in 24 Hours, and Radio UserLand Kick Start. He maintains this book's official website at http://www.java24hours.com.

[*] Cadenhead attended Game 6 of the 1988 NBA Western Conference Finals at Reunion Arena in Dallas. The Dallas Mavericks beat the Los Angeles Lakers 105-103 to force a seventh game of the series. CBS Sports gave half the MVP award to Mavericks power forward Mark Aguirre for 23 points and 13 rebounds, and half to the sellout crowd of 17,007 for shouting a whole lot in loud voices and making enthusiastic hand gestures.

Cadenhead's statistics in the game:

PLAYER     MIN FGM-FGA FTM-FTA OFF-DEF-TOT AST PF ST TO PTS BEERS AVG. DECIBEL LEVEL TRIPS

   TO BATHROOM

======     === ======= ======= =========== === == == == === ===== ==================

   =================

CADENHEAD   0      0-0    0-0        0 0 0   0  0  0  0  00    05                 80

             3


Acknowledgments

To the folks at Sams—especially Mark Taber, Scott Meyers, John Purdum, and Andy Beaster. No author can produce a book like this on his own, regardless of what my agent told Sams during contract negotiations. Their excellent work will give me plenty to take credit for later on.

To Laura Lewin at the Studio B agency, who worked hard on my behalf in regard to this title and many others.

To my wife, Mary, and my sons, Max, Eli, and Sam. Although our family has not fulfilled my dream of becoming a high-wire trapeze team like the Flying Wallendas, I'm the world's proudest husband in a non-acrobatic family.


Reader Acknowledgements

I'd also like to thank readers who have sent helpful comments about corrections, typos, and suggested improvements to the book. The list includes Brian Converse, Philip B. Copp III, Wallace Edwards, M.B. Ellis, Kevin Foad, Adam Grigsby, Mark Hardy, Kelly Hoke, Donovan Kelorii, Russel Loski, Jason Saredy, Mike Savage, Peter Schrier, Gene Wines, Jim Yates, and others who shall remain nameless because they helped me improve the book before I started this list.


We Want to Hear from You!

As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we're doing right, what we could do better, what areas you'd like to see us publish in, and any other words of wisdom you're willing to pass our way.

You can email or write me directly to let me know what you did or didn't like about this book—as well as what we can do to make our books stronger.

Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message.

When you write, please be sure to include this book's title and author as well as your name and phone or email address. I will carefully review your comments and share them with the author and editors who worked on the book.

Email: | webdev@samspublishing.com
Mail: | Mark Taber Associate Publisher Sams Publishing 201 West 103rd Street Indianapolis, IN 46290 USA


Reader Services

For more information about this book or others from Sams Publishing, visit our website at www.samspublishing.com. Type the ISBN (excluding hyphens) or the title of the book in the Search box to find the book you're looking for.


Introduction

As the author of computer books, I spend a lot of time lurking in the computer section of bookstores, observing the behavior of shoppers browsing through the books as if they were hominid jawbones and I was a paleontologist.

Because of my research, I've learned that if you have picked up this book and turned to the introduction, I only have about 12 more seconds before you put it down and head to the coffee bar for a double tall latte decaf skim with two shots of vanilla hold the whip.

So I'll keep this brief: Computer programming with Java is a lot easier than it looks. I'm not supposed to tell you that, because there are thousands of programmers who have used their Java skills to get high-paying jobs in software development, web application programming, and e-commerce. The last thing any of them want is for their bosses to know that anyone who has persistence and a little free time can learn this language, the most popular programming language in use today. By working your way through each of the one-hour tutorials in Sams Teach Yourself Programming with Java in 24 Hours, Fourth Edition, you'll be able to learn Java programming quickly.

Anyone can learn how to write computer programs—even if they can't program a VCR. Java is one of the best programming languages to learn because it's a useful, powerful, modern technology that's embraced by thousands of programmers around the world.

This book is aimed at non-programmers, new programmers who hated learning the subject, and experienced programmers who want to quickly get up to speed with Java. It uses Java 2 version 5, the current version of the language.

Java is the Tiger Woods of programming languages because of the things it makes possible. You can create programs that feature a graphical user interface, design software that makes the most of the Internet, read XML data, add animation to World Wide Web pages, and more.

This book teaches Java programming from the ground up. It introduces the concepts in English instead of jargon, with plenty of step-by-step examples of working programs you will create. Spend 24 hours with this book and you'll be writing your own Java programs, confident in your ability to use the language and learn more about it. You also will have skills that are becoming increasingly important—such as network computing, graphical user interface design, and object-oriented programming.

These terms might not mean much to you now. In fact, they're probably the kind of thing that makes programming seem like a secret ritual for a weird group of humans who have a language of their own. However, if you can use a computer to create an attractive resume, balance your checkbook, or create a home page, you can write computer programs by reading Sams Teach Yourself Programming with Java in 24 Hours, Fourth Edition.

By the Way

At this point, if you would rather have coffee than Java, please reshelve this book with the front cover facing outward on an endcap with access to a lot of the store's foot traffic.


    Part I: Getting Started

    HOUR 1 Becoming a Programmer

    HOUR 2 Writing Your First Program

    HOUR 3 Vacationing in Java

    HOUR 4 Understanding How Java Programs Work


Hour 1. Becoming a Programmer

Computer programming is insanely difficult. It requires a four-year degree in computer science, thousands of dollars in computer hardware and software, a keen analytical intellect, the patience of Job, and a strong liking for caffeinated drinks. If you're a programming novice, this is probably what you've heard about computer programming. Aside from the part about caffeine, all of the rumors are greatly exaggerated.

Programming is easier than most people think, although there are several reasons why you might believe otherwise:

  • Computer programmers have been telling people for years that programming is hard. This belief makes it easier for us to find high-paying jobs and gives us more leeway to goof off during business hours.

  • Computer programming manuals are often written in a language that only a Scrabble player could appreciate. Strange acronyms like OOP, RAD, COM, and MUMPS are used frequently along with newly invented jargon like instantiation, bytecode, and makefile.

  • Many computer programming languages have been available only with software packages costing $200 or more, which is a lot of cabbage.

Because of the growth of the Internet and other factors, this is a great time to learn programming. Useful programming tools are being made available at low cost (or no cost), often as downloads from World Wide Web sites. Thousands of programmers are distributing their work under "open source" licenses so people can examine how the programs were written, correct errors, and add their own improvements.

The goal of this book is to teach programming to the person who has never tried to program before, or the person who tried programming but hated it with an intense passion. The English language will be used as much as possible instead of jargon and obscure acronyms, and all new programming terms will be thoroughly explained as they are introduced.

If I've succeeded, you will finish Sams Teach Yourself Programming with Java in 24 Hours with enough programming skill to be a danger to yourself and others. You'll be able to write programs, dive into other programming books with more confidence, and learn programming languages more easily. You also will have developed skills with Java, the most innovative programming language to be introduced in years.

The first hour of this book provides some introductory material about programming and gives you instructions on how to set up your computer so you can write Java programs. The following topics will be covered:

  • Choosing which programming language to learn first

  • Learning what Java is

  • Using programs to boss your computer around

  • Discovering how programs work

  • Fixing program errors (called bugs)

  • Acquiring a Java development tool

  • Getting ready to write programs


Choosing a Language

As you might have surmised at this point, computer programming is not as hard as it's cracked up to be. If you're comfortable enough with a computer to prepare a nice-looking resume, balance a checkbook with software such as Intuit Quicken, or create your own home page on the Web, you can write programs.

The key to learning how to program is to start with the right language. The programming language you choose often depends on the tasks you want the computer to accomplish. Each language has things it is well-suited for as well as things that are difficult—perhaps impossible—to do with the language. For example, many people use some form of the BASIC language when they are learning how to program because BASIC was created with beginners in mind.

By the Way

The BASIC language was invented in the 1960s to be easy for students and beginners to learn (the B in BASIC stands for Beginner's). The downside to using some form of BASIC is that it's easy to fall into sloppy programming habits with the language. Those habits can make it much more difficult to write complex programs and improve them later.

Microsoft Visual Basic combines the ease of BASIC with some powerful features to aid in the design of Windows software. (VBScript, which is short for Visual Basic Script, offers the simplicity of BASIC for small programs that run in conjunction with World Wide Web pages.) Visual Basic has been used to write thousands of sophisticated programs for commercial, business, and personal use. However, Visual Basic programs can be slower than Windows programs written in other languages such as Borland C++. This difference is especially noticeable in programs that use a lot of graphics—games, screen savers, and the like.

This book covers the Java programming language, which was developed by Sun Microsystems. Though Java is more difficult to learn than a language such as Visual Basic, it is a good starting place for several reasons. One advantage of learning Java is that you can use it on the World Wide Web. If you're an experienced web surfer, you have seen numerous Java programs in action. They can be used to create chat rooms, play games, and help in other interactive efforts.

Another important advantage is that Java requires an organized approach for getting programs to work. The language is very particular about the way programs must be written, and it balks if programmers do not follow all of its rules.

When you start writing Java programs, you might not see the language's choosy behavior as an advantage. You'll write a program and have several errors to fix before the program is finished. Some of your fixes might not be correct, and they will have to be redone. If you don't structure a program correctly as you are writing it, errors will result.

In the coming hours, you'll learn about these rules and the pitfalls to avoid. The positive side of this extra effort is that your programs will be more reliable, useful, and error-free.

Java was invented by Sun Microsystems developer James Gosling as a better way to create computer programs. Gosling was unhappy with the way that the C++ programming language was working on a project he was doing, so he created a new language that did the job better. It's a matter of contentious debate whether Java is superior to other programming languages, of course, but the amount of attention paid to the language today shows that it has a large number of adherents. Book publishers obviously dig it—more than 1,000 books have been published about the language since its introduction. (This is my thirteenth, and I will keep writing more of them until prohibited by municipal, state, or federal law.)

Regardless of whether Java is the best language, it definitely is a great language to learn today. There are numerous resources for Java programmers on the Web, Java job openings fill the classified ads in many cities, and the language has become a major part of the Internet's past, present, and future. You'll get a chance to try out Java during Hour 2, "Writing Your First Program."

Learning Java or any other programming language makes it much easier to learn subsequent languages. Many languages are similar to each other, so you won't be starting from scratch when you dive into a new one. For instance, many C++ programmers find it fairly easy to learn Java, because Java borrows a lot of its structure and ideas from C++. Many programmers are comfortable using several different languages and will learn new ones as needed.

By the Way

C++ is mentioned several times in this hour, and you might be tripping over the term wondering what it means, and more importantly, how it's pronounced. C++ is pronounced C-Plus-Plus, and it's a programming language that was developed by Bjarne Stroustrop and others at Bell Laboratories. C++ is an enhancement of the C programming language, hence the Plus-Plus part of the name. Why not just C+, then? The Plus-Plus part is a computer programming joke you'll understand later on.


Telling the Computer What to Do

A computer program, also called software, is a way to tell a computer what to do. Everything that the computer does, from booting up to shutting down, is done by a program. Windows XP is a program. Ms. Pac-Man is a program. The dir command used in MS-DOS to display filenames is a program. Even an email virus is a program.

Computer programs are made up of a list of commands the computer handles in a specific order when the program is run. Each of these commands is called a statement.

If you're a science fiction fan, you're probably familiar with the concept of household robots. If not, you might be familiar with the concept of henpecked spouses. In either case, someone gives very specific instructions telling the robot or spouse what to do, something like the following:

Dear Rosie,

Please take care of these errands for me while I'm out lobbying members of Congress:

Item 1: Vacuum the living room.

Item 2: Go to the store.

Item 3: Pick up butter, lozenges, and as many bottles of Heinz Easy Squeeze ketchup as you can carry.

Item 4: Return home.

Love,

Jane Jetson

If you tell a loved one or artificially intelligent robot what to do, there's a certain amount of leeway in how your requests are fulfilled. If lozenges aren't available, cough medicine might be brought to you instead. Also, the trip to the store can be accomplished through a variety of routes.

Computers don't do leeway. They follow instructions literally. The programs that you write will be followed precisely, one statement at a time.

The following is one of the simplest examples of a computer program, written in BASIC. Take a look at it, but don't worry yet about what each line is supposed to mean.

1 PRINT "Shall we play a game?"

2 INPUT A$

Translated into English, this program is equivalent to giving a computer the following to-do list:

Dear personal computer,

Item 1: Display the question, "Shall we play a game?"

Item 2: Give the user a chance to answer the question.

Love,

Snookie Lumps

Each of the lines in the computer program is a statement. A computer handles each statement in a program in a specific order, in the same way that a cook follows a recipe, or Rosie the robot followed the orders of Jane Jetson when she vacuumed and shopped at the market. In BASIC, the line numbers are used to put the statements in the correct order. Other languages, such as Java, do not use line numbers, favoring different ways to tell the computer how to run a program.

Figure 1.1 shows the sample BASIC program running on the Liberty BASIC interpreter, a shareware program that can be used to develop Windows and OS/2 programs. Liberty BASIC, which was developed by Carl Gundel, is among many BASIC interpreters that can be found on the Internet for Microsoft Windows, Apple Macintosh, and Linux systems. You can find out more about it at http://www.libertybasic.com.

Figure 1.1. An example of a BASIC program running in Liberty BASIC.

By the Way

The quote "Shall we play a game?" is from the 1983 movie War Games, in which a young computer programmer portrayed by Matthew Broderick saves mankind after almost causing global thermonuclear war and the near-extinction of humankind. You'll learn how to do that in the next book of this series, Sams Teach Yourself to Create International Incidents with Java in 24 Hours.

Because of the way programs operate, it's hard to blame the computer when something goes wrong while your program runs. After all, the computer was just doing exactly what you told it to do. Unless your hardware is on the fritz, a pesky virus is attacking your system, or your operating system is having a bad day, the blame for program errors lies with the programmer.

That's the bad news. The good news is that you can't do any permanent harm to your computer with the programming errors you make. No one was harmed during the making of this book, and no computers will be injured as you learn how to program with Java.


How Programs Work

Most computer programs are written in the same way that you write a letter—by typing each statement into a word processor. Some programming tools come with their own word processor, and others can be used with any text-editing software. If you don't already have a tool that can be used for Java programming, you can use the free Java Development Kit, which you will learn about later in this hour, with any of your favorite editors.

When you have finished writing a computer program, you save the file just like saving any other document to disk. Computer programs often have their own filename extension to indicate what type of file they are. Java programs have the extension .java; an example of a Java program filename is Calculator.java.

By the Way

If you use a fancy word processing program that has features such as boldface text, different font sizes, and other stylistic touches, do not use those features while writing a computer program. Programs should be prepared as text files with no special formatting. For example, when using Microsoft Word to write a program, save the file in Plain Text mode instead of saving it as a Word document. Notepad, a word processor that comes with Windows, saves all files as unformatted text. The vi editor on Linux systems also can be used to create text files without formatting.

To run a program you have saved as a file, you need some help. The kind of help that's needed depends on the programming language you're using. Some languages require an interpreter to run their programs. The interpreter is a program that interprets each line of a computer program and tells the computer what to do. Most versions of BASIC are interpreted languages. The advantage of interpreted languages is that they are faster to test. When you are writing a BASIC program, you can try it out immediately, spot any errors, fix them, and try again. The primary disadvantage is that interpreted languages run more slowly than other programs.

Other programming languages require a compiler. The compiler takes a computer program and translates it into a form that the computer can understand. It also does what it can to make the program run as efficiently as possible. The compiled program can be run directly, without the need for an interpreter. Compiled programs run more quickly than interpreted programs, but they take more time to test. You have to write your program and compile it before trying it out. If you find an error and fix it, you must compile the program again to verify that the error is gone.

Java is unusual because it requires a compiler and an interpreter. You'll learn more about this later as you write Java programs.


How Programs Don't Work

Many new programmers become discouraged when they start to test their programs. Errors appear everywhere. Some of these are syntax errors, which are identified by the computer as it looks at the program and becomes confused by what you wrote. Other errors are logic errors, which are only noticed by the programmer as the program is being tested, if they are noticed at all. Logic errors sneak by the computer unnoticed, but they will cause it to do something unintended.

As you start to write your own programs, you will become well-acquainted with errors. They're a natural part of the process. Programming errors are called bugs, a term that dates back a century or more to describe errors in technical devices. The process of fixing errors has its own term also: debugging. Whether you want it or not, you'll get a lot of debugging experience as you learn how to write computer programs.


Next Stop: Java

Before you can start writing Java programs, you need to acquire and set up some kind of Java programming software. Although several different products are available for the development of Java programs, including many terrific ones that make programming much easier, the starting place for most new Java programmers is the Java Development Kit, a set of tools for writing, debugging, and running Java programs. All of the examples in this book were created and tested using the Kit, but they can be created with any Java development tool that supports the current version of the language.

The Java Development Kit (also referred to as the JDK) is in version 5 as of this writing. Whenever Sun releases a new version of Java, the first tool that supports it is the Kit.

To create all of the programs in this book, you must either use Java Development Kit 5 or another Java programming tool that fully supports all of version 5's features.

There are many different software packages that offer the capability to create Java programs, but all are not created equal when language support is concerned. Some of these programming tools only support Java 1.0, the initial version of the language, which was released by Sun Microsystems in late 1995. Other tools support Java 1.1, which was released in mid-1997, version 1.2 (1998), version 1.3 (2000), or version 1.4 (2003).

Some operating systems such as Mac OS X and Red Hat Enterprise Linux include a copy of the JDK, but it's probably not the current version. Before using an JDK that was included with your operating system, make sure it supports Java version 5.

Users of Microsoft Windows systems may be dismayed to learn that the Java Development Kit is not graphical. You run programs from a command line (the C:\> or D:\> prompt that will be familiar to MS-DOS users) instead of using a mouse and a point-and-click environment. Figure 1.2 shows the Kit in use in an MS-DOS window on a Windows XP system. The Java program WarGames.java is compiled, and then it is run.

Figure 1.2. A program being compiled and run with the Java Development Kit.

Watch Out!

The examples in this book were prepared on the Microsoft Windows XP and Red Hat Linux operating systems. For this reason, some advice is offered for Windows and Linux users running the Java Development Kit. However, all of the Java code in this book will work regardless of the operating system you are using, as long as you have development software that supports all the features of JDK 5.

Official Documentation

Sun Microsystems offers comprehensive documentation for the Java language in web page format. You don't need this information to use this book because each topic is discussed fully as it is introduced, but these pages will come in handy when you write your own programs.

You can download the entire documentation, but it might be more convenient to browse it as needed from Sun's website. The most up-to-date Java documentation is available at http://java.sun.com/j2se/1.5.0/docs/api.


Workshop: Installing a Java Development Tool

Every hour of this book ends with a workshop, a Java programming project you can undertake to enhance your knowledge of the subject matter while it percolates in your brain.

However, you won't be doing any Java programming at all until you install a Java development tool on your computer.

If you have a program such as Borland JBuilder, Sun NetBeans, or IntelliJ IDEA, you can use it to develop the tutorial programs in the next 23 hours. However, you should already have some familiarity with how to use the program—learning Java and a complex development tool at the same time can be daunting.

If you don't have a Java development tool, or the last paragraph scared you away from using one that you own, you can use the Java Development Kit, which is available for free from Sun's Java website at http://java.sun.com.

Though the process is relatively straightforward, there are some configuration issues that cause problems for many people trying to get started with the Kit, especially on a Windows system. To find out how to download and install the Kit and fix any configuration problems that arise, read Appendix A, "Using the Java Development Kit."


Summary

During this hour, you were introduced to the concept of programming a computer—giving it a set of instructions that tell it what to do. You also might have downloaded and installed a Java development tool that will be used as you write sample programs throughout the book.

If you are still confused about programs, programming languages, or Java in general, that's understandable at this point. Everything will make more sense to you in the next hour, "Writing Your First Program," which takes a slow trip through the process of creating a Java program.


Q&A

Q1:

What is it about BASIC that makes it easier to fall into bad habits while writing programs?

A1:

One thing you'll learn as you start writing Java programs is that you have to be organized. If you don't structure your program in the correct way, it won't work. BASIC doesn't have this kind of requirement. You can write in a disorganized manner and still get the program to work successfully. Later on, however, you'll have a much harder time figuring out how the program functions when you try to fix a bug or add an improvement.

Q2:

BASIC? C++? Java? What are the names of these languages supposed to mean?

A2:

Like many programming languages, BASIC gets its name from an acronym that describes what it is: Beginner's All Symbolic Instruction Code. C++ is a programming language that was created to be an improvement on the C language, which itself was an improvement of the B programming language. Java goes against the tradition of naming a language with an acronym or other meaningful term. It's just the name that Java's developers liked the best when brainstorming for possible monikers—beating out WebRunner, Silk, Ruby, and others.

Q3:

Are there really more than 1,000 books about Java programming?

A3:

When JavaWorld magazine stopped counting them, there were approximately 2,400 books on the language. And now there are 2,401.

Q4:

Why are interpreted languages slower than compiled ones?

A4:

For the same reason that a person interpreting a live speech is a lot slower than a translator interpreting a printed speech. The live interpreter has to think about each statement that's being made as it happens, while the other interpreter can work on the speech as a whole and take some shortcuts to speed up the process. Compiled languages can be much faster than interpreted languages because they can do things to make the program more efficient.

Q5:

Is C++ harder to learn than Java?

A5:

It's a matter of personal opinion, but Java does seem more approachable for beginners than C++. C++ and its predecessor C are widely regarded as "programmer's languages," meaning that they were designed for the needs of experienced programmers. There are a lot of features in C and C++ that make them faster—and more powerful—during program creation, but these features often come at the expense of understandability. Java takes a more simplified approach to programming than C++ and is probably a better place to start.

Q6:

Do you only answer questions about Java?

A6:

Not at all. Ask me anything.

Q7:

OK. Where can I learn the art of glass blowing?

A7:

Look in your area for a two-day workshop that teaches lampworking, the art of making figurines out of hot glass.

You can find a list of upcoming workshops on the Glass Line website at http://www.hotglass.com.

Lampworking, which takes its name from artisans who used a lamp's heat to shape glass, costs about $150 to begin.

Off-hand glass blowing—putting hot glass at the end of a hollow tube and blowing it into shape—costs from $5,000 to $10,000 to undertake.

Some schools offer courses in off-hand glass blowing, including California State University-Chico, Tennessee Technological University, and Southern Illinois University.


Quiz

Test your knowledge of the material covered in this chapter by answering the following questions.

Questions

1:

Which of the following is not a reason that people think computer programming is painfully difficult?

  1. Programmers spread that rumor to improve their employment prospects.

  2. Jargon and acronyms are all over the place.

  3. Mind-control waves are sent out by the CIA promoting this belief.

2:

What kind of tool runs a computer program by figuring out one line at a time?

  1. A slow tool

  2. An interpreter

  3. A compiler

3:

Why did James Gosling hole up in his office and create Java?

  1. He was unhappy with the language he was using on a project.

  2. His rock band wasn't getting any gigs.

  3. When you can't download any MP3 files at work, the Internet is pretty dull.

Answers

A1: | c. Of course, the CIA could have forced me to say this.
A2: | b. Compilers figure out the instructions beforehand so the program can run faster.
A3: | a. He was frustrated with C++. At the time Gosling created Java, people thought that "MP3" was some kind of British secret service designation.


Activities

If you would like to better introduce yourself to the subjects of Java and computer programming, do the following activities:

  • Visit Sun's official Java site at http://java.sun.com/learning/new2java and read the company's introduction to the Java language.

  • Using English sentences instead of a programming language, write a set of instructions to add 10 to a number selected by a user and then multiply the result by 5. Break the instructions into as many short one-sentence lines as you can.

To see solutions to the activities at the end of each hour, visit the book's website at http://www.java24hours.com.


Hour 2. Writing Your First Program

As you learned during Hour 1, "Becoming a Programmer," a computer program is a set of instructions that tell a computer what to do. These instructions are prepared in the same way instructions could be given to a person: You type them into a word processor. However, that's where the similarity ends. Instructions given to a computer must be written using a programming language. Dozens of computer programming languages have been created; you might have heard of some of them, such as BASIC or Pascal.

During this hour, you will create your first Java program by entering it using any word processor you like. When that's done, you will save the program, compile it, and test it out. The following topics will be covered during this hour:

  • Entering a program into a word processor

  • Naming a Java program with the class statement

  • Organizing a program with bracket marks

  • Storing information in a variable

  • Displaying the information stored in a variable

  • Saving a program

  • Compiling a program

  • Running a program

  • Fixing errors


What You Need to Write Programs

As explained in Hour 1, to create Java programs, you must have the current version of the Java Development Kit, or another development tool that supports Java 2 version 5. You need something that can be used to compile and test Java programs and a word processor to write programs.

With most programming languages, computer programs are written by entering text into a word processor (also called a text editor). Some programming languages, such as Visual C++ from Microsoft, come with their own word processor. Several advanced tools that you could use as an alternative to the Java Development Kit, such as Borland JBuilder and Sun NetBeans, also come with their own editors.

Java programs are simple text files without any special features, such as centered text, boldface text, or other enhancements. They can be written with any word processing program that can create text files. Windows systems have several word processors you can use, including Notepad, WordPad, and the DOS program Edit. Mac users can create programs with Simple Text or BBEdit Lite and Linux users can rely on vi, emacs, and others. Any of these will work fine.

You also can use more sophisticated word processors such as Microsoft Word, but you must remember to save your programs as text. This option has different names depending on the program you are using. In Word, the file should be saved as a file of type Plain Text. Other programs call these files DOS text, ASCII text, or something similar. You'll probably have a better experience creating the programs in this book if you choose a simple word processor to work on source code rather than a sophisticated editing tool such as Word.

Watch Out!

If you're in doubt about whether a word processor can save files as text files, you always can use one of the simple programs that come with your operating system. For instance, Windows users can rely on Notepad to create Java programs, because text files created with Notepad are always saved as text-only files.


Creating the Saluton Program

The first Java program that you create will be an application that displays a traditional greeting from the world of computer science, "Saluton mondo!"

Beginning the Program

Using your word processor, begin your Java programming career by entering each line from Listing 2.1. Don't enter the line number and colon at the beginning of each line—these are used in this book so that specific line numbers can be referred to.

Listing 2.1. The Saluton Program

1: class Saluton {

2:     public static void main(String[] arguments) {

3:         // My first Java program goes here

4:     }

5: }

Make sure to capitalize everything exactly as shown, and use your spacebar or Tab key to insert the blank spaces in front of some lines. When you're done, save the file with the filename Saluton.java.

Watch Out!

If you're using Windows, don't forget to put quotation marks around the filename when saving it, as in "Saluton.java". This will ensure that the file extension .txt is not added to the filename automatically.

At this point, Saluton.java contains the bare-bones form of a Java program. You will create several programs that start off exactly like this one, except for the word Saluton on Line 1. This word represents the name of your program and changes with each program you write. Line 3 also should make sense—it's a sentence in actual English. The rest is completely new, with each part introduced in the following sections.

The class Statement

The first line of the program is the following:

class Saluton {

Translated into English, this line means, "Computer, give my Java program the name Saluton."

As you might recall from Hour 1, each instruction you give a computer is called a statement. The class statement is the way you give your computer program a name. It's also used to determine other things about the program, as you will see later. The significance of the term class is that Java programs also are called classes.

In this example, the program name Saluton matches the filename you gave your document, Saluton.java. As a general rule, a Java program should have a name that matches the first part of its filename, and they should be capitalized in the same way.

If the program name doesn't match the filename, you will get an error when you try to compile some Java programs, depending on how the class statement is being used to configure the program.

What the main Statement Does

The next line of the program is the following:

public static void main(String[] arguments) {

This line tells the computer, "The main part of the program begins here." Java programs are organized into different sections, so there needs to be a way to identify the part of a program that will be handled first.

The main statement is the entry point to most Java programs. The exceptions are applets, programs that are run in conjunction with a World Wide Web page, and servlets, programs run by a web server. Most programs you will write during upcoming hours use main as the starting point.

Those Squiggly Bracket Marks

In the Saluton program, every line except Line 3 contains a squiggly bracket mark of some kind—either an { or an }. These brackets are a way to group parts of your program (in the same way that parentheses are used in a sentence to group words). Everything between the opening bracket, {, and the closing bracket, }, is part of the same group.

These groupings are called blocks. In Listing 2.1, the opening bracket on Line 1 is associated with the closing bracket on Line 5, which makes your entire program a block. You always will use brackets in this way to show the beginning and end of your programs.

Blocks can be located inside other blocks (just as parentheses are used in this sentence (and a second set is used here)). The Saluton program has brackets on Line 2 and Line 4 that establish another block. This block begins with the main statement. Everything inside the main statement's block is a command for the computer to handle when the program is run.

The following statement is the only thing located inside the block:

// My first Java program goes here

This line is a placeholder. The // at the beginning of the line tells the computer to ignore this line—it is put in the program solely for the benefit of humans who are looking at the program's text. Lines that serve this purpose are called comments.

Right now, you have written a complete Java program. It can be compiled, but if you run it, nothing happens. The reason is that you have not told the computer to do anything yet. The main statement block contains only a line of comments, which is ignored. If the Saluton program is going to greet anyone, you must add some commands inside the opening and closing brackets of the main statement block.


Storing Information in a Variable

In the programs you write, one thing that's often needed is a place to store information for a brief period of time. You can do this by using a variable, a storage place that can hold information such as integers, floating-point numbers, true-false values, characters, and lines of text. The information stored in a variable can change, which is where the name "variable" comes from.

Load the Saluton.java file into your word processor (if it's not already loaded) and replace Line 3 with the following:

String greeting = "Saluton mondo!";

This statement tells the computer to store the line of text "Saluton mondo!" into a variable called greeting.

In a Java program, you must tell the computer what type of information a variable will hold. In this program, greeting is a string—a line of text that can include letters, numbers, punctuation, and other characters. Putting String in the statement String greeting = "Saluton mondo!" sets up the variable to hold string values.

When you enter this statement into the program, a semicolon must be included at the end of the line. Semicolons are used at the end of each statement in your Java programs. They're like periods at the end of a sentence. The computer uses them to determine when one statement ends and the next one begins.

Displaying the Contents of a Variable

If you ran the program at this point, it wouldn't display anything. The command to store a line of text in the greeting variable occurs behind the scenes. To make the computer show that it is doing something, you can display the contents of that variable.

Insert another blank line in the Saluton program after the String greeting = "Saluton mondo!" statement. Use that empty space to enter the following statement:

System.out.println(greeting);

This statement tells the computer to display the value stored in the greeting variable. The System.out.println statement tells the computer to display a line on the system output device. In this case, the output device is your computer monitor.

Watch Out!

If you learned to type on a typewriter rather than a computer, watch out for hitting the "1" key as an alternative to the "l" key (lowercase "L"). A1though your cerebra1 cortex is perfect1y happy to treat the numera1 as the 1etter when it appears, a computer isn't as f1exib1e as your brain. Your program won't compile if you use print1n instead of println, for example.


Saving the Finished Product

Your program should now resemble Listing 2.2, although you might have used slightly different spacing in Lines 3–4. Make any corrections that are needed and save the file as Saluton.java. Keep in mind that all Java programs are created as textfiles and are saved with the .java file extension.

Listing 2.2. The Finished Version of the Saluton Program

1: class Saluton {

2:     public static void main(String[] arguments) {

3:         String greeting = "Saluton mondo!";

4:         System.out.println(greeting);

5:     }

6: }

When the computer runs this program, it will run each of the statements in the main statement block on Lines 3 and 4. Listing 2.3 shows what the program would look like if it were written in the English language instead of Java.

Listing 2.3. A Line-by-Line Breakdown of the Saluton Program

1: The Saluton program begins here:

2:     The main part of the program begins here:

3:         Store the text "Saluton mondo!" in a String variable named greeting

4:         Display the contents of the variable greeting

5:     The main part of the program ends here.

6: The Saluton program ends here.


Compiling the Program into a Class File

Before you can try out the program, it must be compiled. The term compile might be unfamiliar to you now, but you will become quite familiar with it in the coming hours. When you compile a program, you take the instructions you have given the computer and convert them into a form the computer can better understand. You also make the program run as efficiently as possible. Java programs must be compiled before you can run them. With the Java Development Kit, programs are compiled using the javac program.

The javac program, like all programs included with the Kit, is a command-line utility. You run the program by using your keyboard to type a command at a command line that can accept the input.

Because most Linux usage is handled at the command line, readers with that operating system will be familiar with how the Kit's programs are used. Anyone who used MS-DOS prior to the introduction of Windows also has used a command line.

Many Windows users might not be aware that their operating system includes a command-line feature of its own: the MS-DOS Command Prompt window.

To get to a command line in Windows:

  • On Windows 98 or Me, choose Start, Programs, and then choose MS-DOS Prompt.

  • On Windows NT or 2000, choose Start, Programs, Accessories, and then choose Command Prompt.

  • On Windows XP or Windows Server 2003, choose Start, All Programs, Accessories, and then choose Command Prompt.

On a Mac, access a command line by choosing Applications, Utilities, Terminal. To compile the Saluton program using the Java Development Kit, go to a command line, open the folder on your system where the Saluton.java file is located, then type the following at the command line:

javac Saluton.java

If the program compiles successfully, a new file called Saluton.class is created in the same folder as Saluton.java. If you see any error messages, refer to the following section, "Fixing Errors." All Java programs are compiled into class files which are given the .class file extension. A Java program can be made up of several classes that work together, but in a simple program such as Saluton only one class is needed.

By the Way

Did you ever have a relative, spouse, or other loved one who only says something when things go wrong? (Me neither.) A Java compiler only speaks up when there's an error to complain about. If you compile a program successfully without any errors, nothing happens in response.


Fixing Errors

If errors exist in your program when you compile it, a message is displayed that explains each error and the lines on which they occurred. The following output illustrates an attempt to compile a program that has an error and the error messages that are displayed as a result:

C:\J24Work>javac Saluton.java

Saluton.java:4: cannot resolve symbol.

symbol  : method print1n (java.lang.String)

location: class java.io.PrintStream

        System.out.print1n(greeting);

                  ^

1 error

C:\J24Work>

Error messages displayed by the javac tool include the following information:

  • The name of the Java program

  • The number of the line where the error was found

  • The type of error

  • The line where the error was found

As you learned during the past hour, errors in programs are called bugs. Finding those errors and squashing them is called debugging. The following is another example of an error message you might see when compiling the Saluton program:

Saluton.java:4: cannot resolve symbol.

symbol  : variable greting

location: class Saluton

        System.out.println(greting);

                           ^

In this example, the 4 that follows the filename Saluton.java indicates that the error is on Line 4. This is where having a line-numbering word processor comes in handy—you can jump more easily to the Java statement that's associated with the error.

The actual error message, cannot resolve symbol in this case, often can be confusing to new programmers. In some cases, the message can be confusing to any programmer. When the error message doesn't make sense to you, take a look at the line where the error occurred.

For instance, can you determine what's wrong with the following statement?

System.out.println(greting);

The problem is that there's a typo in the variable name, which should be greeting instead of greting.

If you get error messages when compiling the Saluton program, double-check that your program matches Listing 2.2, and correct any differences you find. Make sure that everything is capitalized correctly, and that all punctuation marks (such as {, }, and ;) are included.

Often, a close look at the statement included with the error message is enough to reveal the error, or errors, that need to be fixed.

Did you Know?

This book's official website at http://www.java24hours.com includes source files for all programs that you create. If you can't find any typos or other reasons for errors in the Saluton program, go to the book's website and download Saluton.java from the Hour 2 page. Try to compile that file, too.

If the Java compiler responds with error messages such as Bad command or filename, error: Can't read, Class not found, or NoClassDef, the most likely culprit is that your Java Development Kit needs to be reconfigured—a common situation on Windows systems. For help fixing this, read Appendix A, "Using the Java Development Kit."


Workshop: Running a Java Program

To run the Java program you have just created, you must use a Java interpreter such as java, the command-line tool included with the Java Development Kit. An interpreter makes the computer follow the instructions you gave it when you wrote the program.

To run a Java program, the command java is followed by a space and the name of the class file that contains the program. Although the class file's name includes the .class extension, this part of the name must be left off when running the program with the Java interpreter.

To see whether the Saluton program does what you want, run the class. If you're using the kit, go to the folder that contains the Saluton.class file and type the following at a command line:

java Saluton

Even though the program's filename is Saluton.class, don't include the file extension .class in the command, or the interpreter will fail with an error.

When the program runs, it should state the following:

Saluton mondo!

If you see this text, you have just written your first working Java program. Your computer has just greeted the world, a tradition in the field of computer programming that's as important to many of us as caffeine, short-sleeved dress shirts, and the Star Wars films.

By the Way

You may be asking yourself why "Saluton mondo!" is a traditional greeting, especially if you have tried using it in a conversation with other programmers and received funny looks in response. It's the phrase "Hello world!" in Esperanto, an artificial language created by Ludwig Zamenhof in 1887 to facilitate international communication. The author uses it here in the hope that more computers will be inspired to learn Esperanto.


Summary

During this hour, you got your first chance to create a Java program. You learned that to develop a Java program you need to complete these three basic steps:

1. | Write the program with a word processor.
2. | Compile the program into a class file.
3. | Tell the interpreter to run the class.

Along the way, you were introduced to some basic computer programming concepts such as compilers, interpreters, blocks, statements, and variables. These things will become clearer to you in successive hours. As long as you got the Saluton program to work during this hour, you're ready to proceed.


Q&A

Q1:

In MS-DOS, I seem to recall that there is a control key command to retype the previous line that you had typed in. Do you happen to know that command?

A1:

After opening an MS-DOS Command Prompt window, enter the command doskey. This causes all subsequent commands you type in to be saved, and you can navigate backwards and forwards through these saved commands by using the up arrow and down arrow keys on your keyboard. This can be a timesaver when you're trying to fix a Java program that won't compile successfully. Windows XP supports this functionality automatically.

Q2:

I have several word processing programs on my system. Which should I use to write Java programs?

A2:

Any of them will suffice, as long as the program can save files as text without any special formatting. A word processor that shows the line number your cursor is located on is especially useful. (The Windows programmer's editor UltraEdit-32, for example, shows the line number at the bottom edge of the window along with the column number.) Because the javac compiler lists line numbers with its error messages, the line-numbering feature helps you debug a program more quickly.

Q3:

How important is it to put the right number of blank spaces on a line in a Java program?

A3:

Spacing is strictly for the benefit of people looking at a computer program—the Java compiler could care less. You could have written the Saluton program without using blank spaces or used the Tab key to indent lines, and it would compile successfully. Although the number of spaces in front of the lines isn't important, you should use consistent spacing in your Java programs. Spacing makes it easier for you to see how a program is organized and to which programming block a statement belongs. When you start writing more sophisticated programs, you'll find it much more difficult to do without spacing.

Q4:

A Java program has been described as a class and as a group of classes. Which is it?

A4:

Both. The simple Java programs you create during the next few hours will be compiled into a single file with the extension .class. You can run these with the java interpreter. Java programs also can be made up of a set of classes that work together. In fact, even simple programs like Saluton use other Java classes behind the scenes. This topic will be fully explored during Hour 10, "Creating Your First Object."

Q5:

If semicolons are needed at the end of each statement, why does the comment line // My first Java program goes here not end with a semicolon?

A5:

Comments are completely ignored by the compiler. If you put // on a line in your program, this tells the Java compiler to ignore everything to the right of the // on that line. The following example shows a comment on the same line as a statement:

System.out.println(greeting); // hello, world!

In this example, the compiler will handle the statement System.out.println(greeting) and ignore the comments after the semicolon.

Q6:

What is a character?

A6:

A character is a single letter, number, punctuation mark or other symbol. Examples are T, 5, and %. Characters are stored in variables as text.

Q7:

I get an Invalid argument error message when I use the javac tool to compile the Saluton program. What can I do to correct this?

A7:

You are probably leaving off the .java extension and typing the following command:

javac Saluton

Make sure you are in the same folder as the file Saluton.java, and type the following command to compile the program:

javac Saluton.java

Q8:

I couldn't find any errors in the line where the compiler noted an error. What can I do?

A8:

The line number displayed with the error message isn't always the place where an error needs to be fixed in your program. Examine the statements that are directly above the error message to see whether you can spot any typos or other bugs. The error usually is within the same programming block.

Q9:

When orange juice is labeled "not from concentrate," why don't they just call it fresh squeezed?

A9:

Orange juice labeled "not from concentrate" is flash-heated to pasteurize it immediately after the fruit is squeezed. It has never been concentrated. "Fresh squeezed" juice has not been pasteurized.

As for other orange juice designations, "chilled or ready-to-serve" is juice made from frozen concentrate or pasteurized juice, and "fresh frozen" is freshly squeezed juice packaged and frozen without pasteurizing or further processing.

Fresh-frozen orange juice is usually sold in a supermarket's frozen food section and is ready to drink after it thaws.


Quiz

Test your knowledge of the material covered in this chapter by answering the following questions.

Questions

1:

When you compile a Java program, what are you doing?

  1. Saving it to disk

  2. Converting it into a form the computer can better understand

  3. Adding it to your program collection

2:

What is a variable?

  1. Something that wobbles but doesn't fall down

  2. Text in a program that the compiler ignores

  3. A place to store information in a program

3:

What is the process of fixing errors called?

  1. Defrosting

  2. Debugging

  3. Decomposing

Answers

A1: | b. Compiling a program converts a .java file into a .class file or a set of .class files.
A2: | c. Variables are one place to store information; later you'll learn about others such as arrays and constants. Weebles wobble but they don't fall down, and comments are text in a program that the compiler ignores.
A3: | b. Because errors in a computer program are called bugs, fixing those errors is called debugging. Some programming tools come with a tool called a debugger that helps you fix errors.


Activities

If you would like to explore the topics covered in this hour a little more fully, try the following activities:

  • You can translate the English phrase "Hello world!" into other languages using the AltaVista website Babelfish, located at http://babel.altavista.com. Write a program that enables your computer to greet the world in a language such as French, Italian, or Portuguese.

  • Go back to the Saluton program and add one or two errors. For example, take a semicolon off the end of a line, or change the text println on one line to print1n. Save the program and try to compile it. Compare the error messages you get to the errors you caused.

To see solutions to these activities, visit the book's website at http://www.java24hours.com.


Hour 3. Vacationing in Java

Before you venture further into Java programming, it's worthwhile to learn more about the language and see what Java programmers are doing today. One of the reasons that Java became popular so quickly was because it could be used to offer programs on the World Wide Web. Though Java has outgrown its origins as a language focused on Web programs, you can still find some interesting examples of how Java is used on the Web.

During this hour, we'll take a look at some sites that feature Java programs and talk about the history and development of the language.

To go on this vacation, you need a web browser that can handle Java programs. The current versions of Microsoft Internet Explorer, Mozilla Firefox, and the Opera browser can run Java programs that are found on web pages.

Did you Know?

If you're using a current version of Mozilla Firefox or Microsoft Internet Explorer and it isn't working with Java programs, check your setup configuration from one of the program's pull-down menus (Tools, Options in Firefox or Tools, Internet Options in Internet Explorer). Make sure your browser software has Java enabled in its settings.

Load your browser software of choice, put on your best batik shirt, and get ready to take a vacation. Because you won't be leaving your house, you won't get a chance to experience the simpler pleasures of tourism: odd driving rituals, exotic food, exotic members of the opposite sex, exotic members of the opposite sex with food, and so on. But look on the bright side: no antibacterial shots, traveler's checks, or passports are required either.

The following topics will be covered during this hour:

  • A definition of the Java language

  • The benefits of using Java

  • Some examples of Java at work

  • An explanation of object-oriented programming

  • Sites of note for Java programmers


First Stop: Sun Microsystems

The Java vacation begins at a place you'll be visiting regularly, now that you're a Java programmer: the website of Sun Microsystems, the company that developed the Java language. To get there, go to http://java.sun.com.

A Java program that runs as part of a web page is called an applet. Applets are placed on pages like other elements of a page—a markup language called HTML is used to define where the program should be displayed, how big it is, and what the program does when it runs.

The Java division of Sun Microsystems is responsible for the advancement of the Java language and the development of related software. As you might expect of a proud parent, Sun uses Java applets on its site. There's a glossary applet that's a guide to the site, several applets that are free for your own use, and others.

The sample applets include an animated clock and a shopping cart assistant, which you can try by visiting the web page at http://java.sun.com/openstudio. Java can be a great attention-getter, creating content dynamically that changes as a page is being viewed in a web browser. Figure 3.1 shows the clock and other sample applets.

Figure 3.1. Sun's official Java website offers several Java programs for use on your own website.

[View full size image]

Sun's Java site is the place to find the latest released versions of the Java Development Kit as well as other programmer's resources. This site offers announcements about Java-related products, full documentation for Java, and discussion forums where programmers can help each other as they learn the language. Sun Microsystems first made Java available for free via this website in 1995, and it's still the first place to look for each new version of the language and Java Development Kit upgrade.

A Brief History of Java

Sun co-founder Bill Joy called Java "the end result of fifteen years of work to produce a better, more reliable way to write computer programs." Java's creation was a little more complicated than that.

Java was developed in 1990 by Sun engineer James Gosling as a language that would serve as the brains for smart appliances (interactive TVs, omniscient ovens, SkyNet military satellites with artificial intelligence that enslave mankind—you get the idea). Gosling was unhappy with the results he was getting by writing programs with C++, another programming language, so he holed up in his office and wrote a new language to better suit his needs.

By the Way

Unfortunately, many of us like writing programs with Java so much that we have no incentive to create our own programming languages. This gives us more time to hole up in our offices and play MineSweeper instead.

Gosling named his new language Oak after a tree he could see from his office window. The language was part of Sun's strategy to make millions when interactive TV became a multimillion-dollar industry. That still hasn't happened today (though TiVo, and ReplayTV are making a game attempt), but something completely different took place for Gosling's new language. Just as Sun was ready to scrap Oak development and scatter its workers to other parts of the company, the World Wide Web became popular.

In a fortuitous circumstance, many of the qualities that made Gosling's language good on its appliance project made it suitable for adaptation to the Web. Sun developers devised a way for programs to be run safely from web pages and chose a catchy new name to accompany the language's new focus: Java.

Although Java can be used for many other things, the Web provided the showcase it needed to capture international attention. A programmer who puts a Java program on a web page makes it instantly accessible to the entire Web-surfing planet. Because Java was the first technology that could offer this capability, it became the first computer language to receive star treatment in the media. When the language rose to prominence in 1996, you had to be in solitary confinement or a long-term orbital mission to avoid hearing about Java.

By the Way

You might have heard that Java is an acronym that stands for Just Another Vague Acronym. You also might have heard that it was named for the developers' love of coffee, especially the percolating product from a shop near Sun's offices. Actually, the story behind Java's naming contains no secret messages or declarations of liquid love. Java was chosen as the name for the same reason that comedian Jerry Seinfeld likes to say the word salsa. It sounds cool.

There have been six major releases of the Java language:

  • Fall 1995: Java 1.0— The original release

  • Spring 1997: Java 1.1— An upgrade to the language that improved the way user interfaces are created and handled

  • Summer 1998: Java 2 version 1.2— A version more than three times as large as Java 1.0, making the language a worthy competitor to other general-purpose programming languages

  • Fall 2000: Java 2 version 1.3— A release supporting faster-running Java programs and enhanced multimedia features

  • Spring 2002: Java 2 version 1.4— A substantial upgrade expanded Internet support, XML capabilities, and text processing

  • Spring 2004: Java 2, version 5— The current release, which makes programs more reliable and easier to write through additions such as automatic data conversion


Going to School with Java

As a medium that offers a potential audience of millions, the World Wide Web includes numerous resources for educators and schoolchildren. Because Java programs can offer a more interactive experience than standard web pages, some programmers have used the language to write learning programs for the Internet.

For one of the strongest examples of this use of Java, visit http://www.dhpc.adelaide.edu.au/projects/vishuman2.

This website uses data from the National Library of Medicine's Visible Human Project, a database of thousands of cross-sectional images of human anatomy. A Java program is being used to enable users to search the collection and view images.

Instead of making requests by text commands, users make the requests to see different parts of the body by using the mouse, and the results are shown immediately in graphic detail. The Java program is shown in Figure 3.2.

Figure 3.2. Images from the National Library of Medicine's Visible Human Project can be viewed interactively on the Web using a Java program.

[View full size image]

Numerous educational programs are available for many different computer systems, but what makes this program remarkable is its versatility. The Visible Human Project tool is similar in function and performance to CD-ROM software that users might run on their computer systems. However, it is run directly from a web page. No special installation is needed, and unlike most CD-ROM software, it isn't limited to PC-compatible and Macintosh systems. Just like web pages, Java programs can be run on any computer system that can handle them.

By the Way

The subject of the Visible Human project was Joseph Paul Jernigan, a 39-year-old convicted murderer executed by the state of Texas in 1993. A chaplain persuaded him to donate his body to science, but Jernigan was not told it would become 1,800 of the most famous anatomical images in the world. He just wanted to spare his family the cost of a burial.

To be able to handle Java programs, a web browser must have a Java interpreter. The interpreter included with a browser serves a similar function as the interpreter you used to run the Saluton program during Hour 2, "Writing Your First Program." The difference is that a browser's interpreter can only run Java programs that are set up to run on web pages and cannot handle programs set up to run from the command line.

The primary Java-capable browsers in use today are Microsoft Internet Explorer, Mozilla Firefox, Netscape Navigator, and Opera. Although versions of these browsers support Java, none of them offer built-in support for Java 2 version 5. Browser developers have not kept up with new versions of the language as quickly as Sun produces them.

To make it possible for Java programmers to rely on current Java support in browsers, Sun developed the Java plug-in, a Java interpreter that works as a browser enhancement. When the plug-in is present, Java programmers can take advantage of all features of the language in their web-based programs.

Watch Out!

Sun includes the Java plug-in with the Java Development Kit and other products, so it may already be installed on your computer. If not, you can download and install it as part of the Java Runtime Environment: Visit the web page http://java.com.

A Java program such as the Visible Human Project database does not have to be written for a specific computer system. This advantage is called platform independence. Java was created to work on multiple systems. Originally, Java's developers believed it needed to be multiplatform because it would be used on a variety of appliances and other electronic devices.

The programs you write with Java can be run on a variety of computer systems without requiring any extra work from you. This advantage is one of the primary reasons so many people are learning to write Java programs and are using them on software projects. Many professional software companies are using Java for the same reason. Under the right circumstances, Java can remove the need to create specific versions of a program for different computer systems. The potential audience for software grows with a multiplatform solution such as Java.


Lunch in JavaWorld

If you didn't lose your appetite after searching through the innards of a visible human, take a lunch break with JavaWorld, an online magazine for Java programmers and other Internet developers. The JavaWorld website is available at http://www.javaworld.com.

JavaWorld offers how-to articles, news stories related to Java development, and other regular features. One of the advantages of the publication's web format is that it can display functional Java programs in conjunction with articles. Figure 3.3 shows a Java "poetry magnet board" in a tutorial that describes how it is written.

Figure 3.3. A JavaWorld how-to article on how to create a "poetry magnet board" includes a working example of the program.

[View full size image]

By the Way

JavaWorld occasionally moves things around, but at the time of this writing, you can go directly to the poetry magnet board tutorial at http://www.javaworld.com/ jw-04-1998/step/poetry.html. If that page is unavailable, use the site's search engine to look for the word "poetry."

In addition to offering information of benefit to Java programmers, JavaWorld publishes articles and commentary about the language and its development. One issue that has been hotly debated since Java's introduction is whether the language is secure.

Security is important because of the way Java programs work when they are placed on a web page. The Java programs you have tried during this hour were downloaded to your computer. When the program was finished downloading, it ran on your computer. It was as though someone sat down at your computer, popped in a disc, and ran his or her own program.

Unless you know a whole lot of people, most of the web pages you visit will be published by strangers. In terms of security, running their programs isn't a lot different than letting the general public borrow your computer on alternate weekends. If the Java language did not have safeguards to prevent abuse, its programs could introduce viruses onto your system, delete files, play the collected works of Ashlee Simpson, and do other undesirable things. Java includes several different kinds of security to make sure that its programs are safe when run from web pages.

The main security is provided by the following general restrictions on Java programs running over the Web:

  • No program can open, read, write, or delete files on the user's system.

  • No program can run other programs on the user's system.

  • All windows created by the program will be identified clearly as Java windows. This identification prevents someone from creating a fake window asking for the user's name and password.

  • Programs cannot make connections to websites other than the one from which they came.

  • All programs will be verified to make sure that nothing was modified after they were compiled.

The general consensus among Java developers is that the language has enough safeguards in place to be usable over the Web. Several security holes have been found, often by programming security experts, and these holes have been dealt with quickly by Sun or the web browser programmers.

Did you Know?

None of the safeguards in place are a complete block against malicious programs. Just as loopholes have been found in the past, more will undoubtedly be found in the future. If you are concerned about running Java programs through your web browser, you can turn off Java support in browsers, though you will be missing a lot of interactive content on the Web.

The Java language also offers a more flexible security policy for programs that run in a browser. You can designate some companies and programmers as "trusted developers," which enables their Java programs to run in your browser without the restrictions that normally would be in place.

This system of trust is established through the use of digital signatures, files that clearly identify the author of a Java program. These signatures are created in collaboration with independent verification groups like VeriSign, which has a World Wide Website at http://www.verisign.com.

If you have ever authorized an ActiveX control to run in Internet Explorer, you have worked with a similar system of trust and identity verification.


Watching the Skies at NASA

The first afternoon stop on the Java tour will be a trip to NASA, the National Aeronautics and Space Administration, a U.S. government agency that makes extensive use of Java applets. One of the most popular is J-Track, an applet that helps skywatchers keep an eye out for orbiting satellites. Load it in your browser at http://science.nasa.gov/Realtime/JTrack/Spacecraft.html.

J-Track superimposes the current location and path of satellites over a map of the world, shading the planet to show day and night for those of us who don't look out the window.

More than 100 different satellites can be added or dropped from view. The J-Track applet running in Figure 3.4 provides a glimpse of how crowded the skies have become with all of the scientific, military, and commercial craft circling the globe. With so many identified flying objects, people looking out for UFOs really have their work cut out for them.

Figure 3.4. NASA's J-Track applet monitors the location and path of orbiting satellites, a boon to metal birdwatchers.

[View full size image]

The J-Track applet redraws the position of each tracked satellite as it runs, providing each craft's current latitude and longitude. This kind of real-time update is relatively easy to do because the Java language is multithreaded. Multithreading is a way for the computer to do more than one thing at the same time. One part of a program takes care of one task, another part takes care of a different task, and the two parts can pay no attention to each other. Each part of a program in this example is called a thread.

In a program such as J-Track, each satellite could run in its own thread. If you use an operating system such as Microsoft Windows XP, you're using a type of this behavior when you run more than one program at the same time. If you're at work and you play Texas Hold 'em poker in one window while running a company sales report in another window and making a long-distance call to a friend, congratulate yourself—you're multithreading!


Getting Down to Business

At this point in your travels, you might be getting the impression that Java is primarily of use to science fiction buffs and people who have body parts to show the world. Although those two subject areas are enough to keep many of us entertained for days, the next stop on our trip shows an example of Java getting down to business.

Direct your web browser to http://www.alphatrade.com/partners-freetools.php.

This example shows several financial tools presented as Java programs: a scrolling ticker for current prices on up to 20 stocks, a U.S. and Canadian index chart that can be customized, and a "snap quote" price report. Figure 3.5 shows these three programs running.

Figure 3.5. Java programs from AlphaTrade.com that are used to analyze stock market prices and overall indices.

[View full size image]

Unlike other stock analysis programs that require the installation of software on the computers of each employee who needs access, the use of Java enables AlphaTrade.com to make the programs available to anyone with a web browser—all the employees would have to do is access the company's website.

A program such as AlphaTrade.com's stock ticker applet can be thought of in several different ways. One way is to think of a program as an object—something that exists in the world, takes up space, and has certain things it can do. Java, like the C++ language, uses object-oriented programming, as you will see during Hour 10, "Creating Your First Object." Object-oriented programming (OOP) is a way of thinking about computer programs. A program is thought of as a group of objects. Each object handles a specific task and knows how to speak to other objects. For example, a word processing program could be set up as the following group of objects:

  • A document object, which is the area where you type in text

  • A spell-checking object, which can look over the document object to find any possible spelling errors

  • A printer object, which handles the printing of the document

  • A menu object, a mouse object, and many others

The word processing software is a collection of all the objects necessary to get work done.

OOP is a powerful way to create programs, and it makes the programs you write more useful. Consider the word processing software. If the programmer wants to use the spell-checking capabilities of that program with some other software, the spell-checking object is ready for use with the new program. No changes need to be made.


Stopping by Gamelan to Ask Directions

This world tour of Java programs is being led by a professional who is well-versed in the hazards and highlights of web-based travel. You'll be venturing out on your own trips soon, so it's worthwhile to stop at one of the best guides currently available for the tourist who wants to see Java: Gamelan at http://www.developer.com/java.

Gamelan features one of the most comprehensive directories of Java programs, programming resources, and other information related to the language. Many of the programs visited during this hour were originally found on a trek through the searchable database maintained by Gamelan. Updates are made on a daily basis, so this is another place you'll be visiting often as you develop your Java programming skills.

One of the best uses of Gamelan for programmers is to see what programs are available that offer source code. In case you're unfamiliar with the term, source code is another name for the text files that are used to create computer programs. The Saluton.java file you developed during Hour 2 is an example of source code.

Gamelan's Java Applet Ratings Service (JARS), a directory of Java applets and other resources at the web address http://www.jars.com, often includes programs that are accompanied by the source code used to create them. After you have finished your first 24 hours as a Java programmer, you ought to take a look at some of these programs. The large number of Java programs listed in JARS shows that the language has become adopted by thousands of programmers around the world. Part of the reason is that Java's popularity inspires people to learn it, which is the same principle that caused parachute pants and break dancing to be briefly popular in the mid-'80s. Another reason for the swiftly growing population of Java programmers is the simplicity of the language.

One of the goals of Java's design was to make it easier to learn than C++, the language James Gosling was having fits with on Sun's smart-appliance project. Much of Java is based on C++, so programmers who have learned to use that language will find it easier to learn Java. However, some of the elements of C++ that are the hardest to learn—and the hardest to use correctly—have been removed from Java.

For people who are learning programming for the first time, Java is easier to learn than C++ would be. Also, Java will not work if its variables and other elements of a program are used incorrectly. This adherence to rules can be painful for experienced programmers, but it forces everyone to develop good habits as they create programs.

Some languages are created to make it easier for experienced programmers to harness the capabilities of the computer in their programs. These languages include shortcuts and other features that programming veterans easily understand. Java does not use these features, preferring to make the language as simple as an object-oriented programming language can be. Java was created to be easy to learn, easy to debug, and easy to use.

Because the first experience that most people had with Java was on the Web, it is often thought of strictly as a Web-related programming language. However, Java is not limited to use on the Internet. You can use it to write any kind of software.

Java 2 includes numerous enhancements that make Java a worthy competitor to languages such as Microsoft Visual C++.

One of these enhancements is Swing, a feature that makes it possible to create sophisticated user interfaces for Java programs. These interfaces have a special feature called look-and-feel that enables a Java program to mimic the appearance of different operating systems. Programs can be written to look like Windows software, Mac software, or even a unique-to-Java look-and-feel called Metal.

Sun Microsystems has put its emphasis in recent years on turning Java into a fully capable software development language no matter where the program will run.


Workshop: Venturing into Another World

The last stop on your whirlwind tour of Java is Wurm Online, a multiplayer Internet game that has been developed entirely with the language. Grab your broadsword, wipe the Doritos crumbs off your tunic, and direct your browser to http://www.wurmonline.com.

Wurm belongs to a class of computer games called massively multiplayer online role-playing games, or MMORPGs (don't ask me how that's supposed to be pronounced). You can create a character and begin playing him for free, but the developers charge a subscription fee after you become massively addicted.

As this hour's workshop, visit the Wurm website and click the link to launch the program. When you run Wurm for the first time, a Java Web Start dialog appears like the one shown in Figure 3.6.

Figure 3.6. Loading a Java program with Java Web Start, a new way to set up software over the Internet.

Java Web Start makes it possible to install software over the Web by simply clicking a link on a page. The programs loaded in this manner don't have the security restrictions of the applets you've visited during this hour, so you must give your OK before they are installed.

When a program has been installed with Java Web Start, you can run it like any other software on your computer.

Wurm Online will be a familiar kind of game to players of EverQuest and other MMORPGs. You create a character who wanders through a 3-D world with the arrow keys on the keyboard, looking for people to talk to and things to kill. A screenshot of the game is shown in Figure 3.7.

Figure 3.7. Using Java Web Start, games such as Wurm Online and other software can be installed by clicking a link on a web page.

[View full size image]


Summary

Once you've freed yourself from the massive world of Wurm, it's time to put away your luggage and get ready for a return to programming.

More websites and other items of note for Java programmers are described in Appendix D, "Where to Go From Here: Java Resources."


Q&A

Q1:

Can I use the sample Java programs from the Sun Microsystems website on my own home page?

A1:

Sun encourages the use of its sample programs on websites. In addition to the programs available at http://java.sun.com, take a look at the folders that were created when you installed the Java Development Kit on your system. If you installed the demo programs along with the Kit, you will find more than two dozen sample programs along with the .java files that were used to compile them. These programs can be a valuable resource when you're working on your own Java programs later.

Q2:

What is the difference between Java applets and ActiveX controls?

A2:

ActiveX, an extension of Microsoft technology called the Component Object Model, offers support for interactive web programs that are similar in function to Java programs. They are placed on web pages and run when browsers are equipped to handle them. The primary differences are that ActiveX relies on a system to verify the identity of ActiveX programmers and ActiveX programs are not downloaded each time they are encountered. Unlike Java programs, an ActiveX program stays on a user's system. Also, an ActiveX program is not restricted in what it can do on a system, while Java programs run from web pages face very strong restrictions in what they can do.

Q3:

I ran a useful Java program on a web page. Can I run it on my system without the browser?

A3:

Under mostcircumstances, no. Java programs typically are developed to run on a web page or to run from the command line. A program can be written so that it works in both ways, but most of the programs you will find in a directory such as EarthWeb do not include this functionality. You'll learn much more about the different types of Java programs during Hour 4, "Understanding How Java Programs Work."

Q4:

What's the difference between J2SE (Java 2 Standard Edition) and J2EE (Java 2 Enterprise Edition)? Does J2EE cost money?

A4:

Java 2 Enterprise Edition is an expansion of the Java 2 Standard Edition that includes packages to support advanced technology such as Enterprise JavaBeans, XML processing, and the development of servlets, Java programs that run on a web server. J2EE also includes an application server, a sophisticated environment for executing Java software that's tailored for corporations and other large organizations with heavy computing needs. The J2EE development kit can be downloaded at no cost from Sun at http://java.sun.com/j2ee.

Q5:

Can a Java program I run on a web page give my computer a virus?

A5:

Because of general security restrictions that prevent web programs from reading, writing, or modifying files, there's no way for a virus to be transmitted from a Java program on a web page to your system unless you gave the program full permission to access the hard drive on your system. Java programs you download and run from the command line have the same risk of viruses as any program you download. If you're using programs received over the Internet, you need to acquire a good antivirus program and use it regularly.

Q6:

What makes the lights in tennis shoes light up—batteries or chemicals?

A6:

The light comes from a watch-type battery encased in a temperature-resistant epoxy that is activated when the wearer moves. A wire vibrates, completing a circuit in the battery.

These shoe batteries normally last around four to six months. They were invented by shoe company L.A. Gear.


Quiz

If your mind hasn't taken a vacation by this point in the hour, test your knowledge of this chapter with the following questions.

Questions

1:

How did object-oriented programming get its name?

  1. Programs are considered to be a group of objects working together.

  2. People often object because it's hard to master.

  3. Its parents named it.

2:

Which of the following isn't a part of Java's security?

  1. Web programs cannot run programs on the user's computer.

  2. The identity of a program's author is always verified.

  3. Java windows are labeled as Java windows.

3:

What is a program's capability to handle more than one task called?

  1. Schizophrenia

  2. Multiculturalism

  3. Multithreading

Answers

A1: | a. It's also abbreviated as OOP.
A2: | b. ActiveX programs verify the author of the program, but this security method is not implemented as a standard security measure of Java. Programmers can use digital signatures and an identity verifying company like VeriSign in Java, but it isn't required.
A3: | c. This also is called multitasking, but the term multithreading is used in conjunction with Java because an independently running part of a program is called a thread.


Activities

Before unpacking your luggage, you can explore the topics of this hour more fully with the following activities:

  • Use the Java Applet Ratings Service website at http://www.jars.com to find out what card games have been developed using the language.

  • Find the sample Java programs by searching Sun's official Java site and download one of them to your computer.

When solutions can be provided for the activities in this book, they'll be presented on the book's website at http://www.java24hours.com.


Hour 4. Understanding How Java Programs Work

An important distinction to make in Java programming is where your program is supposed to be running. Some programs are intended to work on your computer; you type in a command or click an icon to start them up. Other programs are intended to run as part of a World Wide Web page. You encountered several examples of this type of program during the previous hour's whirlwind vacation.

Java programs that run locally on your own computer are called applications. Programs that run on web pages are called applets. During this hour, you'll learn why that distinction is important, and the following topics will be covered:

  • How applications work

  • Organizing an application

  • Sending arguments to an application

  • How applets work

  • The required parts of an applet

  • Sending parameters to an applet

  • Using HTML tags to put an applet on a page


Creating an Application

Although Java has become well-known because it can be used in conjunction with World Wide Web pages, you can also use it to write any type of computer program. The Saluton program you wrote during Hour 2, "Writing Your First Program," is an example of a Java application.

To try out another program, use your word processor to open up a new file and enter everything from Listing 4.1. Remember not to enter the line numbers and colons along the left side of the listing; these items are used to make parts of programs easier to describe in the book. When you're done, save the file as Root.java, making sure to save it in text-only or plain ASCII text format.

Listing 4.1. The Full Text of Root.java

1: class Root {

2:     public static void main(String[] arguments) {

3:         int number = 225;

4:         System.out.println("The square root of "

5:             + number

6:             + " is "

7:             + Math.sqrt(number) );

8:     }

9: }

The Root application accomplishes the following tasks:

  • Line 3: An integer value of 225 is stored in a variable named number.

  • Lines 4–7: This integer and its square root are displayed. The Math.sqrt (number) statement in Line 7 displays the square root.

Before you can test out this application, you need to compile it using the Java Development Kit's javac compiler or the compiler included with another Java development environment. If you're using the JDK, go to a command line, open the folder that contains the Root.java file, and then compile Root.java by entering the following at a command line:

javac Root.java

If you have entered Listing 4.1 without any typos, including all punctuation and every word capitalized exactly as shown, it should compile without any errors. The compiler responds to a successful compilation by not responding with any message at all.

Java applications are compiled into a class file that can be run by a Java interpreter. If you're using the JDK, you can run the compiled Root.class file by typing this command:

java Root

The output should be the following:

The square root of 225 is 15.0

When you run a Java application, the interpreter looks for a main() block and starts handling Java statements within that block. If your program does not have a main() block, the interpreter will respond with an error.


Sending Arguments to Applications

Because Java applications are run from a command line, you can send information to applications at the same time you run them. The following hypothetical example uses the java interpreter to run an application called Textdisplayer, and it sends two extra items of information to the application, readme.txt and /p:

java TextDisplayer readme.txt /p

Extra information you can send to a program is called an argument. The first argument, if there is one, is provided one space after the name of the application. Each additional argument is also separated by a space.

If you want to include a space inside an argument, you must put quotation marks around the argument, as in the following:

java TextDisplayer readme.txt /p "Page Title"

This example runs the Textdisplayer program with three arguments: readme.txt, /p, and Page Title. The quote marks prevent Page and Title from being treated as separate arguments.

You can send as many arguments as you want to a Java application. In order to do something with them, however, you have to write some statements in the application to handle them.

To see how arguments work in an application, create a new file in your word processor called Blanks.java. Enter the text of Listing 4.2 into the file and save it when you're done. Compile the program, correcting any errors that are caused by typos.

Listing 4.2. The Full Text of Blanks.java

1: class Blanks {

2:     public static void main(String[] arguments) {

3:         System.out.println("The " + arguments[0]

4:             + " " + arguments[1] + " fox "

5:             + "jumped over the "

6:             + arguments[2] + " dog.");

7:     }

8: }

To try out the Blanks application, run it with a Java interpreter such as the JDK's java tool. Give it three adjectives of your own choosing as arguments, as in the following example:

java Blanks retromingent purple lactose-intolerant

The application uses the adjectives to fill out a sentence. Here's the one produced by the preceding three arguments:

The retromingent purple fox jumped over the lactose-intolerant dog.

Try it with some of your own adjectives, making sure to always include at least three of them.

Arguments are a useful way to customize the performance of a program. They often are used to configure a program so it runs a specific way. Java stores arguments in arrays, groups of related variables that all hold the same information. You'll learn about arrays during Hour 9, "Storing Information with Arrays."

Watch Out!

When you run the Blanks application, you must include at least three words as command-line arguments. If not, you'll see an intimidating error message mentioning an ArrayOutOfBoundsException, something that will be complete gobbledygook for another five hours.


Applet Basics

When the Java language was introduced in 1995, the language feature that got the most attention was applets, Java programs that run on a World Wide Web page. Before Java, web pages were a combination of text, images, and forms that used Common Gateway Interface programs running on the computer that hosted the pages. These gateway programs required special access to the web server presenting the page.

Applets require no special access and can be written by programmers of all skill levels. You'll write several during the span of these 24 hours. You can test them with any web browser that handles Java programs. Most of the Java programs you toured during the previous hour were all applets. Their structure differs from applications in several important ways, and they are designed specifically for presentation on the Web.

By the Way

Because the applets you'll write in this book use Java 2, these applets must be run with a browser that supports the most current version of the language. During Hour 17, "Creating Interactive Web Programs," you'll learn how to set up a browser to use the Java plug-in to run Java 2 applets. All applets can also be tested with the appletviewer tool that is included with the Java Development Kit.

Unlike applications, applets do not have a main() block. Instead, they have several different sections that are handled depending on what is happening in the applet, as detailed fully during Hour 17. Two of the sections are the init() block statement and the paint() block. init() is short for initialization, and it is used to take care of anything that needs to be set up as an applet first runs. The paint() block is used to display anything that should be displayed.

To see an applet version of the Root application, create a new file in your word processor and call it RootApplet.java. Enter the code in Listing 4.3 and save it when you're done.

Listing 4.3. The Full Text of RootApplet.java

 1: import java.awt.*;

 2:

 3: public class RootApplet extends javax.swing.JApplet {

 4:     int number;

 5:

 6:     public void init() {

 7:         number = 225;

 8:     }

 9:

10:     public void paint(Graphics screen) {

11:        Graphics2D screen2D = (Graphics2D) screen;

12:        screen2D.drawString("The square root of " +

13:            number +

14:            " is " +

15:            Math.sqrt(number), 5, 50);

16:     }

17: }

Compile this file using your Java development software. If you are using the javac compiler tool in the JDK, type the following at a command line:

javac RootApplet.java

This program contains a lot of the same statements as the Root application that did the same thing. The primary difference is in how it is organized—the main() block has been replaced with an init() block and a paint() block.

By the Way

The sample programs in this hour are provided primarily to introduce you to the way Java programs are structured. Some aspects of these programs will be introduced fully later, so don't feel like you're falling behind. The main purpose of this hour is to get the programs to compile and see how they function when you run them.

Unlike applications, compiled Java applets cannot be tested using a Java interpreter. You have to put them on a web page and view that page in one of two ways:

  • Use a web browser that can handle Java 2 applets by using Sun's Java plug-in, which requires special configuration of the web page.

  • Use the appletviewer tool that comes with the Java Development Kit.

To create a web page that can display the RootApplet program, return to your word processor and create a new file. Enter Listing 4.4 in that file and save it as RootApplet.html.

Listing 4.4. The Full Text of RootApplet.html

1: <applet code="RootApplet.class" height="100" width="300">

2: </applet>

This web page contains the bare minimum needed to display a Java applet on a web page. The applet tag is used to specify that a Java program is being put on the page, the code attribute provides the name of the applet, and the height and width attributes describe the size of the applet's display area. These items will be described in detail during Hour 17.

To see this applet using the appletviewer tool included with Java Development Kit, type the following at a command line:

appletviewer RootApplet.html

To see it using your computer's default web browser, type the following command instead:

RootApplet.html

You also can load this page with your browser: Choose File, Open, then navigate to the folder that contains RootApplet.html and select the file.

Figure 4.1 shows what the applet looks like when loaded with Mozilla Firefox.

Figure 4.1. The RootApplet applet displayed with a web browser.

Watch Out!

If you try to load this page with your web browser and get an error, the most likely cause is that your browser is not yet equipped with the Java plug-in. To correct this, visit the web page http://java.com to download and install the free Java Runtime Environment, which includes the Java plug-in.


Sending Parameters to Applets

Java applets are never run from the command line, so you can't specify arguments the way you can with applications. Applets use a different way to receive information at the time the program is run. This configuration information is called parameters, and you can send parameters through the HTML page that runs the applet. You have to use a special HTML tag for parameters called param.

To see how the Blanks application would be rewritten as an applet, open your word processor, enter the text of Listing 4.5, then save the file as BlanksApplet.java.

Listing 4.5. The Full Text of BlanksApplet.java

 1: import java.awt.*;

 2:

 3: public class BlanksApplet extends javax.swing.JApplet {

 4:     String parameter1;

 5:     String parameter2;

 6:     String parameter3;

 7:

 8:     public void init() {

 9:         parameter1 = getParameter("adjective1");

10:         parameter2 = getParameter("adjective2");

11:         parameter3 = getParameter("adjective3");

12:     }

13:

14:     public void paint(Graphics screen) {

15:         screen.drawString("The " + parameter1

16:             + " " + parameter2 + " fox "

17:             + "jumped over the "

18:             + parameter3 + " dog.", 5, 50);

19:     }

20: }

Save the file and then compile it. Using the JDK, you can accomplish this by typing the following at the command line:

javac BlanksApplet.java

Before you can try out this applet, you need to create a web page that displays the BlanksApplet applet after sending it three adjectives as parameters. Open your word processor and enter Listing 4.6, saving it as BlanksApplet.html.

Listing 4.6. The Full Text of BlanksApplet.html

1: <applet code="BlanksApplet.class" height=80 width=500>

2: <param name="adjective1" value="lachrymose">

3: <param name="adjective2" value="magenta">

4: <param name="adjective3" value="codependent">

5: </applet>

Save the file when you're done, and load the page using Internet Explorer, the JDK's appletviewer, or another browser equipped with the Java plug-in.

The page when loaded in your browser should resemble Figure 4.2. Change the values of the value attribute in Lines 2–4 of the BlanksApplet.html file, replacing "lachrymose", "magenta", and "codependent" with your own adjectives, then save the file and run the program again. Try this several times, and you'll see that your program is now flexible enough to handle any adjectives, no matter how well or how poorly they describe the strange relationship between the fox and the dog.

Figure 4.2. The BlanksApplet program displayed with a web browser.

You can use as many parameters as needed to customize the operation of an applet, as long as each has a different name attribute specified along with the param tag.


Workshop: Viewing the Code Used to Run Applets

As a short workshop to better familiarize yourself with the applet tag and how it can be used to alter the performance of an applet, visit this book's World Wide Web site at http://www.java24hours.com.

Load this site by using one of the web browsers that can run Java applets, such as Microsoft Internet Explorer, Mozilla Firefox, or Apple Safari. Go to the section of the site labeled "Hour 4 Showcase," and you'll be given a guided tour through several working examples of applets.

On each of the pages in the Hour 4 Showcase, you can use a pull-down menu command to view the HTML tags that were used to create the page:

  • In Internet Explorer or Opera, choose View, Source.

  • In Navigator or Firefox, choose View, Page Source.

Compare the parameters that are used with each applet to the way the applet runs.

Appendix E, "This Book's Website," describes other things you can find on the book's site. The website is intended as a complement to the material covered in this book, and a way to find out about corrections, revisions, or other information that make these 24 hours more productive.


Summary

During this hour, you had a chance to create both a Java application and an applet. These two types of programs have several important differences in the way they function and the way they are created.

Both kinds of Java programs can be easily customized at the time they are run. Applications use arguments, which are specified on the command line at the time the program is run. Applets use parameters, which are included on the web page that displays the applet by using HTML tags.

The next several hours will continue to focus on applications as you become more experienced as a Java programmer. Applications are quicker to test because they don't require you to create a web page to view them; they can be easier to create and more powerful as well.


Q&A

Q1:

Can a single Java program be both an applet and an application?

A1:

It is possible to make a program serve as both applet and application, but it's often an unwieldy solution unless the program is simple. An applet could be set up to run as an application also by including a main() block in the applet, but you would not be able to use the init() block or paint() block in the automatic fashion they are used in an applet. Most programs are written as either an application or as an applet, rather than attempting to do both.

Q2:

Do all arguments sent to a Java application have to be strings?

A2:

Java makes all arguments into strings for storage when an application runs. When you want to use one of these arguments as an integer or some other non-string type, you have to convert the value. You'll learn how to do this during Hour 11, "Describing What Your Object Is Like."

Q3:

I get errors when I try to load RootApplet.html into either Mozilla Firefox or Microsoft Internet Explorer. What's the problem?

A3:

In most cases, the problem is that the browser isn't equipped to run Java 2 applets. Internet Explorer and Firefox lack support for Java 2 applets, which are run by the Java plug-in offered by Sun. When you're in doubt about why an applet won't work in a browser, try loading it with the appletviewer tool included with the Java Development Kit. If it works in appletviewer, the problem is with the browser rather than your Java applet.

Q4:

Why don't Java applets require the same kind of special access as Common Gateway Interface programs?

A4:

Java applets don't have the same access requirements because they don't pose the same risk to a website provider. A Common Gateway Interface (CGI) program is run by the provider's web server.

A web server administrator must trust the people writing gateway programs, because there's no security to prevent the program from harming the server presenting the web page, whether intentionally or by mistake.

Java applets, on the other hand, have strict restrictions to prevent them from being used to write harmful programs. Also, Java programs do not run on a website's server—they run on the computer of the person viewing the page. This also means that the server will not slow down due to numerous people running a Java applet on a page.

Q5:

In the movie, It's a Wonderful Life, Sam Wainwright cabled Bedford Falls from London authorizing his local office to advance George Bailey up to $25,000 to help him. How much would this money be worth in today's dollars?

A5:

Assuming that the scene took place on Christmas Eve 1945, Wainwright's offer was equivalent to $263,000 in current dollars.

More inflation-adjusted figures from the 1946 film: The $8,000 Bailey Building and Loan deposit stolen by Henry Potter is equal to $84,000 today and the $5,000 loan that William Bailey owed Potter in 1919 is like $61,000.

Also in 1919, George Bailey clicked a drugstore lighter and wished for a million dollars. Children today must wish for $12.3 million to be equally enriched.

S. Morgan Friedman offers an inflation calculator on the Web at http://www.westegg.com/inflation. He uses Consumer Price Index statistics from the Historical Statistics of the United States and the Statistical Abstract of the United States.


Quiz

Test your knowledge of the material covered in this chapter by answering the following questions.

Questions

1:

Which type of Java program can be run by a Java interpreter?

  1. Applets

  2. Applications

  3. None

2:

What special HTML tag is used to put a Java program onto a web page?

  1. <applet>

  2. <program>

  3. <run>

3:

If you get into a fight with someone over the way to send information to a Java application, what are you doing?

  1. Struggling over strings

  2. Arguing about arguments

  3. Feudin' for functionality

Answers

A1: | b. Applications are run with the interpreter tool, and web pages containing applets can be run with the appletviewer tool as well as Java-capable World Wide Web browsers.
A2: | a. The <applet> tag is used along with the <param> tag to send parameters to the applet. You'll learn about a second tag that can be used to present applets during Hour 17.
A3: | b. Applications receive information in the form of arguments. Can't we all just get along?


Activities

If you would like to apply your acumen of applets and applications, the following activities are suggested:

  • Check out EarthWeb's Java Applet Ratings Service website at http://www.jars.com and use the search term headline to see links and descriptions to all of the applets that have been written to display news headlines. Each of these applets uses parameters to modify the text that is displayed.

  • Write a Java applet that can handle a parameter named X and a parameter named Y. Display the two parameters in a drawString() statement like the one in the BlanksApplet program.

To see a Java program that implements the second activity, visit the book's website at http://www.java24hours.com.


    Part II: Learning the Basics of Programming

    HOUR 5 Storing and Changing Information in a Program

    HOUR 6 Using Strings to Communicate

    HOUR 7 Using Conditional Tests to Make Decisions

    HOUR 8 Repeating an Action with Loops


Hour 5. Storing and Changing Information in a Program

In Hour 2, "Writing Your First Program," you used a variable, a special storage place that is designed to hold information. The information stored in variables can be changed as your program runs, which is why they're called variables.

Your first program stored a string of text in a variable called greeting. Strings are only one type of information that can be stored in variables. They also can hold characters, integers, floating-point numbers, and other things.

During this hour, you'll learn more about using variables in your Java programs, including the following topics:

  • Creating variables

  • The different types of variables

  • Storing values into variables

  • Using variables in mathematical expressions

  • Putting one variable's value into another variable

  • Increasing and decreasing a variable's value


Statements and Expressions

Computer programs are a set of instructions that tell the computer what to do. Each of these instructions is called a statement. The following example from a Java program is a statement:

int HighScore = 400000;

You can use brackets to group a set of statements together in a Java program. These groupings are called block statements. Consider the following portion of a program:

1: public static void main(String[] arguments) {

2:    int a = 3;

3:    int b = 4;

4:    int c = 8 * 5;

5: }

Lines 2–4 of this example are a block statement. The opening bracket on Line 1 denotes the beginning of the block, and the closing bracket on Line 5 denotes the end of the block.

Some statements are called expressions because they involve a mathematical expression and produce a result. Line 4 in the preceding example is an expression because it sets the value of the c variable equal to 8 multiplied by 5. You'll be working with several different types of expressions throughout the coming sections.


Assigning Variable Types

Variables are the main way that a computer remembers something as it runs a program. The Saluton program in Hour 2 used the greeting variable to hold "Saluton mondo!", a message in Esperanto. The computer needed to remember that text a little later, so that the message could be displayed.

In a Java program, variables are created with a statement that must include two things:

  • The name of the variable

  • The type of information the variable will store

To see the different types of variables and how they are created, load the word processor you're using to write programs and set it up to start a new file. You will be creating a program called Variable.

Give your new file the name Variable.java and start writing the program by entering the following lines:

class Variable {

    public static void main(String[] arguments) {

        // Coming soon: variables

    }

}

Go ahead and save these lines before making any changes.

Integers and Floating-Point Numbers

So far, the Variable program has a main() block with only one statement in it—the comment // Coming soon: variables. Delete the comment and enter the following statement in its place:

int tops;

This statement creates a variable named tops. It does not specify a value for tops, so for the moment this variable is an empty storage space. The int text at the beginning of the statement designates tops as a variable that will be used to store integer numbers. You can use the int type to store most of the non-decimal numbers you will need in your computer programs. It can hold any integer ranging from –2.14 billion to 2.14 billion.

Create a blank line after the int tops statement and add the following statement:

float gradePointAverage;

This statement creates a variable with the name gradePointAverage. The float text stands for floating-point numbers. Floating-point variables are used to store numbers that might contain a decimal point.

By the Way

A floating-point variable can be used to store a grade-point average, such as 2.25, to pick a number that's dear to my heart. It also can be used to store a number such as 0, which is the percentage chance of getting into a good graduate school with that grade point average, despite my really good cover letter and a written recommendation from my parole officer.

Characters and Strings

Because the variables you have dealt with so far are numeric, you might have the impression that all variables are used as a storage place for numbers. Think again. You also can use variables to store text. Two types of text can be stored as variables: characters and strings. A character is a single letter, number, punctuation mark, or other symbol. Most of the things you can use as characters are shown on your computer's keyboard. A string is a group of characters.

Your next step in creating the Variable program is to create a char variable and a String variable. Add these two statements after the line float gradePointAverage:

char key = 'C';

String productName = "Larvets";

When you are using character values in your program, such as in the previous example, you must put single quotation marks on both sides of the character value being assigned to a variable. You must surround string values with double quotation marks. These quotation marks are needed to prevent the character or string from being confused with a variable name or other part of a statement. Take a look at the following statement:

String productName = Larvets;

This statement might look like a statement that tells the computer to create a string variable called productName and give it the text value of Larvets. However, because there are no quotation marks around the word Larvets, the computer is being told to set the productName value to the same value as a variable named Larvets.

By the Way

If you're wondering about Larvets, the product mentioned in this section, it's a snack made from edible worms that have been killed, dried, and mixed with the same kinds of nuclear flavoring as Doritos chips. You can order Larvets in three flavors—BBQ, cheddar cheese, and Mexican spice—from the mail-order retailer HotLix at the website http://www.hotlix.com/larvets.htm or by calling 1-800-EAT-WORM.

After adding the char and String statements, your program will resemble Listing 5.1. Make any changes that are needed and be sure to save the file. This program does not produce anything to display, but you should compile it with your Java compiler to make sure it was created correctly.

Listing 5.1. The Variable Program

1: class Variable {

2:    public static void main(String[] arguments) {

3:       int tops;

4:       float gradePointAverage;

5:       char key = 'C';

6:       String productName = "Larvets";

7:    }

8: }

To compile the program using the JDK compiler, type the following command:

javac Variable.java

The last two variables in the Variable program use the = sign to assign a starting value when the variables are created. You can use this option for any variables you create in a Java program, as you'll discover later in this hour.

By the Way

Although the other variable types are all lowercase letters (int, float, and char), the capital letter is required in the word String when creating string variables. A string in a Java program is somewhat different from the other types of information you will use in variables. You'll learn about this distinction in Hour 6, "Using Strings to Communicate."

Other Numeric Variable Types

The variables you have been introduced to so far will be the main ones you use during this book and probably for most of your Java programming. There are a few other types of variables you can use in special circumstances.

You can use three other variable types with integers. The first, byte, can be used for integer numbers that range from –128 to 127. The following statement creates a variable called escapeKey with an initial value of 27:

byte escapeKey = 27;

The second, short, can be used for integers that are smaller in size than the int type. A short integer can range from –32,768 to 32,767, as in the following example:

short roomNumber = 222;

The last of the numeric variable types, long, is typically used for integers that are too big for the int type to hold. A long integer can be almost any size: If the number has five commas or fewer when you write it down, it can fit into a long. Some six-comma numbers can fit as well.

Except for times when your integer number is bigger than 2.14 billion or smaller than –2.14 billion, you won't need to use any of these special variable types very often. If they're muddling your understanding of variable types, concentrate on int and float. Those types are the ones you'll be using most often.

The boolean Variable Type

Java has a special type of variable called boolean that only can be used to store the value true or the value false. At first glance, a boolean variable might not seem particularly useful unless you plan to write a lot of computerized true-or-false quizzes. However, boolean variables will be used in a variety of situations in your programs. The following are some examples of questions that boolean variables can be used to answer:

  • Has the user pressed a key?

  • Is the game over?

  • Is this the first time the user has done something?

  • Is the bank account overdrawn?

  • Have all 10 images been displayed onscreen?

  • Can the rabbit eat Trix?

The following statement is used to create a boolean variable called gameOver:

boolean gameOver = false;

This variable has the starting value of false, and a statement such as this one can be used in a game program to indicate that the game isn't over yet. Later on, when something happens to end the game (such as the destruction of all the player's acrobatic turtle-squashing Italian plumbers), the gameOver variable can be set to true.

Although the two possible boolean values—TRue and false—look like strings in a program, you should not surround them with quotation marks. Hour 7, "Using Conditional Tests to Make Decisions," describes boolean variables more fully.

By the Way

Boolean numbers are named for George Boole, who lived from 1815 to 1864. Boole, a mathematician who was mostly self-taught until late adulthood, invented Boolean algebra, a fundamental part of computer programming, digital electronics, and logic. One imagines that he did pretty well on true-false tests as a child.


Naming Your Variables

Variable names in Java can begin with a letter, underscore character (_), or a dollar sign ($). The rest of the name can be any letters or numbers, but you cannot use blank spaces. You can give your variables any names you like under those rules, but you should be consistent in how you name variables. This section outlines the generally recommended naming method for variables.

Watch Out!

Java is case-sensitive when it comes to variable names, so you must always capitalize variable names in the same way throughout a program. For example, if the gameOver variable is used as GameOver somewhere in the program, the use of GameOver will cause an error when you compile the program.

For starters, the name you give a variable will describe its purpose in some way. The first letter should be lowercase, and if the variable name has more than one word, make the first letter of each subsequent word a capital letter. For instance, if you wanted to create an integer variable to store the all-time high score in a game program, you can use the following statement:

int allTimeHighScore;

You can't use punctuation marks or spaces in a variable name, so neither of the following will work:

int all-TimeHigh Score;

int all Time High Score;

If you tried to use these names in a program, the Java compiler will respond with an error.


Storing Information in Variables

You can put a value into a variable at the same time that you create the variable in a Java program. You also can put a value in the variable at any time later in the program.

To set up a starting value for a variable upon its creation, use the equal sign (=). The following is an example of creating a floating-point variable called pi with the starting value of 3.14:

float pi = 3.14;

All variables that store numbers can be set up in a similar fashion. If you're setting up a character or a string variable, quotation marks must be placed around the value as shown previously.

You also can set one variable equal to the value of another variable if they both are of the same type. Consider the following example:

int mileage = 300;

int totalMileage = mileage;

First, an integer variable called mileage is created with a starting value of 300. In the second line, an integer variable called totalMileage is created with the same value as mileage. Both variables will have the starting value of 300. In future hours, you will learn how to convert one variable's value to the type of another variable.

Watch Out!

If you do not give a variable a starting value, you must give it a value before you try to use it. If you don't, when you attempt to compile your program, the javac compiler will respond with an error message such as the following:

WarGame.java:7: Variable warships may not have been initialized.

               warships = warships + 10;

               ^

1 error

Another naming convention in Java is to capitalize the names of variables that will not change in value. These variables are called constants. The following creates three constants:

int TOUCHDOWN = 6;

int FIELDGOAL = 3;

int PAT = 1;

Because constants never change in value, you might wonder why one should ever be used—you can just use the value assigned to the constant instead. One of the advantages of using constants is that they can make a program easier to understand. For example, the variables Font.BOLD and Font.ITALIC are constants that hold integer values representing the style of the current font.


Workshop: Using Expressions

When you were younger in school, as you worked on a particularly unpleasant math problem, did you ever complain to a higher power, protesting that you would never use this knowledge in your life? Sorry to break this to you, but all your teachers were right—those math skills are going to be used in your computer programming.

That's the bad news. The good news is that the computer will do any of the math you ask it to do. As mentioned earlier in this hour, any instructions you give a computer program involving math are called expressions. Expressions will be used frequently in your computer programs. You can use them for tasks such as the following:

  • Changing the value of a variable

  • Counting the number of times something has happened in a program

  • Using a mathematical formula in a program

As you write computer programs, you will find yourself drawing on your old math lessons as you use expressions. Expressions can use addition, subtraction, multiplication, division, and modulus division.

To see expressions in action, return to your word processor and close the Variable.java file if it is still open. Create a new file and save it as Elvis.java. The Elvis program creates a virtual person whose weight loss and gain can be tracked with mathematical expressions. Instead of adding statements to the program piece-by-piece, enter the full text of Listing 5.2 into the word processor. Each part of the program will be discussed in turn.

Listing 5.2. The Elvis Program

 1: class Elvis {

 2:     public static void main(String[] arguments) {

 3:         int weight = 250;

 4:         System.out.println("Elvis weighs " + weight);

 5:         System.out.println("Elvis visits all-you-can-eat rib joint.");

 6:         System.out.println("Elvis throws Thanksgiving luau.");

 7:         weight = weight + 10;

 8:         System.out.println("Elvis now weighs " + weight);

 9:         System.out.println("Elvis discovers aerobics.");

10:         weight = weight - 15;

11:         System.out.println("Elvis now weighs " + weight);

12:         System.out.println("Elvis falls into washing machine during "

13:             + "shrink cycle.");

14:         weight = weight / 3;

15:         System.out.println("Elvis now weighs " + weight);

16:         System.out.println("Oops! Elvis clones himself 12 times.");

17:         weight = weight + (weight * 12);

18:         System.out.println("The 13 Elvii now weigh " + weight);

19:     }

20: }

When you're done, save the file and compile the program. If you're using the JDK in the same folder as the Elvis.java file, type the following at a command line to compile the Elvis application:

javac Elvis.java

If it compiles without any errors, you will not see any output; javac only responds if something goes wrong. If you do see error messages, check the line number that is listed in each error message to look for typos. Correct any typos you find and compile the program.

Next, run the program. JDK users should type the following at a command line:

java Elvis

Listing 5.3 shows the output for this program.

Listing 5.3. The Output of the Elvis Program

Elvis weighs 250

Elvis visits all-you-can-eat rib joint.

Elvis throws Thanksgiving luau.

Elvis now weighs 260

Elvis discovers aerobics.

Elvis now weighs 245

Elvis falls into washing machine during shrink cycle.

Elvis now weighs 81

Oops! Elvis clones himself 12 times.

The 13 Elvii now weigh 1053

As in the other programs you have created, the Elvis program uses a main() block statement for all its work. This statement can be broken into the following five sections:

  1. Lines 3–4: The initial weight of Elvis is set to 250.

  2. Lines 5–8: Elvis gains weight.

  3. Lines 9–11: Elvis loses weight.

  4. Lines 12–15: Elvis reduces in size dramatically.

  5. Lines 16–18: Elvis multiplies.

Line 3 creates the weight variable and designates it as an integer variable with int. The variable is given the initial value 250 and used throughout the program to monitor Elvis' weight.

The next line is similar to several other statements in the program:

System.out.println("Elvis weighs " + weight);

The System.out.println() command displays a string that is contained within its parenthesis marks. In the preceding line, the text "Elvis weighs" is displayed, followed by the value of the weight variable. There are numerous System.out.println() statements in the program. If you're still unclear about how these statements work, look at each of them in Listing 5.2 and compare them to the corresponding lines in Listing 5.3.


All about Operators

Four different mathematical expressions are used in the Elvis program—to add weight to Elvis, subtract weight from Elvis, divide Elvis, and finish off with some multiplied Elvii. Each of these expressions uses symbols (+, -, *, /, and %) called operators. You will be using these operators to crunch numbers throughout your Java programs.

An addition expression in Java uses the + sign, as in Line 7 of your program:

weight = weight + 10;

This line sets the weight variable equal to its current value plus 10. Because the weight was set to 250 when it was created, Line 7 changes weight to 260.

A subtraction expression uses the - sign, as in Line 10:

weight = weight - 15;

This expression sets the weight variable equal to its current value minus 15. The weight variable is now equal to 245.

A division expression uses the / sign, as in Line 14:

weight = weight / 3;

The weight variable is set to its current value divided by 3 and rounded down because weight is an integer. The weight variable is now equal to 81.

There's another expression you can use to find the remainder of an integer division. When the value of the weight variable was divided by 3 in Line 14, a remainder of 2 was discarded in order for weight to remain as an integer value. To find a remainder from a division expression, use the % operator. You can use the following statement to find the remainder of 245 divided by 3:

int remainder = 245 % 3;

A multiplication expression uses the * sign. Line 17 uses a multiplication expression as part of a more complicated statement:

weight = weight + (weight * 12);

The weight * 12 part of the expression multiplies weight by 12. The full statement takes the current value of weight and adds it to weight multiplied by 12. This example shows how more than one expression can be combined in a statement. The result is that weight becomes 1,053—in other words, 81 + (81 * 12).

Incrementing and Decrementing a Variable

A common task in programs is to change the value of a variable by one. You can increase the value by one, which is called incrementing the variable, or decrease the value by one, which is decrementing the variable. There are operators to accomplish each of these tasks.

To increment the value of a variable by one, use the ++ operator, as in the following statement:

x++;

This statement adds one to the value stored in the x variable.

To decrement the value of a variable by one, use the -- operator:

y--;

This statement reduces y by one.

You also can put the increment and decrement operators in front of the variable name, as in the following statements:

++x;

--y;

Putting the operator in front of the variable name is called prefixing, and putting it after the name is called postfixing. You probably have many cherished memories of grade school language lessons, when you learned about prefixes such as "pre-", "extra-", and "sub-". A prefixed operator is like a prefix in a word—it comes first. Postfixed operators lag behind. (If your memories of those classes are not-so-cherished, you must not have sat behind Mary Beth Farkas.)

Although it might seem redundant for Java to include both prefixed and postfixed operators, the difference becomes important when you use the increment and decrement operators inside an expression.

Consider the following statements:

int x = 3;

int answer = x++ * 10;

What does the answer variable equal after these statements are handled? You might expect it to equal 40—which would be true if 3 was incremented by 1, which equals 4, and then 4 was multiplied by 10.

However, answer is set to 30. The reason is that the postfixed operator was used instead of the prefixed operator.

When a postfixed operator is used on a variable inside an expression, the variable's value won't change until after the expression has been completely evaluated. The statement int answer = x++ * 10 does the same thing, in the same order, as the following two statements:

int answer = x * 10;

x++;

The opposite is true of prefixed operators. If they are used on a variable inside an expression, the variable's value changes before the expression is evaluated.

Consider the following statements:

int x = 3;

int answer = ++x * 10;

This does result in the answer variable being equal to 40. The prefixed operator causes the value of the x variable to be changed before the expression is evaluated. The statement int answer = ++x * 10 does the same thing, in order, as these statements:

x++;

int answer = x * 10;

At this point, you might be ready to say, "Prefixing, postfixing, incrementing, decrementing—let's call the whole thing off!" It's easy to become exasperated with the ++ and -- operators, because they're not as straightforward as many of the concepts you'll encounter in this book.

There's some good news: You don't need to use the increment and decrement operators in your own programs. You can achieve the same results by using the + and – operators. Incrementing and decrementing are useful shortcuts, but taking the longer route in an expression is fine, too.

By the Way

During Hour 1, "Becoming a Programmer," the name of the C++ programming language was described as a joke you'd understand later. Now that you've been introduced to the increment operator ++, you have all the information you need to figure out why C++ has two plus signs in its name instead of just one. Prepare to laugh: Because C++ adds new features and functionality to the C programming language, it can be considered an incremental increase to C. Hence the name C++. After you work through all 24 hours of this book, you, too, will be able to tell jokes that are incomprehensible to more than 99 percent of the world's population.

Operator Precedence

When you are using an expression with more than one operator, you need to know what order the computer will use as it works out the expression. Consider the following statements:

int y = 10;

x = y * 3 + 5;

Unless you know what order the computer will use when working out the math in this expression, you cannot be sure what the x variable will be set to. It could be set to either 35 or 80, depending on whether y * 3 is evaluated first or 3 + 5 is evaluated first.

The following order is used when working out an expression:

  1. Incrementing and decrementing take place first.

  2. Multiplication, division, and modulus division occur next.

  3. Addition and subtraction follow.

  4. Comparisons take place next.

  5. The equal sign (=) is used to set a variable's value.

Because multiplication takes place before addition, you can revisit the previous example and come up with the answer:

int y = 10;

x = y * 3 + 5;

In the last statement, y is multiplied by 3 first, which equals 30, and then 5 is added. The x variable is set to 35.

Comparisons will be discussed during Hour 7. The rest has been described during this hour, so you should be able to figure out the result of the following statements:

int x = 5;

int number = x++ * 6 + 4 * 10 / 2;

These statements set the number variable equal to 50.

How does the computer come up with this total? First the increment operator is handled, and x++ sets the value of the x variable to 6. However, make note of the fact that the ++ operator is postfixed after x in the expression. This means that the expression is evaluated with the original value of x.

Because the original value of x is used before the variable is incremented, the expression becomes the following:

int number = 5 * 6 + 4 * 10 / 2;

Now, multiplication and division are handled from left to right. First, 5 is multiplied by 6, 4 is multiplied by 10, and that result is divided by 2 (4 * 10 / 2). The expression becomes the following:

int number = 30 + 20;

This expression results in the number variable being set to 50.

If you want an expression to be evaluated in a different order, you can use parentheses to group parts of an expression that should be handled first. For example, the expression x = 5 * 3 + 2; would normally cause x to equal 17 because multiplication is handled before addition. However, look at a modified form of that expression:

x = 5 * (3 + 2);

In this case, the expression within the parentheses is handled first, so the result equals 25. You can use parentheses as often as needed in a statement.


Summary

Now that you have been introduced to variables and expressions, you can give a wide range of instructions to your computer in a program. With the skills you have developed during this hour, you can write programs that accomplish many of the same tasks as a calculator, handling sophisticated mathematical equations with ease.

Numbers are only one kind of thing that can be stored in a variable. You also can store characters, strings of characters, and special true or false values called boolean variables. The next hour will expand your knowledge of String variables and how they are used.


Q&A

Q1:

Is a line in a Java program the same thing as a statement?

A1:

No. Although the programs you will create in this book put one statement on each line, this is done to make the programs easier to understand; it's not required.

The Java compiler does not consider lines, spacing, or other formatting issues when compiling a program. The compiler just wants to see semicolons at the end of each statement. You can put more than one statement on a line, although this makes a program more difficult for humans to understand when they read its source code. For this reason, it is not generally recommended.

Q2:

Is there a reason to set up a variable without giving it a value right away?

A2:

For many of the simple programs you will be creating in the first several hours, no. However, there are many circumstances where it makes more sense to give a variable a value at some point later in the program. One example would be a graphical calculator program. The variable that stores the result of a calculation would not be needed until a user tries out the program's calculator buttons.

Q3:

What's the specific range for the long variable type?

A3:

In Java, a long integer variable can be anything from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. This range ought to give your mathematical expressions plenty of breathing room when you can't use int, which has a range of –2,147,483,648 to 2,147,483,647.

Q4:

Why should the first letter of a variable name be lowercase, as in gameOver?

A4:

It makes the variable easier to spot among all the other elements of a Java program. Also, by following a consistent style in the naming of variables, you eliminate errors that can occur when you use a variable in several different places in a program. The style of naming used in this book has become adopted by most Java programmers over the years.

Q5:

Can two variables have the same letters but different capitalization, as in highScore and HighScore?

A5:

Each of the differently capitalized names would be treated as its own variable, so it's possible to use the same name twice in this way. However, it seems likely to cause a lot of confusion when you or someone else is attempting to figure out how the program works. It also increases the likelihood of using the wrong variable name somewhere in your program, which is an error that will not be caught during compilation. Errors such as that that make it into the finished product are called logic errors. They must be caught by an attentive programmer during testing.

Q6:

Why do a lot of products have a "CE" on their label printed with stylized Greek letters?

A6:

The mark signifies that the product is approved for export to 18 countries in the European Union and European Free Trade Association.

CE stands for the French conformité Européenne, which means "European conformity." All products that fall under health, safety, and environmental protection laws in those countries require the mark.

More than you ever wanted to know about CE marking can be found on the Web at http://www.ce-mark.com.


Quiz

Test your knowledge of variables, expressions, and the rest of the information in this hour by answering the following questions.

Questions

1:

What do you call a group of statements that is contained with an opening bracket and a closing bracket?

  1. A block statement

  2. Groupware

  3. Bracketed statements

2:

A boolean variable is used to store true or false values.

  1. True

  2. False

  3. No, thanks. I already ate.

3:

What characters cannot be used to start a variable name?

  1. A dollar sign

  2. Two forward slash marks (//)

  3. A letter

Answers

A1: | a. The grouped statements are called a block statement, or a block.
A2: | a. true and false are the only answers a boolean variable can store.
A3: | b. Variables can start with a letter, a dollar sign ($), or an underscore character (_). If you started a variable name with two slash marks, the rest of the line would be ignored because the slash marks are used to start a comment line.


Activities

You can review the topics of this hour more fully with the following activities:

  • Expand the Elvis program to track the weight if it were incremented upward by one pound for three straight days (Krispy Kreme donut binge).

  • Create a short Java program that uses an x integer and a y integer and displays the result of x squared plus y squared.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


Hour 6. Using Strings to Communicate

In the film The Piano, Holly Hunter portrays Ada, a young Scottish woman who marries badly. A mute since the age of six, Ada can only express herself fully by playing her prized possession, a piano.

Like Ada, your computer programs are capable of quietly doing their work and never stopping for a chat—or piano recital—with humans. However, if The Piano teaches us anything, it is that communication ranks up there with food, water, and shelter as an essential need. (It also teaches us that the actor Harvey Keitel has a lot of body confidence, but that's a matter for another book.)

Java programs don't have access to a piano. They use strings as the primary means to communicate with users. Strings are collections of text—letters, numbers, punctuation, and other characters. During this hour, you will learn all about working with strings in your Java programs. The following topics will be covered:

  • Using strings to store text

  • Displaying strings in a program

  • Including special characters in a string

  • Pasting two strings together

  • Including variables in a string

  • Comparing two strings

  • Determining the length of a string

  • Changing a string to upper- or lowercase


Storing Text in Strings

Strings are a common feature in computer programming because they provide a way to store text and present it to users. The most basic element of a string is a character. A character is a single letter, number, punctuation mark, or other symbol.

In Java programs, a character is one of the types of information that can be stored in a variable. Character variables are created with the char type in a statement such as the following:

char keyPressed;

This statement creates a variable named keyPressed that can store a character. When you create character variables, you can set them up with an initial value, as in the following:

char quitKey = '@';

Note that the value of the character must be surrounded by single quotation marks. If it isn't, the javac compiler tool will respond with an error when the program is compiled.

A string is a collection of characters. You can set up a variable to hold a string value by following String with the name of the variable, as in this statement:

String fullName = "Ada McGrath Stewart";

This statement creates a string variable called fullName and stores the text Ada McGrath Stewart in it, which is the full name of Hunter's pianist. A string is denoted with double quotation marks around the text in a Java statement. These quotation marks will not be included in the string itself.

Unlike the other types of variables you have used—int, float, char, boolean, and so on—the name of the String type is capitalized.

The reason for this is that strings are somewhat different than the other variable types in Java. Strings are a special data resource called objects, and the types of all objects are capitalized. You'll be learning about objects during Hour 10, "Creating Your First Object." The important thing to note during this hour is that strings are different than the other variable types, and because of this difference, String is capitalized when strings are used in a statement.


Displaying Strings in Programs

The most basic way to display a string in a Java program is with the System.out.println() statement. This statement takes any strings and other variables inside the parentheses and displays their values. The following statement displays a line of text to the system output device, which is the computer's monitor:

System.out.println("Silence affects everyone in the end.");

The preceding statement would cause the following text to be displayed:

Silence affects everyone in the end.

Displaying a line of text on the screen is often called printing, which is what println() stands for—"print this line." You can use the System.out.println() statement to display text within double quotation marks and also to display variables, as you will see. Put all the material you want to be displayed within the parentheses.

Another way to display text is to call System.out.print(). This statement displays strings and other variables inside the parentheses, but unlike System.out.println(), it allows subsequent statements to display text on the same line.

You can use System.out.print() several times in a row to display several things on the same line, as in this example:

System.out.print("She ");

System.out.print("never ");

System.out.print("said ");

System.out.print("another ");

System.out.println("word.");

These statements cause the following text to be displayed:

She never said another word.


Using Special Characters in Strings

When a string is being created or displayed, its text must be enclosed within double quotation marks to indicate the beginning and end of the string. These quotation marks are not displayed, which brings up a good question: What if you want to display double quotation marks?

To display them, Java has created a special code that can be put into a string: \". Whenever this code is encountered in a string, it is replaced with a double quotation mark. For example, examine the following:

System.out.println("Jane Campion directed \"The Piano\" in 1993.");

This code is displayed as the following:

Jane Campion directed "The Piano" in 1993.

You can insert several special characters into a string in this manner. The following list shows these special characters; note that each is preceded by a backslash (\).

Special characters | Display
\' | Single quotation mark
\" | Double quotation mark
\\ | Backslash
\t | Tab
\b | Backspace
\r | Carriage return
\f | Formfeed
\n | Newline

The newline character causes the text following the newline character to be displayed at the beginning of the next line. Look at this example:

System.out.println("Music by\nMichael Nyman");

This statement would be displayed as the following:

Music by

Michael Nyman


Pasting Strings Together

When you use the System.out.println() statement and handle strings in other ways, you will sometimes want to paste two strings together. You do this by using the same operator that is used to add numbers: +.

The + operator has a different meaning in relation to strings. Instead of trying to do some math, it pastes two strings together. This action can cause strings to be displayed together, or it can make one big string out of two smaller ones.

Concatenation is a word used to describe this action, because it means to link two things together. You'll probably see this term in other books as you build your programming skills, so it's worth knowing. However, pasting is the term used here to describe what happens when one string and another string decide to get together.

Pasting sounds like fun. Concatenating sounds like something that should never be done in the presence of an open flame.

The following statement uses the + operator to display a long string:

System.out.println("\"\'The Piano\' is as peculiar and haunting as any" +

    " film I've seen.\"\n\t-- Roger Ebert, \'Chicago Sun-Times\'");

Instead of putting this entire string on a single line, which would make it harder to understand when you look at the program later, the + operator is used to break up the text over two lines of the program's Java text file. When this statement is displayed, it will appear as the following:

"'The Piano' is as peculiar and haunting as any film I've seen."

    -- Roger Ebert, 'Chicago Sun-Times'

Several special characters are used in the string: \", \', \n, and \t. To better familiarize yourself with these characters, compare the output with the System.out.println() statement that produced it.


Using Other Variables with Strings

Although you can use the + operator to paste two strings together, as demonstrated in the preceding section, you will use it more often to link strings and variables. Take a look at the following:

int length = 121;

char rating = 'R';

System.out.println("Running time: " + length + " minutes");

System.out.println("Rated " + rating);

This code will be displayed as the following:

Running time: 121 minutes

Rated R

This example displays a unique facet about how the + operator works with strings. It can cause variables that are not strings to be treated just like strings when they are displayed. The variable length is an integer set to the value 121. It is displayed between the strings Running time: and minutes. The System.out.println() statement is being asked to display a string plus an integer, plus another string. This statement works because at least one part of the group is a string. The Java language offers this functionality to make displaying information easier.

One thing you might want to do with a string is paste something to it several times, as in the following example:

String searchKeywords = "";

searchKeywords = searchKeywords + "drama ";

searchKeywords = searchKeywords + "romance ";

searchKeywords = searchKeywords + "New Zealand";

This code would result in the searchKeywords variable being set to "drama ro-mance New Zealand." The first line creates the searchKeywords variable and sets it to be an empty string, because there's nothing between the double quotation marks.

The second line sets the searchKeywords variable equal to its current string, plus the string drama added to the end. The next two lines add "romance" and "New Zealand" in the same way.

As you can see, when you are pasting more text at the end of a variable, the name of the variable has to be listed twice. Java offers a shortcut to simplify this process a bit: the += operator. The += operator combines the functions of the = and + operators. With strings, it is used to add something to the end of an existing string. The searchKeywords example can be shortened by using +=, as shown in the following code:

String searchKeywords = "";

searchKeywords += "drama ";

searchKeywords += "romance ";

searchKeywords += "New Zealand";

This code produces the same result: searchKeywords is set to "drama romance New Zealand."


Advanced String Handling

In addition to creating strings, pasting them together, and using them with other types of variables, there are several different ways you can examine a string variable and change its value. These advanced features are possible because strings are objects in the Java language. Working with strings develops skills you'll be using to work with other objects later.

Comparing Two Strings

One thing you will be testing often in your programs is whether one string is equal to another. You do this by using equals() in a statement with both of the strings, as in this example:

String favorite = "piano";

String guess = "ukelele";

System.out.println("Is Ada's favorite instrument a " + guess + "?");

System.out.println("Answer: " + favorite.equals(guess));

This example uses two different string variables. One, favorite, is used to store the name of Ada's favorite instrument: a piano. The other, guess, is used to store a guess as to what her favorite might be. The guess is that Ada prefers the ukulele.

The third line displays the text Is Ada's favorite instrument a followed by the value of the guess variable, and then a question mark. The fourth line displays the text Answer: and then contains something new:

favorite.equals(guess)

This part of the statement is known as a method. A method is a way to accomplish a task in a Java program. This method's task is to determine whether one string, favorite, has the same value as another string, guess. If the two string variables have the same value, the text TRue will be displayed. If not, the text false will be displayed. The following is the output of this example:

Is Ada's favorite instrument a ukulele?

Answer: false

Determining the Length of a String

It can also be useful at times to determine the length of a string in characters. You do this by using the length() method. This method works in the same fashion as the equals() method, except that only one string variable is involved. Look at the following example:

String cinematographer = "Stuart Dryburgh";

int nameLength = cinematographer.length();

This example sets nameLength, an integer variable, equal to 15. The cinematographer.length() method counts the number of characters in the string variable called cinematographer, and this count is assigned to the nameLength integer variable.

Changing a String's Case

Because computers take everything literally, it's easy to confuse them. Although a human would recognize that the text Harvey Keitel and the text HARVEY KEITEL are referring to the same thing, most computers would disagree. For instance, the equals() method discussed previously in this hour would state authoritatively that Harvey Keitel is not equal to HARVEY KEITEL.

To get around some of these obstacles, Java has methods that display a string variable as all uppercase letters (toUpperCase()) or all lowercase letters (toLowerCase()). The following example shows the toUpperCase() method in action:

String baines = "Harvey Keitel";

String change = baines.toUpperCase();

This code sets the string variable change equal to the baines string variable converted to all uppercase letters—HARVEY KEITEL, in other words. The toLowerCase() method works in the same fashion but returns an all-lowercase string value.

Note that the toUpperCase() method does not change the case of the string variable it is called on. In the preceding example, the baines variable will still be equal to Harvey Keitel.

Looking for a String

Another common task when handling strings is to see whether one string can be found inside another. This is useful when you're looking for specific text in a large number of strings (or a very large string).

To look inside a string, use its indexOf() method. Put the string you are looking for inside the parentheses. If the string is not found, indexOf() produces the value -1. If the string is found, indexOf() produces an integer that represents the position where the string begins. Positions in a string are numbered upwards from 0, beginning with the first character in the string. (In the string "The Piano", the text "Piano" begins at position 4.)

One possible use of the indexOf() method would be to search the entire script of The Piano for the place where Ada's domineering husband tells her daughter Flora, "You are greatly shamed and you have shamed those trunks."

If the entire script of The Piano was stored in a string called script, you could search it for part of that quote with the following statement.

int position = script.indexOf("you have shamed those trunks");

If that text can be found in the script string, position will equal the position at which the text "you have shamed those trunks" begins. Otherwise, it will equal -1.

Watch Out!

The indexOf() method is case sensitive, which means that it only looks for text capitalized exactly like the search string. If the string contains the same text capitalized differently, indexOf() produces the value -1.


Workshop: Presenting Credits

In The Piano, Ada McGrath Stewart was thrown into unfamiliar territory when she moved from Scotland to New Zealand to marry a stranger who didn't appreciate her ivory tickling. You might have felt similarly lost with some of the topics introduced during this hour.

As a workshop to reinforce the string-handling features that have been covered, you will write a Java program to display credits for a feature film. You have three guesses as to the movie chosen, and if you need a hint, it starts with a The and ends with a musical instrument that can be used to express the repressed passion of attractive mutes.

Load the word processor you're using to write Java programs and create a new file called Credits.java. Enter the text of Listing 6.1 into the word processor and save the file when you're done.

Listing 6.1. The Credits Program

 1: class Credits {

 2:     public static void main(String[] arguments) {

 3:         // set up film information

 4:         String title = "The Piano";

 5:         int year = 1993;

 6:         String director = "Jane Campion";

 7:         String role1 = "Ada";

 8:         String actor1 = "Holly Hunter";

 9:         String role2 = "Baines";

10:         String actor2 = "Harvey Keitel";

11:         String role3 = "Stewart";

12:         String actor3 = "Sam Neill";

13:         String role4 = "Flora";

14:         String actor4 = "Anna Paquin";

15:         // display information

16:         System.out.println(title + " (" + year + ")\n" +

17:             "A " + director + " film.\n\n" +

18:             role1 + "\t" + actor1 + "\n" +

19:             role2 + "\t" + actor2 + "\n" +

20:             role3 + "\t" + actor3 + "\n" +

21:             role4 + "\t" + actor4);

22:     }

23: }

Before you attempt to compile the program, look over the program and see whether you can figure out what it's doing at each stage. Here's a breakdown of what's taking place:

  • Line 1 gives the Java program the name Credits.

  • Line 2 begins the main() block statement in which all of the program's work gets done.

  • Line 3 is a comment statement explaining that you're going to set up the film's information in subsequent lines.

  • Lines 4–14 set up variables to hold information about the film, its director, and its stars. One of the variables, year, is an integer. The rest are string variables.

  • Line 15 is another comment line for the benefit of humans like us who are examining the program.

  • Lines 16–21 are one long System.out.println() statement. Everything between the first parenthesis on Line 16 and the last parenthesis on Line 21 is displayed onscreen. The newline text (\n) causes the text after it to be displayed at the beginning of a new line. The tab text (\t) inserts tab spacing in the output. The rest are either text or string variables that should be shown.

  • Line 22 ends the main() block statement.

  • Line 23 ends the program.

If you're using the JDK, you can attempt to compile the program by going to the folder that contains Credits.java and typing this command:

javac Credits.java

If you do not see any error messages, the program has compiled successfully, and you can run it with the following command:

java Credits

If you do encounter error messages, correct any typos you find in your version of the Credits program and try again to compile it.

Listing 6.2 shows the output of the Credits application: a rundown of the film, year of release, director, and the four lead performers from The Piano. Be glad that you didn't have to present the credits for an ensemble film. A program detailing Robert Altman's Short Cuts, the 1993 film with more than 25 lead characters, could hog an hour of typing alone.

Listing 6.2. The Output of the Credits Program

The Piano (1993)

A Jane Campion film.

Ada     Holly Hunter

Baines  Harvey Keitel

Stewart Sam Neill

Flora   Anna Paquin


Summary

Once your version of Credits works like the one shown in Listing 6.2, give yourself some credit, too. You're writing longer Java programs and dealing with more sophisticated issues each hour. Like variables, strings are something you'll use every time you sit down to write a program.

At the beginning of The Piano, Holly Hunter's Ada lost her piano when her new husband refused to make his Maori laborers carry it home. Luckily for you, the ability to use strings in your Java programs cannot be taken away by an insensitive newlywed, or anyone else. You'll be using strings in many ways to communicate with users.

By the Way

If this hour's trivia related to The Piano and the films of director Jane Campion has sparked your curiosity, or if you just dig quiet women in braids, visit the following World Wide Web sites:

  • Magnus Hjelstuen's unofficial The Piano website, with cast descriptions, storyline discussion, and comprehensive details about his favorite movie can be found at http://www.fys.uio.no/~magnushj/Piano.

  • The Internet Movie Database, a voluminous and searchable database of movies, TV shows, actors, directors, and other related topics, can be found at http://www.imdb.com.


Q&A

Q1:

How can I set the value of a string variable to be blank?

A1:

A pair of double quotation marks without any text between them is considered to be an empty string. You can set a string variable equal to this upon its creation or in other parts of your programs. The following code creates a new string variable called adaSays and sets it to nothing:

String adaSays = "";

Q2:

Is there a way to make the text in one println() statement start right at the end of the text in the preceding println() statement? I don't want the second println() statement to start at the beginning of a new line, but it always does.

A2:

Java automatically ends each System.out.println() statement with its own new line, so the only way to prevent this is to use a statement that includes all of the text you want to display, or use the System.out.print() statement, which displays a string without ending it with a newline character automatically. The Credits program from the workshop has an example of a println() statement that includes several different lines of output. Take a look at it and see whether it fits what you want to do.

Q3:

I can't seem to get the toUpperCase() method to change a string so that it's all capital letters. What am I doing wrong?

A3:

When you call a String object's toUpperCase() method, it doesn't actually change the String object it is called on. Instead, it creates a new string that is all uppercase letters. Consider the following statements:

String firstName = "Nessie";

String changeName = firstName.toUpperCase();

System.out.println("First Name: " + firstName);

This example will output the text First Name: Nessie because firstName contains the original string. If you switched the last statement to display the changeName variable instead, it would output First Name: NESSIE.

Q4:

If the + operator is used with strings to link up two different strings, can you add the numeric value of one string to the value of another?

A4:

You can use the value of a String variable as an integer only by using a method that converts the string's value into a numeric form. This procedure is called casting, because it recasts existing information, in this case a string, as a different type of information. You'll learn about casting during Hour 11, "Describing What Your Object Is Like."

Q5:

Is it necessary to use += instead of + when adding some text to a string variable?

A5:

Not at all. The += operator is strictly for the benefit of programmers who want to use it as a shortcut. If you're more comfortable using the + operator when pasting some added text to a string variable, you ought to stick with it. The time and convenience you can gain by using += will be lost pretty quickly if it causes you to make errors in your program.

Q6:

Isn't there some kind of == operator that can be used to determine whether two strings have the same value, as in daughter == "Flora"?

A6:

As you will discover during the next hour, "Using Conditional Tests to Make Decisions," the == operator can be used with all the variable types except for strings. The reason for the difference is that strings are objects. Java treats objects differently than other types of information, so special methods are necessary to determine whether one string is equal to another.

Q7:

Do all methods in Java display TRue or false in the same way that the equals() method does in relation to strings?

A7:

Methods have different ways of making a response after they are used. When a method sends back a value, as the equals() method does, it's called returning a value. The equals() method is set to return a Boolean value. Other methods might return a string, an integer, another type of variable, or nothing at all.

Q8:

What are butterfly wings made out of?

A8:

Thin layers of chitin, the same protein that forms the rest of their bodies. A system of veins strengthens the wings, which have to be strong enough to support them in the air.

Chitin also forms the exoskeleton of crabs, lobsters, and other crustaceans.


Quiz

The following questions will test your knowledge of the care and feeding of a string.

Questions

1:

My friend concatenates. Should I report him to the authorities?

  1. No. It's only illegal during the winter months.

  2. Yes, but not until I sell the story to Jerry Springer first.

  3. No. All he's doing is pasting two strings together in a program.

2:

Why is the word String capitalized, while int and others are not?

  1. String is a full word, but int ain't.

  2. Like all objects in Java, String has a capitalized name.

  3. Poor quality control at Sun Microsystems.

3:

Which of the following characters will put a single quote in a string?

  1. <quote>

  2. \'

  3. '

Answers

A1: | c. Concatenation is just another word for pasting, joining, melding, or otherwise connecting two strings together. It uses the + and += operators.
A2: | b. The types of objects available in Java are all capitalized, which is the main reason variable names have a lowercase first letter. It makes it harder to mistake them for objects.
A3: | b. The single backslash is what begins one of the special characters that can be inserted into strings.


Activities

You can review the topics of this hour more fully with the following activities:

  • Write a short Java program called Favorite that puts the code from this hour's "Comparing Two Strings" section into the main() block statement. Test it out to make sure it works as described and says that Ada's favorite instrument is not the ukulele. When you're done, change the initial value of the guess variable from ukulele to piano. See what happens.

  • Modify the Credits program so that the names of the director and all performers are displayed entirely in uppercase letters.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


Hour 7. Using Conditional Tests to Make Decisions

Writing a computer program has been compared to telling a household robot what to do. You provide the computer a list of instructions, called statements, and these instructions are followed to the letter. You can tell the computer to work out some unpleasant mathematical formulas, and it will work them out for you. Tell it to display some information, and it will dutifully respond.

However, there are times when you need the computer to be more selective about what it does. For example, if you have written a program to balance your checkbook, you might want the computer to display a warning message if your account is overdrawn. The warning could be something along the lines of "Hear that bouncing noise? It's your checks." The computer should display this message only if your account is overdrawn. If it isn't, the message would be both inaccurate and emotionally upsetting.

The way to accomplish this task in a Java program is to use a statement called a conditional. Conditionals cause something to happen in a program only if a specific condition is met. During this hour, you'll learn how to use three different types of conditional statements: if, else, and switch. The following topics will be covered:

  • Testing to see whether conditions are met

  • Using the if statement for basic conditional tests

  • Using other statements in conjunction with if

  • Testing whether one value is greater than or less than another

  • Testing whether two values are equal or unequal

  • Using else statements as the opposite of if statements

  • Chaining several conditional tests together

  • Using the switch statement for complicated conditional tests

  • Creating complicated tests with the ternary operator


Testing a Condition

Whenever a Java program makes a decision, it does so by employing a conditional statement. During this hour, you'll be checking the condition of several things in your Java programs using the conditional statements if, else, switch, case, and break. You also will be using several conditional operators: ==, !=, <, >, and ?, along with boolean variables.


if Statements

If you want to test a condition in a Java program, the most basic way is with an if statement. As you learned previously, the boolean variable type is used to store only two possible values: true or false. The if statement works along the same lines, testing to see whether a condition is true or false, and taking action only if the condition is true.

You use if along with a condition to test, as in the following statement:

if (account < 0)

    System.out.println("Hear that bouncing noise? It's your checks");

Although this code is listed on two lines, it's one statement. The first part uses if to determine whether the account variable is less than 0 by using the < operator. The second part displays the text Hear that bouncing noise? It's your checks.

The second part of an if statement will be run only if the first part is true. In the preceding example, if the account variable has a value of 0 or higher, the println statement will be ignored. Note that the condition you test with an if statement must be surrounded by parentheses, as in (account < 0).

By the Way

If you're not sure why if (account < 0) is not a statement, note that there is no semicolon at the end of the line. In Java programs, semicolons are used to show where one statement ends and the next one begins. In the preceding example, the semicolon does not appear until after the println portion of the statement. If you put a semicolon after the if portion, as in if (account < 0.01), you'll cause a logic error in your program that can be hard to spot. Take care regarding semicolons when you start using the if statement.

The less-than operator, <, is one of several different operators you can use with conditional statements. You'll become more familiar with the if statement as you use it with some of the other operators.

Less Than and Greater Than Comparisons

In the preceding section, the < operator is used the same way it was used in math class: as a less-than sign. There is also a greater-than conditional operator: >. This operator is used in the following statements:

if (elephantWeight > 780)

    System.out.println("Elephant too fat for tightrope act.");

if (elephantTotal > 12)

    cleaningExpense = cleaningExpense + 150;

The first if statement tests whether the value of the elephantWeight variable is greater than 780. The second if statement tests whether the elephantTotal variable is greater than 12.

One thing to understand about if statements is that they often cause nothing to happen in your programs. If the two preceding statements are used in a program where elephantWeight is equal to 600 and elephantTotal is equal to 10, the rest of the if statements will be ignored.

There will be times when you want to determine whether something is less than or equal to something else. You can do this with the <= operator, as you might expect; use the >= operator for greater-than-or-equal-to tests. Here's an example:

if (account <= 0)

    System.out.println("Hear that bouncing noise? It's your checks");

This revision of the checkbook example tests whether account is less than or equal to the value 0, and taunts the user if it is.

Equal and Not Equal Comparisons

Another condition to check in a program is equality. Is a variable equal to a specific value? Is one variable equal to the value of another? These questions can be answered with the == operator, as in the following statements:

if (answer == rightAnswer)

    studentGrade = studentGrade + 10;

if (studentGrade == 100)

    System.out.println("Such a show off!");

Watch Out!

The operator used to conduct equality tests has two equal signs: ==. It's very easy to confuse this operator with the = operator, which is used to give a value to a variable. Always use two equal signs in a conditional statement.

You can also test inequality—whether something is not equal to something else. This is accomplished with the != operator, as shown in the following example:

if (answer != rightAnswer)

    score = score - 5;

You can use the == and != operators reliably with every type of variable except one: strings. To see whether one string has the value of another, use the equals() method described during Hour 6, "Using Strings to Communicate."

Organizing a Program with Block Statements

Up to this point, all of the if statements have been followed with a single instruction, such as the println() method. In many cases, you will want to perform more than one action in response to an if statement. To do this, you'll use the { and } characters to create a block statement. I believe the technical term for these characters is "squiggly bracket marks."

Block statements are statements that are organized into a group. Previously, you have seen how block statements are used to mark the beginning and end of the main() block of a Java program. Each statement within the main() block is handled when the program is run. Listing 7.1 is an example of a Java program with a block statement used to denote the main() block. The block statement begins with the opening bracket { on Line 2 and ends with the closing bracket } on Line 11. Load your word processor and enter the text of Listing 7.1 as a new file.

Listing 7.1. The Game Program

 1: class Game {

 2:     public static void main(String[] arguments) {

 3:         int total = 0;

 4:         int score = 7;

 5:         if (score == 7) {

 6:             System.out.println("You score a touchdown!");

 7:         }

 8:         if (score == 3) {

 9:             System.out.println("You kick a field goal!");

10:         }

11:         total = total + score;

12:         System.out.println("Total score: " + total);

13:     }

Save this file as Game.java and compile it. If you're using the JDK, you can compile it by typing the following command:

javac Game.java

When you run the program, the output should resemble Listing 7.2.

Listing 7.2. The Output of the Game Program

You score a touchdown!

Total score: 7

You also can use block statements in conjunction with if statements to make the computer do more than one thing if a conditional statement is true. The following is an example of an if statement that includes a block statement:

if (playerScore > 9999) {

    playerLives++;

    System.out.println("Extra life!");

    difficultyLevel = difficultyLevel + 5;

}

The brackets are used to group all statements that are part of the if statement. If the variable playerScore is greater than 9,999, three things will happen:

  • The value of the playerLives variable increases by one (because the increment operator ++ is used).

  • The text ExTRa life! is displayed.

  • The value of the difficultyLevel variable is increased by 5.

If the variable playerScore is not greater than 9,999, nothing will happen. All three statements inside the if statement block will be ignored.


if-else Statements

There are times when you want to do something if a condition is true and do something else if the condition is false. You can do this by using the else statement in addition to the if statement, as in the following example:

if (answer == correctAnswer) {

    score += 10;

    System.out.println("That's right. You get 10 points.");

}

else {

    score -= 5;

    System.out.println("Sorry, that's wrong. You lose 5 points.");

}

The else statement does not have a condition listed alongside it, unlike the if statement. Generally, the else statement is matched with the if statement that immediately comes before it in a Java program. You also can use else to chain several if statements together, as in the following example:

if (grade == 'A')

    System.out.println("You got an A. Great job!");

else if (grade == 'B')

    System.out.println("You got a B. Good work!");

else if (grade == 'C')

    System.out.println("You got a C. You'll never get into a good "

        + "college!");

else

    System.out.println("You got an F. You'll do well in Congress!");

By putting together several different if and else statements in this way, you can handle a variety of conditions. In the preceding example, a specific message is sent to A students, B students, C students, and future legislators.


switch Statements

The if and else statements are good for situations with only two possible conditions, but there are times when you have more than two options that need to be considered. With the preceding grade example, you saw that if and else statements can be chained to handle several different conditions.

Another way to do this is to use the switch statement. You can use it in a Java program to test for a variety of different conditions and respond accordingly. In the following example, the grade example has been rewritten with the switch statement to handle a complicated range of choices:

switch (grade) {

    case 'A':

        System.out.println("You got an A. Great job!");

        break;

    case 'B':

        System.out.println("You got a B. Good work!");

        break;

    case 'C':

        System.out.println("You got a C. You'll never get into a good "

            + "college!");

        break;

    default:

        System.out.println("You got an F. You'll do well in Congress!");

}

The first line of the switch statement specifies the variable that will be tested—in this example, grade. Then the switch statement uses the { and } brackets to form a block statement.

Each of the case statements checks the test variable in the switch statement against a specific value. The value used in a case statement must be either a character or an integer. In this example, there are case statements for the characters 'A', 'B', and 'C'. Each of these has one or two statements that follow it. When one of these case statements matches the variable listed with switch, the computer handles the statements after the case statement until it encounters a break statement.

For example, if the grade variable has the value of B, the text You got a B. Good work! will be displayed. The next statement is break, so no other part of the switch statement will be considered. The break statement tells the computer to break out of the switch statement.

The default statement is used as a catch-all if none of the preceding case statements is true. In this example, it will occur if the grade variable does not equal 'A', 'B', or 'C'. You do not have to use a default statement with every switch block statement you use in your programs. If it is omitted, nothing will happen if none of the case statements has the correct value.

Watch Out!

One thing you might want to do with switch is to make each case statement represent a range of values. As an example, in a grading program, you might want to use an integer called numberGrade and test for case numberGrade > 89:. Unfortunately, this isn't possible in Java because each case statement must refer to a single value. You'll have to use a series of if statements or if-else statements when you aren't working with a bunch of different one-value conditions.


The Conditional Operator

The most complicated conditional statement is one that you might not find reasons to use in your programs: the ternary operator. If you find it too confusing to implement in your own programs, take heart: You can use other conditionals to accomplish the same thing.

You can use the ternary operator when you want to assign a value or display a value based on a conditional test. For example, in a video game, you might need to set the numberOfEnemies variable based on whether the skillLevel variable is greater than 5. One way to do this is with an if-else statement:

if (skillLevel > 5)

    numberOfEnemies = 10;

else

    numberOfEnemies = 5;

A shorter way to do this is to use the ternary operator, which is ?. A ternary operator has five parts:

  • The condition to test, surrounded by parentheses, as in (skillLevel > 5)

  • A question mark (?)

  • The value to use if the condition is true

  • A colon (:)

  • The value to use if the condition is false

To use the ternary operator to set the value of numberOfEnemies based on skillLevel, you could use the following statement:

numberOfEnemies = (skillLevel > 5) ? 10 : 5;

You also can use the ternary operator to determine what information to display. Consider the example of a program that displays the text Mr. or Ms. depending on the value of the gender variable. You could do this action with another if-else statement:

if (gender.equals("male"))

    System.out.print("Mr.");

else

    System.out.print("Ms.");

A shorter method is to use the ternary operator to accomplish the same thing, as in the following:

System.out.print( (gender.equals("male")) ? "Mr." : "Ms." );

The ternary operator can be useful, but it's also the hardest conditional in Java to understand. As you learn Java, you won't encounter any situations where the ternary operator must be used instead of if and else statements.


Workshop: Watching the Clock

This hour's workshop gives you another look at each of the conditional tests you can use in your programs. For this project, you will use Java's built-in timekeeping feature, which keeps track of the current date and time, and present this information in sentence form.

Run the word processor you're using to create Java programs and give a new document the name ClockTalk.java. This program is long, but most of it consists of long conditional statements. Type the full text of Listing 7.3 into the word processor and save the file as ClockTalk.java when you're done.

Listing 7.3. The ClockTalk Program

 1: import java.util.*;

 2:

 3: class ClockTalk {

 4:     public static void main(String[] arguments) {

 5:         // get current time and date

 6:         Calendar now = Calendar.getInstance();

 7:         int hour = now.get(Calendar.HOUR_OF_DAY);

 8:         int minute = now.get(Calendar.MINUTE);

 9:         int month = now.get(Calendar.MONTH) + 1;

10:         int day = now.get(Calendar.DAY_OF_MONTH);

11:         int year = now.get(Calendar.YEAR);

12:

13:         // display greeting

14:         if (hour < 12) {

15:             System.out.println("Good morning.\n");

16:         } else if (hour < 17) {

17:             System.out.println("Good afternoon.\n");

18:         } else {

19:             System.out.println("Good evening.\n");

20:         }

21:

22:         // begin time message by showing the minutes

23:         System.out.print("It's");

24:         if (minute != 0) {

25:             System.out.print(" " + minute + " ");

26:             System.out.print( (minute != 1) ? "minutes" :

27:                 "minute");

28:             System.out.print(" past");

29:         }

30:

31:         // display the hour

32:         System.out.print(" ");

33:         System.out.print( (hour > 12) ? (hour - 12) : hour );

34:         System.out.print(" o'clock on ");

35:

36:         // display the name of the month

37:         switch (month) {

38:             case 1:

39:                 System.out.print("January");

40:                 break;

41:             case 2:

42:                 System.out.print("February");

43:                 break;

44:             case 3:

45:                 System.out.print("March");

46:                 break;

47:             case 4:

48:                 System.out.print("April");

49:                 break;

50:             case 5:

51:                 System.out.print("May");

52:                 break;

53:             case 6:

54:                 System.out.print("June");

55:                 break;

56:             case 7:

57:                 System.out.print("July");

58:                 break;

59:             case 8:

60:                 System.out.print("August");

61:                 break;

62:             case 9:

63:                 System.out.print("September");

64:                 break;

65:             case 10:

66:                 System.out.print("October");

67:                 break;

68:             case 11:

69:                 System.out.print("November");

70:                 break;

71:             case 12:

72:                 System.out.print("December");

73:         }

74:

75:         // display the date and year

76:         System.out.println(" " + day + ", " + year + ".");

77:     }

78: }

Save the file when you're done, and attempt to compile it (JDK users can enter javac ClockTalk.java at the command line). Correct any typos that cause error messages to occur during the attempted compilation. After the program compiles correctly, look it over before reading more about the program. See whether you can get a good idea about what is taking place in each of its sections and how the conditional tests are being used.

With the exception of Lines 6–11, the ClockTalk program contains material that has been covered up to this point. After a series of variables are set up to hold the current date and time, a series of if or switch conditionals are used to determine what information should be displayed.

This program contains several uses of System.out.println() and System.out.print() to display strings.

Lines 6–11 refer to a Calendar variable called now. The Calendar variable type is capitalized, just as String is capitalized in a program that uses strings. The reason for the capitalization is that Calendar is an object.

You'll learn how to create and work with objects during Hour 10, "Creating Your First Object." For this hour, focus on what's taking place in those lines rather than how it's happening.

The ClockTalk program is made up of the following sections:

  • Line 1 enables your program to use a class that is needed to track the current date and time: java.util.Calendar.

  • Lines 3–4 begin the ClockTalk program and its main() statement block.

  • Line 6 creates a Calendar object called now that contains the current date and time of your system. The now object will change each time you run this program (unless, of course, the physical laws of the universe are altered and time stands still).

  • Lines 7–11 create variables to hold the hour, minute, month, day, and year. The values for these variables are pulled from the Calendar object, which is the storehouse for all of this information. These variables are used in the subsequent sections as the program displays information.

  • Lines 14–20 display one of three possible greetings: Good morning., Good afternoon., or Good evening. The greeting to display is selected based on the value of the hour variable.

  • Lines 23–29 display the current minute along with some accompanying text. First, the text It's is displayed in Line 23. If the value of minute is equal to 0, Lines 25–28 are ignored because of the if statement in Line 24. This statement is necessary because it would not make sense for the program to tell someone that it's 0 minutes past an hour. Line 25 displays the current value of the minute variable. A ternary operator is used in Lines 26–27 to display either the text minutes or minute, depending on whether minute is equal to 1. Finally, in Line 28 the text past is displayed.

  • Lines 32–34 display the current hour by using another ternary operator. This ternary conditional statement in Line 33 causes the hour to be displayed differently if it is larger than 12, which prevents the computer from stating times like "15 o'clock."

  • Lines 37–73, almost half of the program, are a long switch statement that displays a different name of the month based on the integer value stored in the month variable.

  • Line 76 finishes off the display by showing the current date and the year.

  • Lines 77–78 close out the main() statement block and then the entire ClockTalk program.

When you run this program, the output should resemble the following code, with changes based on the current date and time. For example, if the program was run on 6/26/2005 at 11:33 p.m., it would display the following text:

Good evening.

It's 33 minutes past 11 o'clock on June 26, 2005.

Run the program several times to see how it keeps up with the clock. If the time doesn't match the time on your computer, the Java interpreter might be using the wrong time zone to determine the current time. When the interpreter does not know the default time zone to use, it uses Greenwich Time instead.

The following statements set the current time zone to U.S. Eastern time:

TimeZone tz = TimeZone.getTimeZone("EST");

TimeZone.setDefault(tz);

The setDefault() method should be used before calendar or any other date-related items are created.

The first statement creates a TimeZone object called tz. The text EST is sent as an argument to the getTimeZone() method, and this causes TimeZone to be set up for Eastern Time.

The second statement sets the time zone by calling the setDefault () method of the TimeZone class. If you're having trouble finding the right time zone arguments, the following statements display all valid zones recognized by Java on your system:

String[] ids = TimeZone.getAvailableIDs();

for (int i = 0; i < ids.length; i++)

    System.out.println(ids[i].toString());

By the Way

The ClockTalk program uses the Gregorian calendar system that has been used throughout the Western world for many years to determine the date and time. It was introduced in 1582 when Pope Gregory XIII moved the Julian calendar system forward 10 days—turning Oct. 5, 1582, into Oct. 15, 1582. This was needed because the calendar was moving out of alignment with the seasons due to discrepancies in the Julian system (which had to be small comfort to anyone who had a birthday on October 6 through October 14). Java also supports the use of alternate calendar systems—if you're looking for a class that supports the Arabic, Buddhist, Japanese, or Hebrew calendar systems, visit the International Components for Unicode for Java site at the web address http://www-306.ibm.com/software/globalization/icu.


Summary

Now that you can use conditional statements, the overall intelligence of your Java programs has improved greatly. Your programs can now evaluate information and use it to react differently in different situations, even if information changes as the program is running. They can decide between two or more alternatives based on specific conditions.

Programming a computer forces you to break a task down into a logical set of steps to undertake and decisions that must be made. Using the if statement and other conditionals in programming also promotes a type of logical thinking that can reap benefits in other aspects of your life:

  • "If he is elected president in November, I will seek a Cabinet position, else I will move to Canada."

  • "If my blind date is attractive, I'll pay for dinner at an expensive restaurant, else we will go to Pizza Hut."

  • "If I violate my probation, the only team that will draft me is the Dallas Cowboys."


Q&A

Q1: | The if statement seems like the one that's most useful. Is it possible to use only if statements in programs and never use the others?
A1: | It's possible to do without else or switch, and many programmers never use the ternary operator ?. However, else and switch often are beneficial to use in your programs because they make them easier to understand. A set of if statements chained together can become unwieldy.
Q2: | An if statement is described as either a single statement or as a conditional statement followed by another statement to handle if the condition is true. Which is it?
A2: | The point that might be confusing is that if statements and other conditionals are used in conjunction with other statements. The if statement makes a decision, and the other statements do work based on the decision that is made. The if statement combines a conditional statement with one or more other types of Java statements, such as statements that use the println() method or create a variable.
Q3: | In the ClockTalk program, why is 1 added to Calendar.MONTH to get the current month value?
A3: | This is necessary because of a quirk in the way that the Calendar class represents months. Instead of numbering them from 1 to 12 as you might expect, Calendar numbers months beginning with 0 in January and ending with 11 in December. Adding 1 causes months to be represented numerically in a more understandable manner.
Q4: | During this hour, opening and closing brackets { and } are not used with an if statement if it is used in conjunction with only one statement. Isn't it mandatory to use brackets?
A4: | No. Brackets can be used as part of any if statement to surround the part of the program that's dependent on the conditional test. Using brackets is a good practice to get into because it prevents a common error that might take place when you revise the program. If you add a second statement after an if conditional and don't add brackets, unexpected errors will occur when the program is run.
Q5: | Will the JDK's Java compiler catch the error when an = operator is used with a conditional instead of a ==?
A5: | Often it will not, and it results in a real doozy of a logic error. These errors only show up when a program is being run and can be discovered only through observation and testing. Because the = operator is used to assign a value to a variable, if you use name = "Fernando" in a spot in a program where you mean to use name == "Fernando", you could wipe out the value of the name variable and replace it with Fernando. When the value stored in a variable changes unexpectedly, it can cause subtle and unexpected errors.
Q6: | Does break have to be used in each section of statements that follow a case?
A6: | You don't have to use break. If you do not use it at the end of a group of statements, all of the remaining statements inside the switch block statement will be handled, regardless of the case value they are being tested with.
Q7: | Why do you sometimes use single-quotation marks after a case statement and sometimes leave them off?
A7: | The value associated with a case statement must be either a character or an integer. The single-quotation marks surround a char value and are not used with an int value, so they differentiate between these two data types—for example, case '1': looks for the '1' character and case 1: looks for the integer value of 1.
Q8: | Why do they call them "buffalo wings" when they are made out of chicken?
A8: | The spicy chicken dish was invented by a bar owner in Buffalo, N.Y. Teressa Bellissimo served the wings in 1964, as a late-night snack for her son and his friends, including blue cheese dressing and celery because they were on hand. The family-owned Anchor Bar continues to serve 1,000 pounds of wings a day.


Quiz

The following questions will see what condition you're in after studying conditional statements in Java.

Questions

1:

Conditional tests result in either a true or false value. Which variable type does this remind you of?

  1. None. Stop pestering me with all of these questions.

  2. The long variable type.

  3. The boolean type.

2:

Which statement is used as a catch-all category in a switch block statement?

  1. default

  2. otherwise

  3. onTheOtherHand

3:

What's a conditional?

  1. The thing that repairs messy split ends and tangles after you shampoo.

  2. Something in a program that tests whether a condition is true or false.

  3. The place where you confess your sins to a neighborhood religious figure.

Answers

A1: | c. The boolean variable type can only equal TRue or false, making it similar to conditional tests. If you answered a., I'm sorry, but there's only 17 hours left and we've got a lot left to cover. Java doesn't teach itself.
A2: | a. default statements will be handled if none of the other case statements matches the switch variable.
A3: | b. The other answers describe conditioner and a confessional.


Activities

To improve your conditioning in terms of Java conditionals, review the topics of this hour with the following activities:

  • Remove the break statement from one of the lines in the ClockTalk program, and then compile it and see what happens when you run it. Try it again with a few more break statements removed.

  • Create a short program that stores a value of your choosing from 1 to 100 in an integer variable called grade. Use this grade variable with a conditional statement to display a different message for all A, B, C, D, and F students. Try it first with an if statement, and then try it with a switch statement.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


Hour 8. Repeating an Action with Loops

One of the more annoying punishments for schoolchildren is to make them write something over and over again on paper or a chalkboard.

On The Simpsons, in one of his frequent trips to the board, Bart Simpson had to write, "I will not obey the voices in my head" dozens of times. This kind of punishment might work on children, but it definitely would fail to be punitive to a computer, which can repeat a task with ease.

Computer programs are ideally suited to do the same thing over and over again because of loops. A loop is a statement or set of statements that will be repeated in a program. Some loops take place a fixed number of times. Others take place indefinitely.

There are three loop statements in Java: for, do, and while. These statements are often interchangeable in a program because each can be made to work like the others. The choice to use a loop statement in a program often depends on personal preference, but it's beneficial to learn how all three work. You frequently can simplify a loop section of a program by choosing the right statement.

The following topics will be covered during this hour:

  • Using the for loop

  • Using the while loop

  • Using the do-while loop

  • Exiting a loop prematurely

  • Naming a loop


for Loops

In the Java programs that you write, you will find many circumstances in which a loop is useful. You can use them to keep doing something several times, such as an antivirus program that opens each new email you receive to look for any viruses. You also can use them to cause the computer to do nothing for a brief period, such as an animated clock that displays the current time once per minute.

To create and control loops, you use a loop statement. A loop statement causes a computer program to return to the same place more than once. If the term seems unusual to you, think of what a stunt plane does when it loops: It completes a circle and returns to the place where it started the loop.

The most complex of the loop statements is for. The for loop is often used in cases where you want to repeat a section of a program for a fixed number of times. It also can be used if the number of times the loop should be repeated is based on the value of a variable. The following is an example of a for loop:

for (int dex = 0; dex < 1000; dex++) {

    if (dex % 12 == 0) {

        System.out.println("#: " + dex);

    }

}

This loop displays every number from 0 to 999 that is evenly divisible by 12.

Every for loop has a variable that is used to determine when the loop should begin and end. This variable often is called the counter. The counter in the preceding loop is a variable called dex.

The example illustrates the three parts of a for statement:

  • The initialization section: In the first part, the dex variable is given an initial value of 0.

  • The conditional section: In the second part, there is a conditional test like one you might use in an if statement. The test is dex < 1000.

  • The change section: The third part is a statement that changes the value of the dex variable by using the increment operator.

In the initialization section, you can set up the counter variable you want to use in the for statement. You even can create the variable inside the for statement, as the preceding example does with the integer variable named dex. You also can create the variable elsewhere in the program. In any case, the variable should be given a starting value in this section of the for statement. The variable will have this value when the loop starts.

The conditional section contains a test that must remain TRue for the loop to continue looping. Once the test is false, the loop will end. In this example, the loop will end when the dex variable is equal to or greater than 1,000.

The last section of the for statement contains a Java statement that changes the value of the counter variable in some way. This statement is handled each time the loop goes around. The counter variable has to change in some way or the loop will never end. For instance, in this example, dex is incremented by one using the increment operator ++ in the change section. If dex was not changed, it would stay at its original value, 0, and the conditional dex < 1000 would always be true.

The statements inside the bracket marks, { and }, also are executed during each trip through the loop. The bracketed area is usually where the main work of the loop takes place, although some loops do all their work in the change section.

The preceding example had the following statements within the { and } marks:

if (dex % 12 == 0) {

    System.out.println("#: " + dex);

}

These statements will be executed 1,000 times. The loop starts by setting the dex variable equal to 0. It then adds 1 to dex during each pass through the loop and stops looping when dex is no longer less than 1,000. Every time dex is evenly divisible by 12, the number is displayed next to the text #:.

By the way

An unusual term you might hear in connection with loops is iteration. An iteration is a single trip through a loop. The counter variable that is used to control the loop often is called an iterator.

As you have seen with if statements, a for loop does not require brackets if it contains only a single statement. This is shown in the following example:

for (int p = 0; p < 500; p++)

    System.out.println("I will not speculate on how hot teacher used to be");

This loop will display the text "I will not speculate on how hot teacher used to be" 500 times. Although brackets are not required around a single statement inside a loop, you can use them if desired as a way of making the program easier to understand.

The first program you create during this hour will display the first 200 multiples of 9—9 x 1, 9 x 2, 9 x 3, and so on, up to 9 x 200. Because this task is so repetitious, it should be handled with a loop statement such as for.

Open your word processor and create a new file. Enter the text of Listing 8.1 and save the file as Nines.java when you're done.

Listing 8.1. The Full Text of Nines.java

1: class Nines {

2:     public static void main(String[] arguments) {

3:         for (int dex = 1; dex <= 200; dex++) {

4:             int multiple = 9 * dex;

5:             System.out.print(multiple + " ");

6:         }

7:     }

8: }

The Nines program contains a for statement in line 3. This statement has three parts:

  • The initialization section: int dex = 1, which creates an integer variable called dex and gives it an initial value of 1.

  • The conditional section: dex <= 200, which must be true during each trip through the loop. When it is not true, the loop ends.

  • The change section: dex++, which increments the dex variable by one during each trip through the loop.

Compile and run the program. If you are using the JDK, you can handle these tasks by using the following commands:

javac Nines.java

java Nines

This program produces the following output:

9 18 27 36 45 54 63 72 81 90 99 108 117 126 135 144 153 162 171

180 189 198 207 216 225 234 243 252 261 270 279 288 297 306 315

324 333 342 351 360 369 378 387 396 405 414 423 432 441 450 459

468 477 486 495 504 513 522 531 540 549 558 567 576 585 594 603

612 621 630 639 648 657 666 675 684 693 702 711 720 729 738 747

756 765 774 783 792 801 810 819 828 837 846 855 864 873 882 891

900 909 918 927 936 945 954 963 972 981 990 999 1008 1017 1026

1035 1044 1053 1062 1071 1080 1089 1098 1107 1116 1125 1134 1143

1152 1161 1170 1179 1188 1197 1206 1215 1224 1233 1242 1251 1260

1269 1278 1287 1296 1305 1314 1323 1332 1341 1350 1359 1368 1377

1386 1395 1404 1413 1422 1431 1440 1449 1458 1467 1476 1485 1494

1503 1512 1521 1530 1539 1548 1557 1566 1575 1584 1593 1602 1611

1620 1629 1638 1647 1656 1665 1674 1683 1692 1701 1710 1719 1728

1737 1746 1755 1764 1773 1782 1791 1800

The for loop statement is extremely useful. You'll get a lot of practice using it in upcoming hours, because several of the tutorial programs and workshops make use of these loops.

Watch Out!

Because many Java statements end with a semicolon, an easy mistake to make is putting a semicolon at the end of a for statement, as in the following:

for (int i = 0; i < 100; i++) {

    value = value + i;

}

Look closely at the closing parenthesis in the first line of this example. It is followed by a semicolon, which will prevent the loop from running correctly. The semicolon puts the statements in the brackets, value = value + i, outside the loop. As a result, nothing will happen as the for loop is handled. The program might compile without any errors, but you won't get the results you expect when it runs.


while Loops

The while loop does not have as many different sections to set up as the for loop. The only thing it needs is a conditional test, which accompanies the while statement. The following is an example of a while loop:

while (gameLives > 0) {

    // the statements inside the loop go here

}

This loop will continue repeating until the gameLives variable is no longer greater than 0.

The while statement tests the condition at the beginning of the loop, before any statements of the loop have been handled. For this reason, if the tested condition is false when a program reaches the while statement for the first time, the statements inside the loop will be ignored.

If the while condition is true, the loop goes around once and tests the while condition again. If the tested condition never changes inside the loop, the loop will keep looping indefinitely.

The following statements cause a while loop to display the same line of text several times:

int limit = 5;

int count = 1;

while (count < limit) {

    System.out.println("Pork is not a verb");

    count++;

}

A while loop uses one or more variables that are set up before the loop statement. In this example, two integer variables are created: limit, which has a value of 5, and count, which has a value of 1.

The while loop displays the text Pork is not a verb four times. If you gave the count variable an initial value of 6 instead of 1, the text would never be displayed.


do-while Loops

The do-while loop is similar in function to the while loop, but the conditional test goes in a different place. The following is an example of a do-while loop:

do {

    // the statements inside the loop go here

} while ( gameLives > 0 );

Like the previous while loop, this loop will continue looping until the gameLives variable is no longer greater than 0. The do-while loop is different because the conditional test is conducted after the statements inside the loop, instead of before them.

When the do loop is reached for the first time as a program runs, the statements between the do and the while are handled automatically. Then the while condition is tested to determine whether the loop should be repeated. If the while condition is TRue, the loop goes around one more time. If the condition is false, the loop ends. Something must happen inside the do and while statements that changes the condition tested with while, or the loop will continue indefinitely. The statements inside a do-while loop will always be handled at least once.

The following statements cause a do-while loop to display the same line of text several times:

int limit = 5;

int count = 1;

do {

    System.out.println("The nurse is not dealing");

    count++;

} while (count < limit);

Like a while loop, a do-while loop uses one or more variables that are set up before the loop statement.

The loop displays the text The nurse is not dealing four times. If you gave the count variable an initial value of 6 instead of 1, the text would be displayed once, even though count is never less than limit.

If you're still confused about the difference between a while loop and a do-while loop, engage in a little role-playing and pretend you're a teenager who wants to borrow your father's car. If you are a teenager, all the better. There are two strategies that you can take:

  1. Borrow the car first and tell Dad later that you did it.

  2. Ask Dad before you borrow the car.

Strategy 1 has an advantage over Strategy 2: Even if Dad doesn't want to let you use the car, you get to borrow it once.

The do-while loop is like Strategy 1 because something happens once even if the loop condition is false the first time while is encountered.

The while loop is like Strategy 2 because nothing will happen unless the while condition at the beginning is TRue. It all depends on the situation in your program.

Watch Out!

Sams Publishing makes no warranties express nor implied that your father will be happy if you borrow his car without telling him first.


Exiting a Loop

The normal way to exit a loop is for the condition that is tested to become false. This is true of all three types of loops in Java: for, while, and do-while. However, there might be times when you want a loop to end immediately, even if the condition being tested is still true. You can do this with a break statement, as shown in the following code:

int index = 0;

while (index <= 1000) {

    index = index + 5;

    if (index == 400)

        break;

    System.out.println("The index is " + index);

}

The condition tested in the while loop sets it up to loop until the value of the index variable is greater than 1,000. However, a special case causes the loop to end earlier than that: If index equals 400, the break statement is executed, ending the loop immediately.

Another special-circumstance statement you can use inside a loop is continue. The continue statement causes the loop to exit its current trip through the loop and start over at the first statement of the loop. Consider the following loop:

int index = 0;

while (index <= 1000) {

    index = index + 5;

    if (index == 400)

        continue;

    System.out.println("The index is " + index);

}

In this loop, the statements will be handled normally unless the value of index equals 400. In that case, the continue statement causes the loop to go back to the while statement instead of proceeding normally to the System.out.println() statement. Because of the continue statement, the loop will never display the following text:

The index is 400

You can use the break and continue statements with all three kinds of Java loop statements.


Naming a Loop

Like other statements in Java programs, loops can be put inside of each other. The following shows a for loop inside a while loop:

int points = 0;

int target = 100;

while (target <= 100) {

    for (int i = 0; i < target; i++) {

        if (points > 50)

            break;

        points = points + i;

    }

}

In this example, the break statement will cause the for loop to end if the points variable is greater than 50. However, the while loop will never end, because target is never greater than 100.

In this case (and others), you might want to break out of both loops. To make this possible, you have to give the outer loop—in this example, the while statement—a name. To name a loop, put the name on the line before the beginning of the loop and follow it with a colon (:).

Once the loop has a name, you can use the name after the break or continue statement to indicate to which loop the break or continue statement applies. Although the name of the loop is followed by a colon at the spot where the loop begins, the colon is not used with the name in a break or continue statement.

The following example repeats the previous one with the exception of one thing: If the points variable is greater than 50, both loops are ended.

int points = 0;

int target = 100;

targetloop:

while (target <= 100) {

    for (int i = 0; i < target; i++) {

        if (points > 50)

            break targetloop;

        points = points + i;

    }

}

Complex for Loops

Most for loops are directly comparable to the ones used up to this point in the hour. They can also be a little more complex if you want to work with more than one variable in the for statement.

Each section of a for loop is set off from the other sections with a semicolon (;). A for loop can have more than one variable set up during the initialization section, and more than one statement in the change section, as in the following:

int i, j;

for (i = 0, j = 0; i * j < 1000; i++, j += 2) {

    System.out.println(i + " * " + j + " = " + i * j);

}

These multiple statement sections of the for loop are set off by commas, as in i = 0, j = 0. This loop will display a list of equations where the i variable is multiplied by the j variable. The i variable increases by one, and the j variable increases by two during each trip through the loop. Once i multiplied by j is no longer less than 1,000, the loop will end.

Sections of a for loop can also be empty. An example of this would be if the counter variable has already been created with an initial value in another part of the program, as in the following:

for ( ; displayCount < endValue; displayCount++) {

    // loop statements would be here

}


Workshop: Teaching Your Computer a Lesson

This hour's workshop provides evidence that you cannot punish your computer in the same way that Bart Simpson is punished at the beginning of each episode of The Simpsons. Pretend you're a teacher and the computer is a kid who contaminated your morning cup of coffee with Thorium 230.

Even if you're the most strident liberal, you realize that the computer must be taught a lesson—it's not acceptable behavior to give the teacher radiation poisoning. Your computer must be punished, and the punishment is to display the same sentence over and over again.

The Repeat program will use a loop statement to handle a System.out.println() statement again and again. Once the computer has been dealt this punishment for 1,000,000 sentences or one minute, whichever comes first, it can stop running and think about the error of its ways.

By the way

A topic of heated debate here at Sams concerns whether the punishment is severe enough. Thorium is a silver-white metal that has a half-life of 80,000 years. Some scientists believe that it is as toxic as plutonium, and if it finds a home in someone's liver, bone marrow, or lymphatic tissue, Thorium 230 can cause serious problems. A student who irradiates a teacher probably should receive three hours of in-school detention, at least.

Use your word processor to create a new file called Repeat.java. Enter the text of Listing 8.2 and save the file when you're done.

Listing 8.2. The Full Source Code of Repeat.java

 1: import java.util.*;

 2:

 3: class Repeat {

 4:     public static void main(String[] arguments) {

 5:         String sentence = "Thorium 230 is not a toy.";

 6:         int count = 10;

 7:         Calendar start = Calendar.getInstance();

 8:         int startMinute = start.get(Calendar.MINUTE);

 9:         int startSecond = start.get(Calendar.SECOND);

10:         start.roll(Calendar.MINUTE, true);

11:         int nextMinute = start.get(Calendar.MINUTE);

12:         int nextSecond = start.get(Calendar.SECOND);

13:         while (count < 1000000) {

14:             System.out.println(sentence);

15:             GregorianCalendar now = new GregorianCalendar();

16:             if (now.get(Calendar.MINUTE) >= nextMinute) {

17:                 if (now.get(Calendar.SECOND) >= nextSecond) {

18:                     break;

19:                 }

20:             }

21:             count++;

22:         }

23:         System.out.println("\nI wrote the sentence " + count

24:             + " times.");

25:         System.out.println("I have learned my lesson.");

26:     }

27: }

The following things are taking place in this program:

  • Line 1: The import statement makes the java.util group of classes available to this program. You're going to use one of these classes, Calendar, in order to keep track of time while the program is running.

  • Lines 3 and 4: The Repeat class is declared, and the main() block of the program begins.

  • Lines 5 and 6: The sentence variable is set up with the text of the punishment sentence, and the count variable is created with a value of 0.

  • Line 7: Using the Calendar class, which keeps track of time-related information, the start variable is created with the current time as its value.

  • Lines 8 and 9: The get() method of the Calendar class is used to retrieve the current minute and second and store them in the variables startMinute and startSecond.

  • Line 10: The Calendar roll() method is used to roll the value of the start variable one minute forward in time.

  • Lines 11 and 12: The get() method is used again to retrieve the minute and second for start and store them in the variables nextMinute and nextSecond.

  • Line 13: The while statement begins a loop using the count variable as the counter. When count hits 1,000,000, the loop will end.

  • Line 14: The punishment text, stored in the string variable sentence, is displayed.

  • Line 15: Using the Calendar class, the now variable is created with the current time.

  • Lines 16–20: Using one if statement inside of another, the program tests to see if one minute has passed by comparing the current minute and second to the values of nextMinute and nextSecond. If it has passed, break ends the while loop.

  • Line 22: The } marks the end of the while loop.

  • Lines 23–25: The computer displays the number of times it repeated the punishment sentence and claims to be rehabilitated.

  • Lines 26 and 27: The main() block of the program and the program are closed out with } marks.

Compile the program with the javac compiler tool or another compiler and then give it a try. Using the JDK, you can run it by typing the following at the command line:

java Repeat

Run this program several times to see how many sentences are displayed in a minute's time. The Repeat program is an excellent way to see whether your computer is faster than mine. During the testing of this workshop program, Repeat usually displayed around 530,000 sentences in a minute's time. If your computer displays the sentence more times than mine does, don't just send me your condolences. Buy more of my books so I can upgrade.


Summary

The information presented in this chapter is material you will be coming back to again and again and again when you write programs. Loops are a fundamental part of most programming languages. In several of the hours to come, you get a chance to manipulate graphics so you can produce animated effects. You couldn't do this without loops.

As you might expect, every one of Bart Simpson's chalkboard punishments has been documented on the World Wide Web. Visit http://www.snpp.com/guides/chalkboard.openings.html to see the list along with a Java applet that draws sayings on a green chalkboard.


Q&A

Q1:

Should the counter variable used in a for loop be created inside the for statement or before the loop begins?

A1:

The only time the counter should be created outside of the for loop, or any other loop for that matter, is when it needs to be used in another part of the program. A variable that is created in a loop or other kind of block statement only exists inside that block. You can't use the value in any other part of the program. This is good programming practice because it makes it harder to misuse variables—you can't set their value in one part of the program and use them somewhere else incorrectly. The concept of a variable existing in one part of a program and not existing anywhere else is called scope, and it's covered fully during Hour 11, "Describing What Your Object Is Like."

Q2:

The term initialization has been used in several places. What does it mean?

A2:

It means to give something an initial value and set it up. When you create a variable and assign a starting value to it, you are initializing the variable.

Q3:

If a loop never ends, how does the program stop running?

A3:

Usually in a program where a loop does not end, something else in the program is set up to stop execution in some way. For example, a loop could continue indefinitely while the program waits for the user to click a button labeled Quit.

A3:

One bug that crops up often as you work on programs is an infinite loop, a loop that never stops because of a programming mistake. If one of the Java programs you run from the command line is stuck in an infinite loop, press Ctrl+C.

Q4:

Why do airplane windows have tiny little scratches on them?

A4:

The small hairline scratches and spider-web marks are caused by cleaning or chemicals in the atmosphere such as volcanic ash. The windows, made of plastic rather than glass, get scratched often.

There's nothing unsafe about the scratches on the windows, which are periodically removed and polished.


Quiz

The following questions will test your knowledge of loops. In the spirit of the subject matter, repeat each of these until you get them right.

Questions

1:

What must be used to separate each section of a for statement?

  1. Commas

  2. Semicolons

  3. Off-duty police officers

2:

Which statement causes a program to go back to the statement that began a loop and then keep going from there?

  1. continue

  2. next

  3. skip

3:

When it comes to borrowing a car from your father, what lesson did you learn during this hour?

  1. Don't even think about it.

  2. Speak softly and carry a big stick.

  3. It's better to beg forgiveness than to ask permission.

Answers

A1: | b. Commas are used to separate things within a section, but semicolons separate sections.
A2: | a. The break statement ends a loop entirely, and continue skips to the next go-round of the loop.
A3: | c. Though I'm not sure my father has completely forgiven me for that incident in 1987.


Activities

If your head isn't going in circles from all this looping, review the topics of this hour with the following activities:

  • Modify the Repeat program so that it uses a for loop instead of a while loop, and compare the efficiency of each approach.

  • Write a short program using loops that finds the first 400 numbers that are multiples of 13.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


    Part III: WORKING WITH INFORMATION IN NEW WAYS

    HOUR 9 Storing Information with Arrays

    HOUR 10 Creating Your First Object

    HOUR 11 Describing What Your Object Is Like

    HOUR 12 Making the Most of Existing Objects


Hour 9. Storing Information with Arrays

No one benefited more from the development of the computer than Santa Claus. For centuries, humankind has put an immense burden on him to gather and process information. Old St. Nick has to keep track of the following things:

  • Naughty children

  • Nice children

  • Gift requests

  • Homes with impassable chimneys

  • Women who want more from Santa than Mrs. Claus is willing to let him give

  • Countries that shoot unidentified aircraft first and ask questions later

Computers were a great boon at the North Pole. They are ideal for the storage, categorization, and study of information.

The most basic way that information is stored in a computer program is by putting it into a variable. However, this method is limited to relatively simple usage. If Santa had to give each naughty child his or her own variable name, he would be working on the program for the next 12 holiday seasons at least, to say nothing of the effect on his jolly disposition.

The list of naughty children is an example of a collection of similar information. Each child's name is a string of text or some kind of Santa Information System ID number. To keep track of a list of this kind, you can use arrays.

Arrays are groups of related variables that share the same type. You can have arrays of any type of information that can be stored as a variable. Arrays can be used to keep track of more sophisticated types of information than a single variable, but they are almost as easy to create and manipulate as variables are.

The following topics will be covered during this hour:

  • Creating an array

  • What a dimension of an array is

  • Giving a value to an array element

  • Changing the information in an array

  • Making multidimensional arrays

  • Sorting an array


Creating Arrays

Arrays are variables that are grouped together under a common name. The term "array" should be familiar to you, though the meaning might not be so clear—think of a salesman showing off his array of fabulous cleaning products, or a game show with a dazzling array of prizes. Like variables, arrays are created by stating the type of the variable being organized into the array and the name of the array. The difference lies in the addition of the square bracket marks, [ and ].

You can create arrays for any type of information that can be stored as a variable. For example, the following statement creates an array of string variables:

String[] naughtyChild;

Here are two more examples:

int[] reindeerWeight;

boolean[] hostileAirTravelNations;

By the Way

Java is flexible about where the square brackets are placed when an array is being created. You can put them after the variable name instead of the variable type, as in the following:

String niceChild[];

To make arrays easier for humans to spot in your programs, you should probably stick to one style rather than switching back and forth, though Java allows both styles of usage. Examples in this book always place the brackets after the variable type.

The previous examples create arrays, but they do not store any values in them initially. To do this, you must either use the new statement along with the variable type or store values in the array within { and } marks. You also must specify how many different items will be stored in the array. Each item in an array is called an element.

The following statement creates an array and sets aside space for the values that it will hold:

int[] elfSeniority = new int[250];

This example creates an array of integers called elfSeniority. The array has 250 elements in it that can be used to store the months that each of Santa's elves has been employed at the Pole. If the rumors are true and Santa runs a union shop, this information is extremely important to keep track of.

When you create an array with the new statement, you must specify the number of elements. Each element of the array is given an initial value when it is set up with new; the value depends on the type of the array. All numeric arrays have the value 0, char arrays have the value '\0', and boolean arrays have the value false. A String array and all other objects are created with the initial value of null.

For arrays that are not extremely large, you can set up their initial values at the same time that you create them. The following example creates an array of strings and gives them initial values:

String[] reindeerNames = { "Dasher", "Dancer", "Prancer", "Vixen",

    "Comet", "Cupid", "Donder", "Blitzen" };

The information that should be put into elements of the array is placed between { and } brackets, with commas separating each element. The number of elements in the array is not specified in the statement because it is set to the number of elements in the comma-separated list. Each element of the array in the list must be of the same type. The preceding example uses a string for each of the reindeer names.

Once the array is created, you cannot make more space and add another variable to the array. Even if you recall the most famous reindeer of all, you couldn't add "Rudolph" as the ninth element of the reindeerNames array. A Java compiler won't let poor Rudolph join in any reindeerNames.


Using Arrays

You use arrays in a program as you would use any variable, except for the element number in between the square brackets next to the array's name. Once you refer to the element number, you can use an array element anywhere a variable could be used. The following statements all use arrays that have already been defined in this hour's examples:

elfSeniority[193] += 1;

niceChild[94287612] = "Max";

if (hostileAirTravelNations[currentNation] == true)

    sendGiftByMail();

An important thing to note about arrays is that the first element of an array is numbered 0 instead of 1. This means that the highest number is one less than you might expect. For example, consider the following statement:

String[] topGifts = new String[10];

This statement creates an array of string variables that are numbered from 0 to 9. If you referred to topGifts[10] somewhere else in the program, you would get an error message like the following when you run the program:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:

        at Gift.main(Gift.java:4);

Like all of the error messages encountered in Java, this one's a bit hard to decipher. The key thing to note is the part that mentions an exception, because exceptions are another word for errors in Java programs. This exception is an "array index out of bounds" error, which means that a program tried to use an array element that doesn't exist within its defined boundaries.

By the Way

This error could have occurred when you ran the Blanks application in Hour 4, "Understanding How Java Programs Work." The program tried to use the arrayelements arguments[0], arguments[1], and arguments[2]. If too-few arguments are specified when the program is run, those array references will cause an out-of-bounds error.

If you want to check the upper limit of an array during a program so that you can avoid going beyond that limit, you can use a variable called length that is associated with each array that is created. The length variable is an integer that contains the number of elements an array can hold. The following example creates an array and then reports its length:

String[] reindeerNames = { "Dasher", "Dancer", "Prancer", "Vixen",

    "Comet", "Cupid", "Donder", "Blitzen", "Rudolph" };

System.out.println("There are " + reindeerNames.length + " reindeer.");

In this example, the value of reindeerNames.length is 9, which means that the highest element number you can specify is 8.

There are two primary ways to work with text in Java: a string or an array of characters. When you're working with strings, one useful technique is to put each character in a string into its own element of a character array. To do this, call the string's toCharArray() method, which produces a char array with the same number of elements as the length of the string.

This hour's first project is an application that uses both of the techniques introduced in this section. The NoSpaces program displays a string with all space characters (' ') replaced with periods ('.').

Enter the text of Listing 9.1 in your word processor and save the file as NoSpaces.java.

Listing 9.1. The Full Text of NoSpaces.java

 1: class NoSpaces {

 2:     public static void main(String[] arguments) {

 3:         String mostFamous = "Rudolph the Red-Nosed Reindeer";

 4:         char[] mfl = mostFamous.toCharArray();

 5:         for (int dex = 0; dex < mfl.length; dex++) {

 6:             char current = mfl[dex];

 7:             if (current != ' ') {

 8:                 System.out.print(current);

 9:             } else {

10:                 System.out.print('.');

11:             }

12:         }

13:     }

14: }

Compile and run this program using your Java development environment. The following commands can be used with the JDK:

javac NoSpaces.java

java NoSpaces

This program produces the following output:

Rudolph.the.Red-Nosed.Reindeer

The NoSpaces application stores the text Rudolph the Red-Nosed Reindeer in two places: a string called mostFamous, and a char array called mfl. The array is created in line 4 by calling the toCharArray() method of mostFamous, which fills an array with one element for each character in the text. The character R goes into element 0, u into element 1, d into element 2, and so on, up to r in element 29.

The for loop in lines 5–12 looks at each character in the mfl array. If the character is not a space, it is displayed. If it is a space, a . character is displayed instead.


Multidimensional Arrays

The arrays you have been introduced to thus far in the hour all have one dimension, so you can retrieve an element using a number ranging from 0 to the largest element number in the array. Some types of information require more dimensions to store adequately as arrays. An example would be the (x,y) coordinate system. If you needed to store a list of x and y coordinates that have a point marked on them, you could use a two-dimensional array. One dimension of the array could store the x coordinate, and the other dimension could store the y coordinate.

To create an array that has two dimensions, you must use an additional set of square brackets when creating and using the array. Consider the following:

boolean[][] selectedPoint = new boolean[50][50];

selectedPoint[4][13] = true;

selectedPoint[7][6] = true;

selectedPoint[11][22] = true;

This example creates an array of Boolean values called selectedPoint. The array has 50 elements in its first dimension and 50 elements in its second dimension, so there are 2,500 individual array elements that can hold values (50 multiplied by 50). When the array is created, each element is given the default value of false. Three elements are then given the value of true: a point at the (x,y) position of (4,13), one at (7,6), and one at (11,22).

Arrays can have as many dimensions as you need, but keep in mind that they take up a lot of memory if they're extremely large. Creating the 50 by 50 selectedPoint array was equivalent to creating 2,500 individual variables.


Sorting an Array

When you have grouped a bunch of similar items together into an array, one of the things you can do easily is rearrange items. The following statements switch the values of two elements in an integer array called numbers:

int temp = numbers[5];

numbers[5] = numbers[6];

numbers[6] = temp;

These statements result in numbers[5] and numbers[6] trading values with each other. The integer variable called temp is used as a temporary storage place for one of the values being swapped.

The most common reason to rearrange elements of an array is to sort them into a specific order. Sorting is the process of arranging a list of related items into a set order. An example would be sorting a list of numbers from lowest to highest.

Santa Claus, the world's biggest user of lists, might want to use sorting to rearrange the order of gift recipients according to last name. This order could determine who receives gifts first on Christmas Eve, with people such as Willie Aames and Paul Azinger raking in their Yuletide plunder much earlier than alphabetical unfortunates such as Dweezil Zappa and Jim Zorn. (As someone whose last name begins with "C," I'm not necessarily opposed to this practice.)

Sorting an array is easy in Java because the Arrays class does all of the work for you. Arrays, which is part of the java.util group of classes, can rearrange arrays of all variable types as well as strings.

To use the Arrays class in a program to sort an array, undertake the following steps:

  • Use the import java.util.* statement to make all of the java.util classes available in the program.

  • Create the array.

  • Use the sort() method of the Arrays class to rearrange an array.

An array of variables that is sorted by the Arrays class will be rearranged into ascending numerical order. This will be easy to see with an array of numbers such as float values. Characters and strings will be arranged according to the alphabet, with the first letters such as A, B, and C coming first, and the last letters such as X, Y, and Z coming last.

Listing 9.2 contains a short program that sorts five names. Enter this with your word processor and save the file as Name.java. Make sure not to overlook line 1. If you do, the program will fail to compile because the Arrays class in line 12 can't be found.

Listing 9.2. The Full Source Code of Name.java

 1: import java.util.*;

 2:

 3: class Name {

 4:     public static void main(String[] arguments) {

 5:         String names[] = { "Peter", "Patricia", "Hunter", "Sarah",

 6:             "Gabe", "Gina", "Rob", "John", "Zoey", "Tammy", "Robert",

 7:             "Sean", "Paschal", "Kathy", "Neleh", "Vecepia" };

 8:         System.out.println("The original order:");

 9:         for (int i = 0; i < names.length; i++) {

10:             System.out.println(i + ": " + names[i]);

11:         }

12:         Arrays.sort(names);

13:         System.out.println("The new order:");

14:         for (int i = 0; i < names.length; i++) {

15:             System.out.println(i + ": " + names[i]);

16:         }

17:     }

18: }

After you have created this source file, compile it. Using the JDK, you can compile it at a command line by entering this command:

javac Name.java

This Java program displays a list of five names in their original order, sorts the names, and then redisplays the list.

The following output is produced:

The original order:

0: Peter

1: Patricia

2: Hunter

3: Sarah

4: Gabe

5: Gina

6: Rob

7: John

8: Zoey

9: Tammy

10: Robert

11: Sean

12: Paschal

13: Kathy

14: Neleh

15: Vecepia

The new order:

0: Gabe

1: Gina

2: Hunter

3: John

4: Kathy

5: Neleh

6: Paschal

7: Patricia

8: Peter

9: Rob

10: Robert

11: Sarah

12: Sean

13: Tammy

14: Vecepia

15: Zoey

When you're working with strings and the basic types of variables such as integers and floating-point numbers, you can only sort them by ascending order using the Arrays class. You can write code to do your own sorts by hand if you desire a different arrangement of elements during a sort, or you want better efficiency than the Arrays class provides.

By the Way

There are numerous sorting techniques that have been created for use in computer programs. The Arrays class uses a technique called a "tuned quicksort," which was described by Jon L. Bentley and M. Douglas McIlroy in a 1993 issue of Software-Practice and Experience. Different techniques have their own names, including the heap sort, tree sort, and bubble sort. Jason Harrison has a web page that uses Java to visually demonstrate the speed of different sorting techniques. To see it, visit the web address http://www.cs.ubc.ca/spider/harrison/Java/sorting-demo.html.


Workshop: Array of Prizes, Indeed

Watch the syndicated game show Wheel of Fortune for any length of time and you'll be surprised at how predictable the contestants are.

In the years that this show has been one of the world's most successful television programs, fortune seekers have worked the puzzle-solving process into an exact science.

Wheel contestants typically guess the same letters when they are starting out on a puzzle: R, S, T, L, and N. In the final round, when these letters and the vowel E are given to the players right away, they usually choose four other letters: C, D, M, and the vowel O.

The reason for this predictability is that these are the letters that appear most often in English words. The contestants are stifling their desire for spontaneity in order to better their chances to win a trip to Bermuda, cash, and a Yamaha Waverunner.

By the Way

In case you're unfamiliar with the show, Wheel of Fortune is a game in which three contestants try to guess the letters of a phrase, name, quote, or other memorable item. If they get a letter right and it's a consonant, they win the amount of money they spun on a big wheel. To re-create the experience, play hangman with some of your friends in front of a studio audience, hand out random amounts of money when someone guesses a letter in the secret word or phrase, and give the winner a new Chevy Suburban.

Your Java workshop during this hour will test the most-common-letter theory by looking at as many different phrases and expressions as you care to type. An array will be used to count the number of times that each letter appears. When you're done, the program will present each letter and the number of times it appears in the phrases you entered. It also will present some clues about which letters to avoid entirely (unless you suspect that a puzzle's answer is the Aztec priest-ruler Quetzalcoatl or the fire god Xiuhtecuhtle).

Open up a new file in your word processor and call it Wheel.java. Enter Listing 9.3 and save the file when you're done.

Listing 9.3. The Full Source Code of Wheel.java

 1: class Wheel {

 2:    public static void main(String[] arguments) {

 3:        String phrase[] = {

 4:            "A STITCH IN TIME SAVES NINE",

 5:            "DON'T EAT YELLOW SNOW",

 6:            "JUST DO IT",

 7:            "EVERY GOOD BOY DOES FINE",

 8:            "I WANT MY MTV",

 9:            "HOW 'BOUT THEM COWBOYS",

10:            "PLAY IT AGAIN, SAM",

11:            "FROSTY THE SNOWMAN",

12:            "ONE MORE FOR THE ROAD",

13:            "HOME FIELD ADVANTAGE",

14:            "VALENTINE'S DAY MASSACRE",

15:            "GROVER CLEVELAND OHIO",

16:            "WONDERFUL WORLD OF DISNEY",

17:            "COAL MINER'S DAUGHTER",

18:            "WILL IT PLAY IN PEORIA"

19:        };

20:        int[] letterCount = new int[26];

21:        for (int count = 0; count < phrase.length; count++) {

22:            String current = phrase[count];

23:            char[] letters = current.toCharArray();

24:            for (int count2 = 0;  count2 < letters.length; count2++) {

25:                char lett = letters[count2];

26:                if ( (lett >= 'A') & (lett <= 'Z') ) {

27:                    letterCount[lett - 'A']++;

28:                }

29:            }

30:        }

31:        for (char count = 'A'; count <= 'Z'; count++) {

32:            System.out.print(count + ": " +

33:                letterCount[count - 'A'] +

34:                "\t");

35:        }

36:        System.out.println();

37:    }

38: }

After you compile the file and run it, the output should resemble Listing 9.4.

Listing 9.4. Output of the Wheel Program

A: 22   B: 3   C: 5   D: 13   E: 28   F: 6   G: 5   H: 8   I: 18

J: 1    K: 0   L: 13  M: 10   N: 19   O: 27  P: 3   Q: 0   R: 13

S: 15   T: 19  U: 4   V: 7    W: 9    X: 0   Y: 10  Z: 0

The following things are taking place in the Wheel program:

  • Lines 1 and 2: The Wheel program and the main() block of the program begin.

  • Lines 3–19: Phrases are stored in a string array called phrase. Every phrase between the { on Line 3 and the } on Line 19 will be stored in its own element of the array, beginning with A STITCH IN TIME SAVES NINE in phrase[0].

  • Line 20: An integer array called letterCount is created with 26 elements. This array will be used to store the number of times each letter appears. The order of the elements is from A to Z. letterCount[0] will store the count for letter A, letterCount[1] will store the count for B, and so on, up to letterCount[25] for Z.

  • Line 21: A for loop is begun that cycles through the phrases stored in the phrase array. The phrase.length variable is used in the for statement to end the loop after the last phrase is reached.

  • Line 22: A string variable named current is created and set with the value of the current element of the phrase array.

  • Line 23: A character array is created that stores all of the characters in the current phrase.

  • Line 24: A for loop is begun that cycles through the letters of the current phrase. The letters.length variable is used to end the loop after the last letter is reached.

  • Line 25: A character variable called lett is created with the value of the current letter. In addition to their text value, characters have a numeric value. Because elements of an array are numbered, the numeric value of each character will be used to determine its element number.

  • Lines 26–28: An if statement is used to weed out all characters that are not part of the alphabet, such as punctuation and spaces. An element of the letterCount array is increased by 1 depending on the numeric value of the current character, which is stored in lett. The numeric values of the alphabet range from 65 for 'A' to 90 for 'Z'. Because the letterCount array begins at 0 and ends at 25, 'A' (65) is subtracted from lett to determine which array element to increase.

  • Line 29: One pass through the inner for loop ends, and the loop returns to Line 24 to get the next letter in the current phrase, if there is one.

  • Line 30: One pass through the outer for loop ends, and the loop returns to Line 21 to get the next phrase, if there is one.

  • Line 31: A for loop is used to cycle through the alphabet from 'A' to 'Z'.

  • Lines 32–34: The current letter is displayed followed by a semicolon and the number of times the letter appeared in the phrases stored in the phrase array. The \t inserts a Tab character.

  • Line 35: One pass through the for loop ends, and the loop returns to Line 31 to get the next character in the alphabet, unless 'Z' has been reached.

  • Lines 36–38: A blank line is displayed, followed by the end of the program's main() block, and the end of the program.

This workshop project shows how two nested for loops can be used to cycle through a group of phrases one letter at a time. Java attaches a numeric value to each character; this value is easier to use than the character inside arrays.

By the Way

The numeric values associated with each of the characters from A to Z are those used by the ASCII character set. ASCII is a standard method of arranging and numbering letters, numbers, punctuation, and other symbols that can be represented by a computer. The ASCII character set is part of Unicode, the full character set supported by the Java language. Unicode includes support for more than 60,000 different characters used in the world's written languages.

Using the length variable makes it possible for you to add as many phrases as desired within the { and } marks. The letters in each of the new phrases you add will be analyzed, and you can build up a better idea of what it takes to make a small fortune in 30 minutes on television.


Summary

Arrays make it possible to store complicated types of information in a program and manipulate that information. They're ideal for anything that can be arranged in a list and can be accessed easily using the loop statements that you learned about during Hour 8, "Repeating an Action with Loops."

To be honest, the information processing needs of Santa Claus probably have outgrown arrays. There are more children being manufactured each year, and the gifts they want are increasing in complexity and expense. Pokémon cards alone created a logistical nightmare at the North Pole.

Your programs are likely to use arrays to store information that is unwieldy to work with using variables, even if you're not making any lists or checking them twice.


Q&A

Q1:

Do arrays have to begin with an element 0, or can they range from a higher minimum number to a higher maximum number, such as 65 to 90?

A1:

They don't have to begin at element 0, but it is more efficient to do so because it takes up less memory in the computer to store arrays that begin with 0. You can use arrays of a higher index number simply by referring to the numbers you want to use. For example, if you created a for loop that cycled from array element 65 to element 90, you could disregard any other element numbers. However, there still will be array elements numbered from 0 to 64 taking up space in memory, even if you don't use them for anything.

Q2:

Is the numeric range of the alphabet, from 65 for A to 90 for Z, part of the basic Java language? If so, what are 1 through 64 reserved for?

A2:

The numbers 1 through 64 include numerals, punctuation marks, and some unprintable characters, such as linefeed, newline, and backspace. A number is associated with each printable character that can be used in a Java program, as well as some unprintable ones. Java uses the Unicode numbering system, which supports more than 60,000 different characters from the different languages of the world. The first 127 characters are from the ASCII character set, which you might have used in another programming language.

Q3:

Why are some errors called exceptions?

A3:

The significance of the term is that a program normally runs without any problems, and the exception signals an exceptional circumstance that must be dealt with. Exceptions are warning messages that are sent from within a Java program. In the Java language, the term error is sometimes confined to describe error conditions that take place within the interpreter running a program. You learn more about both subjects during Hour 18, "Handling Errors in a Program."

Q4:

In a multidimensional array, is it possible to use the length variable to measure different dimensions other than the first?

A4:

You can test any dimension of the array. For the first dimension, use length with the name of the array, as in x.length. Subsequent dimensions can be measured by using length with the [0] element of that dimension. Consider an array called data that was created with the following statement:

int[][][] data = new int[12][13][14];

The dimensions of this array can be measured by using the data.length variable for the first dimension, data[0].length for the second, and data[0][0].length for the third.

Q5:

Can the length variable be set to increase or decrease the size of an array after it has been created?

A5:

There's no way to modify the size of an array after it has been created; length is strictly used to find out an array's upper boundary.

Q6:

Who did the singing for Milli Vanilli?

A6:

The vocals were performed by John Davis and Brad Howell, two former U.S. soldiers living in Germany who were recruited by Milli Vanilli producer Frank Farian. Another ex-soldier, Charles Shaw, performed the rap portion of the single "Girl You Know It's True."

Because Howell didn't want to tour, Farian hired Rob Pilatus and Fabrice Morvan and presented them as the band's singers. After the news broke that Pilatus and Morvan didn't sing on their albums, the real singers released The Moment of Truth and called themselves The Real Milli Vanilli. Pilatus and Morvan also released an album as Rob & Fab.

All of the projects were commercial failures.


Quiz

If the brain were an array, you could test its length by answering each of the following questions about arrays.

Questions

1:

What types of information are arrays best suited for?

  1. Lists

  2. Pairs of related information

  3. Trivia

2:

What variable can be used to check the upper boundary of an array?

  1. top

  2. length

  3. limit

3:

Who is the famous Aztec priest-ruler?

  1. Quisp

  2. Quetzalcoatl

  3. Quichelorraine

Answers

A1: | a. Lists that contain nothing but the same type of information—strings, numbers, and so on—are well-suited for storage in arrays.
A2: | b. The length variable contains a count of the number of elements in an array.
A3: | b. It's also the name of a god of learning and civilization who is depicted as an approaching storm whose winds kick up dust before the rain comes.


Activities

To give yourself an array of experiences to draw from later, you can expand your knowledge of this hour's topics with the following activities:

  • Create a program that uses a multidimensional array to store student grades. The first dimension should be a number for each student, and the second dimension should be for each student's grades. Display the average of all the grades earned by each student and an overall average for every student.

  • Write a program that stores the first 400 numbers that are multiples of 13 in an array.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


Hour 10. Creating Your First Object

One of the more fearsome examples of jargon that you'll encounter during these 24 hours is object-oriented programming. This is a complicated term that describes, in an elegant way, what a computer program is and how it works.

Before object-oriented programming, a computer program was usually described under the simplest definition you've learned in this book: a set of instructions listed in a file and handled in some kind of reliable order.

Whether the program is big or small, the programmer's job is largely the same—write instructions for each thing the computer must do. By thinking of a program as a collection of objects instead, you can figure out the tasks a program must accomplish, then assign the tasks to the objects where they best belong.

During this hour, the following topics will be covered:

  • Understanding objects

  • Describing an object with attributes

  • Determining how objects behave

  • Combining objects

  • Inheriting from other objects

  • Creating an object

  • Converting objects and other types of information


How Object-Oriented Programming Works

The programs you create with Java can be thought of as objects, just like physical objects that exist in the real world. Objects exist independently of other objects, interact in specific ways, and can often be combined with other objects to form something. Examples of objects in the real world include ham sandwiches, the Nixon tapes, a stereo receiver, and my father-in-law Clint. Examples of objects in a computer include a web browser, the Java compiler, an MP3 file, and a Macromedia Flash plug-in.

If you think of a computer program as a group of objects that interact with each other, you often can come up with a design for the program that's more reliable, easier to understand, and reusable in other projects.

Later in this book you will create a Java program that displays pie graphs—circles with different-colored pie slices to represent data (see Figure 10.1). A pie chart is an object that is made up of smaller objects—individual slices of different colors, a legend identifying what each slice represents, and a title.

Figure 10.1. A Java program that displays a pie chart.

Each object has things that make it different from other objects. Pie charts are circular, while bar graphs represent data as a series of rectangles instead of pie slices. If you break down computer programs in the same way you have broken down a pie chart, you are engaging in object-oriented programming. It's a much less complicated concept than it originally sounds.

In object-oriented programming, an object contains two things: attributes and behavior. Attributes are things that describe the object and show how it is different from other objects. Behavior is what an object does.

You create objects in Java by using a class as a template. A class is a master copy of the object that is consulted to determine which attributes and behavior an object should have. The term class should be familiar to you, because every Java program you have written thus far has been called a class. Every program you create with Java will be a class because each one can be used as a template for the creation of new objects. As an example, any Java program that uses strings is using objects created from the String class. This class contains attributes that determine what a String object is and behavior that controls what String objects can do.

With object-oriented programming, a computer program is a group of objects that work together to get something done. Some simple programs may seem as though they consist of only one object—the class file. However, even those programs are using other objects to get work done.


Objects in Action

Consider the case of a program that displays a pie chart. A PieChart object could consist of the following:

  • Behavior to calculate how big each pie slice should be in the chart

  • Behavior to draw the chart

  • An attribute to store the title of the chart

When you compare a pie chart in the real world to a PieChart object in a computer program, it might seem odd to ask the PieChart object to draw itself. Graphs don't draw themselves in the real world. However, objects in object-oriented programming work for themselves whenever possible. This quality makes them more useful because you can incorporate them in other programs without having as many things to teach them. If a PieChart object did not know how to draw itself, for instance, every time you used that PieChart object somewhere, you would have to create behavior to draw it.

For another example of object-oriented programming, consider the autodialer program that Matthew Broderick's character used in War Games to find computers he could break into.

By the way

An autodialer is software that uses a modem to dial a series of phone numbers in sequence. The purpose of such a program is to find other computers that answer their own phone, so you can call them up later to see what they are.

Using an autodialer today practically guarantees you'll be on a first-name basis with your local phone company. In the early '80s, it was a good way to be rebellious without actually leaving the house. David Lightman (the character portrayed by Broderick) used his autodialer to look for a video game company's private computer system so he could play the company's new game before it was released. Instead, Lightman found a secret government computer that could play everything from chess to Global Thermonuclear War.

An autodialer, like any computer program, can be thought of as a group of objects that work together. It could be broken down into the following:

  • A Modem object, which knows how to make the modem dial a number and how to report when another computer system has answered a call

  • A Monitor object, which keeps track of what numbers were called and which ones were successful, and can save this information for later inspection

Each object exists independently of the other. The Modem object does its job without requiring any help from the Monitor object.

One of the advantages of having a completely independent Modem object is that it could be used in other programs that need modem functionality. If David Lightman returns to hacking in War Games 2006 after a bitter divorce from Jennifer Mack (Ally Sheedy's character), he could use the Modem object as part of an elaborate ATM fraud scheme.

Another reason to use self-contained programs such as objects is that they are easier to debug. Computer programs quickly become unwieldy in size. If your program is just one big list of instructions, you can't change one part without making sure it won't damage the performance of other parts that are dependent on it. If you're debugging something like a Modem object, though, you know it's not dependent on anything else. You can focus on making sure the Modem object does the job it's supposed to do and holds the information that it needs to do its job.

For these reasons, object-oriented programming is becoming the norm in many areas of software development. Learning an object-oriented language like Java as your first programming language can be an advantage in some ways because you're not unlearning the habits of other styles of programming. The main disadvantage is that an object-oriented language can be more challenging to learn than a non-object-oriented language such as Visual Basic.


What Objects Are

As stated, objects are created by using a class of objects as a guideline. The following is an example of a class:

public class Modem {

}

Any object created from this class can't do anything because it doesn't have any attributes or behavior yet. You need to add those or this class that won't be terribly useful. You could expand the class into the following:

public class Modem {

    int speed;

    public void displaySpeed() {

        System.out.println("Speed: " + speed);

    }

}

The Modem class now should be recognizable to you because it looks a lot like the programs you have written during Hours 1 through 9. The Modem class begins with a class statement, as your programs have, except that it has a public statement alongside it. The public statement means that the class is available for use by the public—in other words, by any program that wants to use Modem objects.

The first part of the Modem class creates an integer variable called speed. This variable is an attribute of the object; the name is one of the things that distinguish a modem from other modems.

The second part of the Modem class is a method called displaySpeed(). This method is some of the object's behavior. It contains one statement: a System.out. println() statement that displays the modem's speed value along with some text.

If you wanted to use a Modem object in a program, you would create the object much like you would create a variable. You could use the following statement:

Modem com = new Modem();

This statement creates a Modem object called com. You now can use the object in the program; you can set its variables and call its methods. To set the value of the speed variable of the com object, you could use the following statement:

com.speed = 28800;

To make this modem display its speed by calling the displaySpeed() method, you could use the following code:

com.displaySpeed();

The Modem object named com would respond to this statement by displaying the text Speed: 28800.


Understanding Inheritance

One of the biggest advantages to using object-oriented programming is inheritance, which is the way one object can inherit behavior and attributes from other objects that are similar to it.

When you start creating objects for use in other programs, you will find that some new objects you want are a lot like other objects that already have been developed. For example, if David Lightman does not run afoul of the law because of his ATM scheme, he might want to create an object that can handle error correction and other advanced modem features that weren't around back in 1983 when War Games was released.

Lightman could create a new ErrorCorrectionModem object by copying the statements of the Modem object and revising them. However, if most of the behavior and attributes of ErrorCorrectionModem are the same as those of Modem, this is a lot of unnecessary work. It also means that Lightman will have to maintain two separate programs if something needs to be changed or debugged later.

Through inheritance, a programmer can create a new class of objects by defining only how it is different from an existing class. Lightman could make ErrorCorrectionModem inherit from Modem, and all he would have to write are the things that make error-correction modems different than previous modems.

The way a class of objects inherits from another class is through the extends statement. The following is a skeleton of an ErrorCorrectionModem class that inherits from the Modem class:

class ErrorCorrectionModem extends Modem {

    // program goes here

}


Building an Inheritance Hierarchy

Inheritance, which enables a variety of related classes to be developed without a lot of redundant work, makes it possible for code to be passed down from one class to another class to another class. This organization of classes is called a class hierarchy, and all of the standard classes you can use in your Java programs are part of a hierarchy.

Understanding a hierarchy is easier if you understand what subclasses and superclasses are. A class that inherits from another class is called a subclass, and the class that is inherited from is called a superclass.

In the preceding War Games example, the Modem class is the superclass of the ErrorCorrectionModem class. ErrorCorrectionModem is the subclass of Modem. A class can have more than one class that inherits from it in the hierarchy—another subclass of Modem could be ISDNModem, since ISDN modems have behavior and attributes that make them different from error-correcting modems. If there were a subclass of ErrorCorrectionModem such as InternalErrorCorrectionModem, it would inherit from all classes above it in the hierarchy—both ErrorCorrectionModem and Modem. These inheritance relationships are shown in Figure 10.2.

Figure 10.2. An example of a class hierarchy.

The programs you write as you are learning about Java won't use complicated class hierarchies. However, the classes that are part of the standard Java language make full use of inheritance. Understanding it is essential to working with the classes that are part of the Java language. You'll learn more about inheritance during Hour 12, "Making the Most of Existing Objects."


Converting Objects and Simple Variables

One of the most common tasks you'll need to accomplish in Java is to convert information from one form into another. There are several types of conversions you can do:

  • Converting an object into another object

  • Converting a simple variable into another type of variable

  • Using an object to create a simple variable

  • Using a simple variable to create an object

Simple variables are the basic data types you learned about during Hour 5, "Storing and Changing Information in a Program." These types include int, float, char, long, and double.

When using a method or an expression in a program, you must use the right type of information that's expected by these methods and expressions. A method that expects a Calendar object must receive a Calendar object, for instance. If you used a method that takes a single integer argument and you sent it a floating-point number instead, an error would occur when you attempted to compile the program.

By the way

There is one area in which Java is less particular: strings. When a method such as System.out.println() requires a string argument, you can use the + operator to combine several different types of information in that argument. As long as one of the things being combined is a string, the combined argument will be converted into a string. This makes the following statements possible:

float sentence = 17.5F;

System.out.println("My sentence has been reduced to "

    + sentence + "years.");

Converting information into a new form in a program is called casting. Casting produces a new value that is a different type of variable or object than its source. You don't actually change the value of a variable or object when it is cast. Instead, a new variable or object is created in the format you need.

The terms source and destination are useful when discussing the concept of casting. The source is some kind of information in its original form—whether it's a variable or an object. The destination is the converted version of the source in its new form.

Casting Simple Variables

With simple variables, casting occurs most commonly between numeric variables, such as integers and floating-point numbers. There's one type of variable that cannot be used in any casting: Boolean values.

To cast information into a new format, you precede it with the new format surrounded by parenthesis marks. For example, if you wanted to cast something into a long variable, you would precede it with (long).

For example, the following statements cast a float value into an int:

float source = 7.06F;

int destination = (int)source;

In a variable cast where the destination holds larger values than the source, the value is converted easily. An example is when a byte is cast into an int. A byte holds values from –128 to 127, while an int holds values from –2.1 million to 2.1 million. No matter what value the byte variable holds, there's plenty of room for it in a new int variable.

You sometimes can use a variable in a different format without casting it at all. For example, char variables can be used as if they were int variables. Also, int variables can be used as if they were long variables, and anything can be used as a double.

By the way

A character can be used as an int variable because each character has a corresponding numeric code that represents its position in the character set. As an example, if the variable k has the value 67, the cast (char)k produces the character value 'C' because the numeric code associated with a capital C is 67, according to the ASCII character set. The ASCII character set is part of the Unicode character standard adopted by the Java language.

In most cases, because the destination provides more room than the source, the information is converted without changing its value. The main exceptions occur when an int or long variable is cast to a float, or a long is cast into a double.

When you are converting information from a larger variable type into a smaller type, you must explicitly cast it, as in the following statements:

int xNum = 103;

byte val = (byte)xNum;

Casting is used to convert an integer value called xNum into a byte variable called val. This is an example where the destination variable holds a smaller range of values than the source variable. A byte holds integer values ranging from –128 to 127, and an int holds a much larger range of integer values: –2.14 billion to 2.14 billion.

When the source variable in a casting operation has a value that isn't allowed in the destination variable, Java will change the value to make the cast fit successfully. This can produce unexpected results if you're not expecting the change.

Casting Objects

Objects can be cast into other objects as long as the source and destination are related by inheritance. One class must be a subclass of the other.

Some objects do not require casting at all. An object can be used where any of its superclasses are expected. For example, because all objects in Java are subclasses of the Object class, you can use any object as an argument when an Object is expected.

You also can use an object where one of its subclasses is expected. However, because subclasses usually contain more information than their superclasses, you might lose some of this information. If the object doesn't have a method that the subclass would contain, an error will result if that missing method is used in the program.

To use an object in the place of one of its subclasses, you must cast it explicitly with statements such as the following:

JWindow win = new JWindow();

JFrame top = new (JFrame)win;

This casts a JWindow object called win into a JFrame object. You won't lose any information in the cast, but you gain all the methods and variables the subclass defines.

Converting Simple Variables to Objects and Back

One thing you can't do is cast an object to a simple variable or a simple variable to an object. These types of information are too different in Java for them to be substituted for each other.

Instead, there are classes in the java.lang package for each of the simple variable types: Boolean, Byte, Character, Double, Float, Integer, Long, and Short. All of these classes are capitalized, which serves as a reminder that they are objects, rather than simple variable types.

Using class methods defined in each of these classes, you can create an object using a variable's value as an argument. The following statement creates an Integer object with the value 5309:

Integer suffix = new Integer(5309);

After you have created an object like this, you can use it like any other object. When you want to use that value again as a simple variable, the class has methods for this also. For example, to get an int value from the preceding suffix object, the following statement can be used:

int newSuff = suffix.intValue();

This statement causes the newSuff variable to have the value 5309, expressed as an int value. One of the most commonplace casts from an object to a variable is when you have a string that should be used in a numeric way. This is done by using the parseInt() method of the Integer class, as in the following example:

String count = "25";

int myCount = Integer.parseInt(count);

This converts a string with the text 25 into an integer with the value 25.

The next project you will create is an application that converts a string value in a command-line argument to a numeric value, a common technique when you're taking input from a user at the command line.

Enter the text of Listing 10.1 in your word processor and save the file as NewRoot.java.

Listing 10.1. The Full Text of NewRoot.java

 1: class NewRoot {

 2:     public static void main(String[] arguments) {

 3:         int number = 100;

 4:         if (arguments.length > 0) {

 5:             number = Integer.parseInt(arguments[0]);

 6:         }

 7:         System.out.println("The square root of "

 8:             + number

 9:             + " is "

10:             + Math.sqrt(number) );

11:     }

12: }

Compile the application using the javac tool included with the Java Development Kit or another compiler. When you run the program, specify an integer as a command-line argument, as in the following command:

java NewRoot 196

The program will display the number and its square root, as in this example:

The square root of 196 is 14.0

The NewRoot application is an expansion of an earlier tutorial from Hour 4, "Understanding How Java Programs Work." The Root program in that hour displayed the square root of the integer 225.

That program would have been more useful if it took a number submitted by a user and displayed its square root. This requires conversion from a string to an integer. All command-line arguments are stored as elements of a String array, so you must be able to convert them to numbers before using them in mathematical expressions.

To create an integer value based on the contents of a string, the Integer.parseInt() method is called with the string as the only argument, as in Line 5:

number = Integer.parseInt(arguments[0]);

Because arguments[0] holds the first command-line argument submitted when the application was run, the value of number will be an integer based on that string.

Autoboxing and Unboxing

Every one of the basic data types in Java has a corresponding object class: boolean (Boolean class), byte (Byte), char (Character), double (Double), float (Float), int (Integer), long (Long), and short (Short).

For each of these pairs, the information has identical value. The only difference between them is the format the value takes. An integer value such as 413 could be represented by either an int or the Integer class.

Java 2 version 5 includes support for autoboxing and unboxing, new language features that make it possible to use the basic data type and object forms of a value interchangeably.

These features work behind the scenes, assuring that when you are expecting a data type, an object will be converted to the matching data type with the same value. This also is true in the other direction: a data type will be converted to an object as necessary.


Workshop: Creating an Object

To see a working example of classes and inheritance, you will create classes that represent two types of objects: cable modems, which will be implemented as the CableModem class, and DSL modems, which will be implemented as the DslModem class.

For the sake of simplicity, the workshop will focus on a few simple attributes and behavior for these objects:

  • Each object should have a speed and be able to display it when asked.

  • Each object should be able to connect to the Internet.

One thing that cable modems and DSL modems have in common is that they both have a speed. Because it is something they share, it could be put into a class that is the superclass of both the CableModem and DslModem classes. Call this class Modem. Using your word processor, create a new file and save it as Modem.java. Enter Listing 10.2 and save the file.

Listing 10.2. The Full Text of Modem.java

1: public class Modem {

2:     int speed;

3:

4:     public void displaySpeed() {

5:         System.out.println("Speed: " + speed);

6:     }

7: }

Compile this file with javac or another compiler to produce a file called Modem.class. Although you cannot run this program with the interpreter, you will be able to use it in other classes. You now have a Modem class that can handle one of the things that the CableModem and DslModem classes have in common. By using the extends statement when you are creating the CableModem and DslModem classes, you can make each of them a subclass of Modem.

Start a new file in your word processor and save it as CableModem.java. Enter Listing 10.3 and then save and compile the file.

Listing 10.3. The Full Text of CableModem.java

1: public class CableModem extends Modem {

2:     String method = "cable connection";

3:

4:     public void connect() {

5:         System.out.println("Connecting to the Internet ...");

6:         System.out.println("Using a " + method);

7:     }

8: }

Create a third file with your word processor, and save it as DslModem.java. Enter Listing 10.4 and then save and compile the file when you're done.

Listing 10.4. The Full Text of DslModem.java

1: public class DslModem extends Modem {

2:     String method = "DSL phone connection";

3:

4:     public void connect() {

5:         System.out.println("Connecting to the Internet ...");

6:         System.out.println("Using a " + method);

7:     }

8: }

Once you have compiled all three of these files, you will have three class files: Modem.class, CableModem.class, and DslModem.class. However, you cannot run any of these class files with java or another Java interpreter because they do not have main() blocks. You need to create a short Java program to test out the class hierarchy you have just built.

Return to your word processor and create a new file called TestModems.java. Enter Listing 10.5.

Listing 10.5. The Full Text of TestModems.java

 1: class TestModems {

 2:     public static void main(String[] arguments) {

 3:         CableModem roadRunner = new CableModem();

 4:         DslModem bellSouth = new DslModem();

 5:         roadRunner.speed = 500000;

 6:         bellSouth.speed = 400000;

 7:         System.out.println("Trying the cable modem:");

 8:         roadRunner.displaySpeed();

 9:         roadRunner.connect();

10:         System.out.println("Trying the DSL modem:");

11:         bellSouth.displaySpeed();

12:         bellSouth.connect();

13:     }

14: }

Save and compile the file when you're done. When you run it, the output should resemble the following:

Trying the cable modem:

Speed: 500000

Connecting to the Internet ...

Using a cable connection

Trying the DSL modem:

Speed: 400000

Connecting to the Internet ...

Using a DSL phone connection

The following things are taking place in the program:

  • Lines 3–4: Two new objects are created—a CableModem object called roadRunner, and a DslModem object called bellSouth.

  • Line 5: The speed variable of the CableModem object named roadRunner is set to 500000.

  • Line 6: The speed variable of the DslModem object named bellSouth is set to 400000.

  • Line 8: The displayMethod() method of the roadRunner object is called. This method is inherited from Modem—even though it isn't present in the CableModem class, you can call it.

  • Line 9: The connect() method of the roadRunner object is called.

  • Line 10: The displayMethod() method of the bellSouth object is called.

  • Line 11: The connect() method of the bellSouth object is called.


Summary

After creating your first class of objects and arranging several classes into a hierarchy, you ought to be more comfortable with the term object-oriented programming. You will be learning more about object behavior and attributes in the next two hours as you start creating more sophisticated objects.

Terms such as program, class, and object will make more sense as you become more experienced with this style of development. Object-oriented programming is a concept that takes some time to get used to. Once you have mastered it, you'll find that it's an effective way to design, develop, and debug computer programs.


Q&A

Q1:

Can classes inherit from more than one class?

A1:

It's possible with some programming languages, but not Java. Multiple inheritance is a powerful feature, but it also makes object-oriented programming a bit harder to learn and use. Java's developers decided to limit inheritance to one superclass for any class, although a class can have numerous subclasses. One way to compensate for this limitation is to inherit methods from a special type of class called an interface. You'll learn more about interfaces during Hour 19, "Creating a Threaded Program."

Q2:

Why are object-oriented programs easier to debug?

A2:

Object-oriented programs enable you to focus on a smaller part of a computer program when figuring out where an error is happening. Because a related group of tasks are handled by the same object, you can focus on that object if the tasks aren't being performed correctly. You don't have to worry about any other parts of the program.

Q3:

When would you want to create a class that isn't public?

A3:

The main time you would not want to make a class of objects available to other programs is when the class is strictly for the use of one program you're writing. If you're creating a game program and your RayGunReloader class of objects is highly specific to the game you're writing, it could be a private class. To keep a class from being public, leave off the public statement in front of class.

Q4:

Why does the term "fifth column" refer to traitors, and what are the other four columns?

A4:

The term was coined by Gen. Emilio Mola Vidal during the Spanish Civil War.

As four Nationalist army columns approached Madrid in 1936, Vidal claimed that secret sympathizers within the city would serve as a "fifth column" helping to topple the Republican government.

The term, along with "fifth columnist," now describes anyone working covertly against an existing government from within.


Quiz

The following questions will test your knowledge of objects and the programs that use them.

Questions

1:

What statement is used to enable one class to inherit from another class?

  1. inherits

  2. extends

  3. handitoverandnobodygetshurt

2:

Why are compiled Java programs saved with the .class file extension?

  1. Java's developers think it's a classy language.

  2. It's a subtle tribute to the world's teachers.

  3. Every Java program is a class.

3:

What are the two things that make up an object?

  1. Attributes and behavior

  2. Commands and data files

  3. Spit and vinegar

Answers

A1: | b. The extends statement is used because the subclass is an extension of the attributes and behavior of the superclass and of any superclasses above that in the class hierarchy.
A2: | c. Your programs will always be made up of at least one main class and any other classes that are needed.
A3: | a. In a way, b also is true because commands are comparable to behavior, and data files are analogous to attributes.


Activities

If you don't object, you can extends your knowledge of this hour's topics with the following activities:

  • Create an AcousticModem class with a speed of 300 and its own connect() method.

  • Add a disconnect() method to one of the classes in the Modem project, deciding where it should go to support modem disconnection in cable, DSL, and acoustic modems.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


Hour 11. Describing What Your Object Is Like

As you learned during last hour's introduction to object-oriented programming, an object is a way of organizing a program so that it has everything it needs to accomplish a task. Objects need two things to do their jobs: attributes and behavior.

Attributes are the information stored within an object. They can be variables such as integers, characters, Boolean values, or other objects such as String and Calendar objects. Behavior is the groups of statements used to handle specific jobs within the object. Each of these groups is called a method.

Up to this point, you have been working with the methods and variables of objects without knowing it. Any time your statement had a period in it that wasn't a decimal point or part of a string, chances are an object was involved. You'll see this during this hour as the following topics are covered:

  • Creating variables for an object

  • Creating variables for a class

  • Using methods with objects and classes

  • Calling a method in a statement

  • Returning a value with a method

  • Creating constructor methods

  • Sending arguments to a method

  • Using this to refer to an object

  • Creating new objects

  • Putting one object inside another object


Creating Variables

For the purposes of this hour's examples, you'll be looking at a class of objects called Virus whose sole purpose in life is to reproduce in as many places as possible—much like some of the people I knew in college. A Virus has several different things it needs in order to do its work, and these will be implemented as the behavior of the class. The information that's needed for the methods will be stored as attributes.

Watch Out!

This hour will not teach actual virus writing, though it might provide some insight into how virus programs work as they wreak havoc on the file systems of the computer-loving world. This publisher had scheduled Sams Teach Yourself Virus Programming in a Three-Day Weekend for next spring, but the book has been postponed because the author's hard drive was unexpectedly erased by an email from someone who said "I love you" but had a funny way of showing it.

The attributes of an object represent any variables needed in order for the object to function. These variables could be simple data types such as integers, characters, and floating-point numbers, or they could be arrays or objects of classes such as String or Calendar. An object's variables can be used throughout its program, in any of the methods the object includes. You create variables immediately after the class statement that creates the class and before any methods.

One of the things that a Virus object needs is a way to indicate that a file already has been infected. Some computer viruses change the field that stores the time a file was last modified; for example, a virus might move the time from 13:41:20 to 13:41:61. Because no normal file would be saved on the 61st second of a minute, the time is a sign that the file was infected. The Virus object will use 86 as the seconds field of a file's modification time because "86 it" is slang that means to throw something away—exactly the kind of unpleasant antisocial connotation we're going for. The value will be stored in an integer variable called newSeconds.

The following statements begin a class called Virus with an attribute called newSeconds and two other attributes:

public class Virus {

    public int newSeconds = 86;

    public String author = "Sam Snett";

    int maxFileSize = 30000;

}

All three variables are attributes for the class: newSeconds, maxFileSize, and author.

Putting a statement such as public in a variable declaration is called access control, because it determines how other objects made from other classes can use that variable—or if they can use it at all.

The newSeconds variable has a starting value of 86, and the statement that creates it has public as the first part of the statement. Making a variable public makes it possible to modify the variable from another program that is using the Virus object. If the other program attaches special significance to the number 92, for instance, it can change newSeconds to that value. The following statements create a Virus object called influenza and set its newSeconds variable:

Virus influenza = new Virus();

influenza.newSeconds = 92;

In the Virus class, the author variable also is public, so it can be changed freely from other programs. The other variable, maxFileSize, can only be used within the class itself.

When you make a variable in a class public, the class loses control over how that variable is used by other programs. In many cases, this might not be a problem. For example, the author variable can be changed to any name or pseudonym that identifies the author of the virus, and the only restriction is aesthetic. The name might eventually be used on court documents if you're prosecuted, so you don't want to pick a dumb one. The State of Ohio v. LoveHandles doesn't have the same ring to it as Ohio v. MafiaBoy.

Restricting access to a variable keeps errors from occurring if the variable is set incorrectly by another program. With the Virus class, if newSeconds is set to a value of 60 or less, it won't be reliable as a way to tell that a file is infected. Some files might be saved with that number of seconds regardless of the virus, and they'll look infected to Virus. If the Virus class of objects needs to guard against this problem, you need to do these two things:

  • Switch the variable from public to protected or private, two other statements that provide more restrictive access.

  • Add behavior to change the value of the variable and report the value of the variable to other programs.

A protected variable only can be used in the same class as the variable, any subclasses of that class, or by classes in the same package. A package is a group of related classes that serve a common purpose. An example is the java.util package, which contains classes that offer useful utility functions such as date and time programming and file archiving. When you use the import statement in a Java program with an asterisk, as in import java.util.*, you are making the classes of a package available for use in that program.

A private variable is restricted even further than a protected variable—it only can be used in the same class. Unless you know that a variable can be changed to anything without affecting how its class functions, you probably should make the variable private or protected.

The following statement makes newSeconds a private variable:

private int newSeconds = 86;

If you want other programs to use the newSeconds variable in some way, you'll have to create behavior that makes it possible. This task will be covered later in the hour.

There also is another type of access control: the lack of any public, private, or protected statement when the variable is created.

In the programs you have created prior to this hour, you didn't specify any of these statements. When no access control is specified, the variable is available to be used only by any classes in the same package. This is often called default or package access, although there are no statements used to declare it specifically when creating a variable.


Creating Class Variables

When you create an object, it has its own version of all variables that are part of the object's class. Each object created from the Virus class of objects has its own version of the newSeconds, maxFileSize, and author variables. If you modified one of these variables in an object, it would not affect the same variable in another Virus object.

There are times when an attribute has more to do with an entire class of objects than a specific object itself. For example, if you wanted to keep track of how many Virus objects were being used in a program, it would not make sense to store this value repeatedly in each Virus object. Instead, you can use a class variable to store this kind of information. You can use this kind of variable with any object of a class, but only one copy of the variable exists for the whole class. The variables you have been creating for objects thus far can be called object variables, because they are tied to a specific object. Class variables refer to a class of the objects as a whole.

Both types of variables are created and used in the same way, except that static is used in the statement that creates class variables. The following statement creates a class variable for the Virus example:

static int virusCount = 0;

Changing the value of a class variable is no different than changing an object's variables. If you have a Virus object called tuberculosis, you could change the class variable virusCount with the following statement:

tuberculosis.virusCount++;

Because class variables apply to an entire class instead of a specific object, you can use the name of the class instead:

Virus.virusCount++;

Both statements accomplish the same thing, but there's an advantage to using the name of the class when working with class variables. It shows immediately that virusCount is a class variable instead of an object's variable, because you can't refer to object variables using the name of a class. If you always use object names when working with class variables, you won't be able to tell whether they are class or object variables without looking carefully at the source code of the class.


Creating Behavior with Methods

Attributes are the way to keep track of information about a class of objects, but they don't take any action. For a class to actually do the things it was created to do, you must create behavior. Behavior describes all of the different sections of a class that accomplish specific tasks. Each of these sections is called a method.

You have been using methods throughout your programs up to this point without knowing it, including one in particular: println(). This method displays text onscreen. Like variables, methods are used in connection with an object or a class. The name of the object or class is followed by a period and the name of the method, as in screen2D.drawString() or Integer.parseInt().

By the Way

The System.out.println() method might seem confusing because it has two periods instead of one. This is because two classes are involved in the statement—the System class and the PrintStream class. The System class has a variable called out that is a PrintStream object. println() is a method of the PrintStream class. The System.out.println() statement means, in effect, "Use the println() method of the out variable of the System class." You can chain together references to variables and methods in this way.

Declaring a Method

You create methods with a statement that looks similar to the statement that begins a class. Both can take arguments between parentheses after their names, and both use { and } marks at the beginning and end. The difference is that methods can send back a value after they are handled. The value can be one of the simple types such as integers or Boolean values, or it can be a class of objects. If a method should not return any value, use the statement void.

The following is an example of a method the Virus class can use to infect files:

public boolean infectFile(String filename) {

    boolean success = false;

    // file-infecting statements would be here

    return success;

}

The infectFile() method is used to add a virus to a file. This method takes a single argument, a string variable called filename, and this variable represents the file that should be attacked. The actual code to infect a file is omitted here due to the author's desire to stay on the good side of the U.S. Secret Service. The only thing you need to know is that if the infection is a success, the success variable is set to a value of TRue.

By looking at the statement that begins the method, you can see boolean preceding the name of the method, infectFile. This statement signifies that a boolean value will be sent back after the method is handled. The return statement is what actually sends a value back. In this example, the value of success is returned.

When a method returns a value, you can use the method as part of an assignment statement. For example, if you created a Virus object called malaria, you could use statements such as these:

if (malaria.infectFile(currentFile))

    System.out.println(currentFile + " has been infected!");

else

    System.out.println("Curses! Foiled again!");

Any method that returns a value can be used at any place a value or variable could be used in a program.

Earlier in the hour, you switched the newSeconds variable to private to prevent it from being set by other programs. However, because you're a virus writer who cares about people, you still want to make it possible for newSeconds to be used if it is used correctly. The way to do this is to create public methods in the Virus class that read the value of newSeconds or write a new value to newSeconds. These new methods should be public, unlike the newSeconds variable itself, so they can be called by other programs. The new methods will be able to work with newSeconds because they are in the same class as the variable.

Consider the following two methods:

public int getSeconds() {

    return newSeconds;

}

public void setSeconds(int newValue) {

    if (newValue > 60)

        newSeconds = newValue;

}

The getSeconds() method is used to send back the current value of newSeconds. The getSeconds() method is necessary because other programs can't even look at a private variable such as newSeconds. The getSeconds() method does not have any arguments, but it still must have parentheses after the method name. Other wise, when you were using getSeconds in a program, the method would look no different than a variable.

The setSeconds() method takes one argument, an integer called newValue. This integer contains the value that a program wants to change newSeconds to. If newValue is greater than 60, the change will be made. The setSeconds() method has void preceding the method name, so it does not return any kind of value.

In this example, the Virus class controls how the newSeconds variable can be used by other classes. This process is called encapsulation, and it's a fundamental concept of object-oriented programming. The better your objects are able to protect themselves against misuse, the more useful they will be when you use them in other programs.

Similar Methods with Different Arguments

As you have seen with the setSeconds() method, you can send arguments to a method to affect what it does. Different methods in a class can have different names, but methods can also have the same name if they have different arguments.

Two methods can have the same name if they have a different number of arguments, or the specific arguments are of different variable types. For example, it might be useful for the Virus class of objects to have two tauntUser() methods. One could have no arguments at all and would deliver a generic taunt. The other could specify the taunt as a string argument. The following statements could implement these methods:

void tauntUser() {

    System.out.println("The problem is not with your set, but "

        + "with yourselves.");

}

void tauntUser(String taunt) {

    System.out.println(taunt);

}

Constructor Methods

When you want to create an object in a program, the new statement is used, as in the following example:

Virus typhoid = new Virus();

This statement creates a new Virus object called typhoid. When you use the new statement, a special method of that object's class is called. This method is called a constructor because it handles the work required to create the object. The purpose of a constructor is to set up any variables and other things that need to be established for the object to function properly.

Constructor methods are defined like other methods, except that they cannot return a value as other methods do. The following are two constructor methods for the Virus class of objects:

public Virus() {

    author = "Ignoto";

    maxFileSize = 30000;

}

public Virus(String name, int size) {

    author = name;

    maxFileSize = size;

}

Like other methods, constructors can use the arguments they are sent as a way to define more than one constructor in a class. In this example, the first constructor would be called when a new statement such as the following is used:

Virus mumps = new Virus();

The other constructor could be called only if a string and an integer were sent as arguments with the new statement, as in this example:

Virus rubella = new Virus("April Mayhem", 60000);

If you don't include any constructor methods in a class, it will inherit a single constructor method with no arguments from its superclass. There also might be other constructor methods that it inherits, depending on the superclass used.

In any class, there must be a constructor method that has the same number and type of arguments as the new statement that's used to create objects of that class. In the example of the Virus class, which has Virus() and a Virus(String name, int size) constructors, you only could create Virus objects with two different types of new statements: one without arguments and one with a string and an integer as the only two arguments.

Class Methods

Like class variables, class methods are a way to provide functionality associated with an entire class instead of a specific object. Use a class method when the method does nothing that affects an individual object of the class. One example that you have used in a previous hour was the parseInt() method of the Integer class. This method is used to convert a string to a variable of the type int, as in the following:

int time = Integer.parseInt(timeText);

To make a method into a class method, use static in front of the method name, as in the following:

static void showVirusCount() {

    System.out.println("There are " + virusCount + " viruses.");

}

The virusCount class variable was used earlier to keep track of how many Virus objects have been created by a program. The showVirusCount() method is a class method that displays this total, and it should be called with a statement such as the following:

Virus.showVirusCount();

Variable Scope within Methods

When you create a variable or an object inside a method in one of your classes, it is usable only inside that method. The reason for this is the concept of variable scope. Scope is the section in which a variable exists in a program. If you go outside of the part of the program defined by the scope, you can no longer use the variable.

The { and } statements in a program define the boundaries for a variable. Any variable created within these marks cannot be used outside of them. For example, consider the following statements:

if (numFiles < 1) {

    String warning = "No files remaining.";

}

System.out.println(warning);

This example does not work correctly because the warning variable was created inside the brackets of the if block statement. Those brackets define the scope of the variable. The warning variable does not exist outside of the brackets, so the System.out.println() method cannot use it as an argument.

When you use a set of brackets inside another set of brackets, you'll need to pay attention to the scope of the variables with which you are working. Take a look at the following example:

if (infectedFiles < 5) {

    int status = 1;

    if (infectedFiles < 1) {

        boolean firstVirus = true;

        status = 0;

    } else {

        firstVirus = false;

    }

}

In this example the status variable can be used anywhere, but the firstVirus variable will cause a compiler error. Because firstVirus is created within the scope of the if (infectedFiles < 1) statement, it doesn't exist inside the scope of the else statement that follows.

To fix the problem, firstVirus must be created outside both of these blocks so that its scope includes both of them. One solution would be to create firstVirus at the same time that status is created.

Rules that enforce scope make programs easier to debug because scope limits the area in which a variable can be used. This reduces one of the most common errors that can crop up in many programming languages: the same variable being used two different ways in different parts of a program. By enforcing restrictive rules for a variable's scope, the Java language makes it more difficult to misuse a variable.

The concept of scope applies to methods also, because they are defined by an opening bracket and closing bracket. A variable created inside a method cannot be used in other methods. You can only use a variable in more than one method if it was created as an object variable or class variable after the class statement at the beginning of the program.


Putting One Class inside Another

Although a Java program is sometimes called a class, there are many occasions when a program requires more than one class to get its work done. A multiclass program consists of a main class and any helper classes that are needed. These helper classes earn their name by helping the main class do its work.

An example might be a Java applet that displays a scrolling headline as part of its graphical user interface. The headline could be an independent object in the program, just like other interface elements such as buttons and scroll bars. It makes sense to put the headline into its own class, rather than including its variables and methods in the applet class.

When you divide a program into multiple classes, there are two ways to define the helper classes. One way is to define each class separately, as in the following example:

public class WreakHavoc {

    String author = "Ignoto";

    public void infectFile() {

        VirusCode vic = new VirusCode(1024);

    }

}

class VirusCode {

    int vSize;

    VirusCode(int size) {

        vSize = size;

    }

}

In this example, the VirusCode class is being used as a helper of the WreakHavoc class. Helper classes will often be defined in the same .java source file as the class they're assisting. When the source file is compiled, multiple class files will be produced. The preceding example would produce the files WreakHavoc.class and VirusCode.class.

Watch Out!

If more than one class is defined in the same source file, only one of the classes can be public. The other classes should not have public in their class statements. Also, the name of the source file should match the name of the public class. In the preceding example, the name should be WreakHavoc.java.

When creating a main class and a helper class, you can also put the helper inside the main class. When this is done, the helper class is called an inner class.

An inner class is placed within the opening bracket and closing bracket of another class.

public class WreakMoreHavoc {

    String author = "Ignoto";

    public void infectFile() {

        VirusCode vic = new VirusCode(1024);

    }

    class VirusCode {

        int vSize;

        VirusCode(int size) {

            vSize = size;

        }

    }

}

An inner class can be used in the same manner as any other kind of helper class. The main difference—other than its location—is what happens after the compiler gets through with these classes. Inner classes do not get the name indicated by their class statement. Instead, the compiler gives them a name that includes the name of the main class.

In the preceding example, the compiler produces WreakHavoc.class and WreakHavoc$VirusCode.class.

By the Way

This section illustrates one of the simplest examples of how an inner class can be defined and used. Inner classes are an advanced feature of Java that you won't encounter often as you first learn the language. The functionality they offer can be accomplished by using helper classes defined separately from a main class, and that's the best course to take as you're starting out in programming.


Using the this Keyword

Because you can refer to variables and methods in other classes along with variables and methods in your own classes, the variable you're referring to can become confusing in some circumstances. One way to make things a little more clear is with the this statement. The this statement is a way to refer in a program to the program's own object.

When you are using an object's methods or variables, you put the name of the object in front of the method or variable name, separated by a period. Consider these examples:

Virus chickenpox = new Virus();

chickenpox.name = "LoveHandles";

chickenpox.setSeconds(75);

These statements create a new Virus object called chickenpox, set the name variable of chickenpox, and then call the setSeconds() method of chickenpox.

There are times in a program when you need to refer to the current object—in other words, the object represented by the program itself. For example, inside the Virus class, you might have a method that has its own variable called author:

void public checkAuthor() {

    String author = null;

}

A variable called author exists within the scope of the checkAuthor() method, but it isn't the same variable as an object variable called author. If you wanted to refer to the current object's author variable, you have to use the this statement, as in the following:

System.out.println(this.author);

By using this, you make it clear to which variable or method you are referring. You can use this anywhere in a class that you would refer to an object by name. If you wanted to send the current object as an argument in a method, for example, you could use a statement such as the following:

verifyData(this);

In many cases, the this statement will not be needed to make it clear that you're referring to an object's variables and methods. However, there's no detriment to using this any time you want to be sure you're referring to the right thing.


Workshop: Using Class Methods and Variables

At the insistence of every attorney and management executive in the Pearson family of computer publishers, the workshop for this hour will not be the creation of a working virus program. Instead, you'll create a simple Virus object that can do only one thing: count the number of Virus objects that a program has created and report the total.

Load your word processor and create a new file called Virus.java. Enter Listing 11.1 into the word processor and save the file when you're done.

Listing 11.1. The Full Text of Virus.java

 1: public class Virus {

 2:     static int virusCount = 0;

 3:

 4:     public Virus() {

 5:         virusCount++;

 6:     }

 7:

 8:     static int getVirusCount() {

 9:         return virusCount;

10:     }

11: }

Compile the file and return to your word processor. To test out this new Virus class, you need to create a second class that can create Virus objects.

The VirusLook class is a simple application that creates Virus objects and then counts the number of objects that have been created with the getVirusCount() class method of the Virus class.

Open up a new file with your word processor and enter Listing 11.2. Save the file as VirusLook.java when you're done.

Listing 11.2. The Full Text of VirusLook.java

 1: public class VirusLook {

 2:     public static void main(String[] arguments) {

 3:         int numViruses = Integer.parseInt(arguments[0]);

 4:         if (numViruses > 0) {

 5:             Virus[] virii = new Virus[numViruses];

 6:             for (int i = 0; i < numViruses; i++) {

 7:                 virii[i] = new Virus();

 8:             }

 9:             System.out.println("There are " + Virus.getVirusCount()

10:                 + " viruses.");

11:         }

12:     }

13: }

The VirusLook class is an application that takes one argument when you run it at the command line: the number of Virus objects to create. The following is an example of a command that can be used to run the application:

java VirusLook 200

Arguments are read into an application using a string array that's sent to the main() method. In the VirusLook class, this occurs in Line 2.

To work with an argument as an integer, it must be converted from a String object to an integer. This requires the use of the parseInt() class method of the Integer class. In Line 3, an int variable named numViruses is created from the first argument sent to the program on the command line.

If the numViruses variable is greater than 0, the following things take place in the VirusLook application:

  • Line 5: An array of Virus objects is created with the numViruses variable determining the number of objects in the array.

  • Lines 6–8: A for loop is used to call the constructor method for each Virus object in the array.

  • Lines 9–10: After all of the Virus objects have been constructed, the getVirusCount() class method of the Virus class is used to count the number of its objects that have been created. This should match the argument that was set when the VirusLook application was run.

If the numViruses variable is not greater than 0, nothing happens in the VirusLook application.

After you compile the VirusLook.java file, test it with any command-line argument you would like to try. The number of Virus objects that can be created depends on the memory that's available on your system when you run the VirusLook application. On the author's system, anything above 5.5 million viruses causes the program to crash after displaying an OutOfMemoryError message.

If you don't specify more Virus objects than your system can handle, the output should be something like the following:

There are 5500000 viruses.


Summary

You now have completed two of the three hours devoted to object-oriented concepts in this book. You've learned how to create an object, give behavior and attributes to the object and its class of objects, and convert objects and variables into other forms by using casting.

Thinking in terms of objects is one of the tougher challenges of the Java programming language. Once you start to understand it, however, you realize that the entire language makes use of objects and classes.

During the next hour, you'll learn how to give your objects parents and children.


Q&A

Q1: | Can constructor methods send back a value like other methods?
A1: | No, because there's no way to receive that value. Unlike other methods that can be used as part of an equation, the argument of a method, or other statements, constructors are only handled in response to a new statement. There's no way for that statement to receive a value that would be sent by the method.
Q2: | Do you have to create an object to use class variables or methods?
A2: | Because class variables and methods aren't associated with a specific object, you don't need to create an object solely for the purpose of using them. The use of the Integer.parseInt() method is an example of this because you don't have to create a new Integer object just to convert a string to an int value.
Q3: | Is there a list of all the built-in methods that Java supports?
A3: | Sun offers full documentation for all classes in the Java language, including all public methods you can use. The documentation is in HTML format, so you can browse easily through the classes to see what methods and variables they include. Visit the Java 2, version 5 documentation web page at http://java.sun.com/j2se/1.5/docs/api. During the preparation of this book, I spent enough time at this part of Sun's website to qualify for California residency.
Q4: | When I run the VirusLook application without an argument, the program crashes with an ArrayIndexOutOfBoundsException error. What can I do to correct this?
A4: | This error occurs because of the effort to call the Integer.parseInt() method with a null string as the value of arguments[0]. One solution would be to test the value of arguments[0] with an if statement and call Integer.parseInt() only if arguments[0] is not null. This would require a default value for the numViruses variable. Arguments often require some kind of testing to make sure they have acceptable values before you use them.
Q5: | What's the difference between the Integer object and the int variable type?
A5: | The first is an object, and the second is a simple variable type. Each of the variable types, such as char, int, and float, has a corresponding object. The object is used when you want to make use of an object's methods or treat the variable like an object. Because an Integer object can do things in a program that the int variable type cannot, it is convenient to have both.
Q6: | What is the systematic IUPAC name for a carboxylic acid with a potassium ion in place of the acid hydrogen?
A6: | Potassium octanoate, a corrosive acid for which there is no known practical use. IUPAC, the International Union of Pure and Applied Chemistry, is a scientific council that recommends names for chemicals, atomic weights, and related areas of study. In 1997, the group participated in the decision to name atomic element 106 seaborgium after Berkeley nuclear physicist Glenn Seaborg.


Quiz

The following questions will see whether you have the attributes and behavior to understand object-oriented programming techniques.

Questions

1:

In a Java class, a method is an example of what?

  1. Attributes

  2. Statements

  3. Behavior

2:

If you want to make a variable a class variable, what statement must you use when it is created?

  1. new

  2. public

  3. static

3:

What is the name for the part of a program in which a variable lives?

  1. Its nest

  2. The scope

  3. Variable valley

Answers

A1: | c. A method is made up of statements, but it's an example of behavior.
A2: | c. If the static statement is left off, the variable will be an object variable instead of a class variable.
A3: | b. The compiler fails with an error when a variable is used outside of its scope.


Activities

If all this talk of viruses didn't make you sick, you can increase your knowledge of this hour's topics with the following activity:

  • Add a private variable to the Virus class that stores an integer called newSeconds. Create methods to return the value of newSeconds and change the value of newSeconds only if the new value is between 60 and 100.

  • Write a Java application that takes an argument as a string, converts it to a float variable, converts that to a Float object, and finally turns that into an int variable. Run it a few times with different arguments to see what results.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


Hour 12. Making the Most of Existing Objects

This might be a surprise to you, but your Java objects are ideally suited for childbearing. When you create a program as an object—a set of attributes and behavior—you have designed something that's ready to pass on these qualities to offspring. Like most offspring, these child objects will take on a lot of the attributes and behavior of their parent. They also can do some things differently than their parent does; some extra attributes and behavior can be added that dad is incapable of.

This system is called inheritance, and it's something every superclass (parent) gives to its subclasses (children). Inheritance is one of the most useful aspects of object-oriented programming, and you'll be learning more about it during this hour.

Another useful aspect of object-oriented programming is the capability to create an object that can be used with different programs. Reusability speeds up the software development process and makes it easier to develop error-free, reliable programs. Using Java and special development tools, you can develop JavaBeans—completely reusable Java objects that are easily incorporated into programs.

The following topics will be covered:

  • Designing superclasses and subclasses

  • Forming an inheritance hierarchy

  • Overriding methods

  • Developing JavaBeans


The Power of Inheritance

Without knowing it, you have used inheritance every time you worked with one of the standard Java classes such as String or Math. Java classes are organized into a pyramid-shaped hierarchy of classes in which all classes descend from the Object class.

A class of objects inherits from all superclasses that are above it. To get a working idea of how this operates, you'll look at the JApplet class. This class is a superclass of all Swing applets, Java programs written to run on the World Wide Web. The JApplet class, which is used to create Java 2 applets, is a subclass of Applet.

A partial family tree of JApplet is shown in Figure 12.1. Each of the boxes is a class, and the lines connect a superclass to any subclasses below it.

Figure 12.1. The family tree of the Applet class.

At the top is the Object class. JApplet has five superclasses above it in the hier archy: Applet, Panel, Container, Component, and Object. The JApplet class in herits attributes and behavior from each of these classes because each is directly above it in the hierarchy of superclasses. JApplet does not inherit anything from the five shaded classes in Figure 12.1, which include Dialog and Frame, because they are not above it in the hierarchy.

If this seems confusing, think of the hierarchy as a family tree. JApplet will inherit from its parent, the parent's parent, and on upward. It even might inherit some things from its great-great-grandparent, Object. The JApplet class won't inherit from its siblings or its cousins, however.

Setting up a complicated hierarchy of classes is a difficult thing, but it makes it easier to create new programs later. The amount of work necessary to write a new class of objects is reduced. Creating a new class boils down to the following task: You only have to define the ways in which it is different from an existing class. The rest of the work is done for you.

As an example, consider the popular video game Tetris. Since the game was invented by Soviet mathematician Alexey Pajitnov, it has been adapted for dozens of different operating systems and programming languages—including several different Java versions. In case you somehow avoided Tetris during the past decade by lapsing into a coma or falling into a deep meditative trance, the game works as follows: Blocks of different shapes fall from the top of the screen, and you must organize them into unbroken horizontal lines before they stack up too high.

The Java source file for several adaptations of Tetris is available for your use. If you wanted to create a new version of Tetris based on one of these existing classes, you could make your game a subclass of an existing Tetris game. All you would have to do is create the things that are new or different about your version, and you would end up with a new game.

Inheriting Behavior and Attributes

The behavior and attributes of a class are a combination of two things: its own behavior and attributes, and all the behavior and attributes it inherits from its superclasses.

The following are some of the behavior and attributes of Applet:

  • The equals() method determines whether a JApplet object has the same value as another object.

  • The setBackground() method sets the background color displayed on the applet window.

  • The add() method adds user interface components such as buttons and text fields to the applet.

  • The setLayout() method defines how the applet's graphical user interface will be organized.

The JApplet class can use all of these methods, even though setLayout() is the only one it didn't inherit from another class. The equals() method is defined in Object, setBackground() comes from Component, and add() comes from Container.

Overriding Methods

Some of the methods defined in the JApplet class of objects also were defined in one of its superclasses. As an example, the update() method is set up in both the JApplet class and the Component class. This method was originally used in Java 1.0 to control whether the applet window is cleared out before anything is drawn in it. In Java 2, the JApplet class has its own update() method that never clears the applet window. When a method is defined in a subclass and its superclass, the subclass method is used. This enables a subclass to change, replace, or completely wipe out some of the behavior or attributes of its superclasses. In the case of update(), the purpose was to wipe out some behavior present in a superclass.

Creating a new method in a subclass to change behavior inherited from a superclass is called overriding the method. You need to override a method any time the inherited behavior will produce an undesired result.


Establishing Inheritance

You establish a class as the subclass of another class with the extends statement, as in the following:

class AnimatedLogo extends javax.swing.JApplet {

    // behavior and attributes go here

}

The extends statement establishes the AnimatedLogo class of objects as a subclass of JApplet, using the full class name of javax.swing.JApplet. As you will see during Hour 17, "Creating Interactive Web Programs," all Swing applets must be subclasses of JApplet. They need the functionality this class provides to run when presented on a web page.

One method that AnimatedLogo will have to override is the paint() method, which is used to draw all things that are shown on the program's window. The paint() method is implemented by the Component class and is passed all the way down to AnimatedLogo. However, the paint() method does not do anything. It exists so that subclasses of Component have a method they can use when something must be displayed when that subclass is running.

To override a method, you must start the method in the same way it started in the superclass from which it was inherited. A public method must remain public, the value sent back by the method must be the same, and the number and type of arguments to the method must not change.

The paint() method of the Component class begins as follows:

public void paint(Graphics g) {

When AnimatedLogo overrides this method, it must begin with a statement like this:

public void paint(Graphics screen) {

The only difference is in the name of the Graphics object, which does not matter when determining whether the methods are created in the same way. These two statements match because the following things match:

  • Both paint() methods are public.

  • Both methods return no value, as declared by the use of the void statement.

  • Both have a Graphics object as their only argument.

Using this and super in a Subclass

Two keywords that are extremely useful in a subclass are this and super.

As you learned during the previous hour, the this keyword is used to refer to the current object. When you're creating a class and you need to refer to the specific object created from that class, this can be used, as in the following statement:

this.title = "Cagney";

This statement sets the object's title variable to the text "Cagney."

The super keyword serves a similar purpose: It refers to the immediate superclass of the object. super can be used in several different ways:

  • To refer to a constructor method of the superclass, as in super("Adam", 12)

  • To refer to a variable of the superclass, as in super.hawaii = 50

  • To refer to a method of the superclass, as in super.dragNet()

One of the ways you'll use the super keyword is in the constructor method of a subclass. Because a subclass inherits all the behavior and attributes of its superclass, you have to associate each constructor method of that subclass with a constructor method of its superclass. Otherwise, some of the behavior and attributes might not be set up correctly, and the subclass won't be able to function properly.

To make sure that this happens, the first statement of a subclass constructor method must be a call to a constructor method of the superclass. This requires the super keyword, as in the following statements:

public ReadFiles(String name, int length) {

    super(name, length);

}

This example is the constructor method of a subclass, and it uses super(name, length) to call a comparable constructor in its superclass.

Did you Know?

If you don't use super to call a constructor method in the superclass, the program still might compile and run successfully. If no superclass constructor is called, Java automatically calls one with no arguments when the subclass constructor begins. If this superclass constructor doesn't exist or provides unexpected behavior, errors will result, so it's much better to call a superclass constructor yourself.


Working with Existing Objects

One of the things you have learned about object-oriented programming is how it encourages reuse. If you develop an object for use with one Java programming project, it should be possible to incorporate that object into another project without modification.

If a Java class is well-designed, it's possible to make that class available for use in other programs. As long as the class is documented thoroughly, a programmer should be able to work with that class as if it were part of the official Java language itself.

This is an idea that has great potential for software developers. The more objects available for use in your programs, the less work you have to do when creating your own software. If there's an excellent spell-checking object that suits your needs, you can use it instead of writing your own. Ideally, you can even give your boss a false impression about how long it took to add spell-checking functionality to your project, and use this extra time to make personal long-distance calls from the office.

By the Way

The author of this book, like many in his profession, is self-employed and works out of his home. Please keep this in mind when evaluating his advice on how to conduct yourself in the workplace.

When Java was first introduced, the system of sharing objects was largely an informal one. Programmers developed their objects to be as independent as possible and protected them against misuse through the use of private variables and public methods to read and write those variables.

Sharing objects becomes more powerful when there's a standard for developing reusable objects. The benefits of a standard include the following:

  • There's less need to document how an object works, because anyone who knows the standard already knows a lot about how it functions.

  • Development tools can be designed that follow the standard, making it possible to work more easily with these objects.

  • Two objects that follow the standard will be able to interact with each other without special programming to make them compatible.


Storing Objects of the Same Class in Vectors

An important decision to make when writing a computer program is where to store data. In the first half of this book, you've found three useful places to keep information: basic data types like int and char, arrays, and String objects.

Any Java class can hold data. One of the most useful is Vector, a data structure that holds objects of the same class.

Vectors are like arrays, which also hold elements of related data, but they can grow or shrink in size at any time.

The Vector class belongs to the java.util package of classes, one of the most useful in the Java 2 class library. An import statement makes it available in your program:

import java.util.Vector;

A vector holds objects that either belong to the same class or share the same superclass. They are created by referencing two classes—the Vector class and the class the vector will hold.

The name of the class held by the vector is placed within "<" and ">" characters, as in this statement:

Vector<String> victor = new Vector<String>();

The preceding statement creates a vector that will hold strings. Identifying a vector's class in this manner utilizes generics, an enhancement of Java 2 version 5. If you were using vectors with an older version of Java, you would write a constructor like this:

Vector victor = new Vector();

Although you can still do this, generics make your code more reliable because they give the compiler a way to prevent you from misusing a vector. If you attempted to put an Integer object in a vector that's supposed to hold String objects, the compiler fails with an error.

Unlike arrays, vectors aren't created with a fixed number of elements they hold. The vector will be created with 10 elements. If you know you're storing a lot more objects than that, a size can be specified as an argument to the constructor. Here's a statement that creates a 300-element vector:

Vector<String> victoria = new Vector<String>(300);

An object can be added to a vector by calling its add() method, using the object as the only argument:

victoria.add("Vance");

victoria.add("Vernon");

victoria.add("Velma");

Objects are added in order, so if these were the first three objects added to victoria, element 0 is "Vance", element 1 is "Vernon", and element 2 is "Velma".

Elements are retrieved from vectors by calling their get() method with the element's index number as the argument:

String name = victoria.get(1);

This statement stores "Vernon" in the name string.

To see whether a vector contains an object in one of its elements, call its contains() method with that object as argument:

if (victoria.contains("Velma")) {

    System.out.println("Velma found");

}

An object can be removed from a vector using itself or an index number:

victoria.remove(0);

victoria.remove("Vernon");

These two statements leave "Velma" as the only string in the vector.

Looping Through a Vector

Java 2 version 5 introduces a new for loop that makes it easy to load a vector and examine each of its elements in turn.

This loop has two parts, one less than the for loops you learned about in Hour 8, "Repeating an Action with Loops."

The first part is the initialization section: the class and name of a variable that holds each object retrieved from the vector. This object should belong to the same class that holds the vector.

The second part identifies the vector.

Here's code that loops through the victoria vector, displaying each name to the screen:

for (String name : victoria) {

    System.out.println(name);

}

Watch Out!

As a new feature of Java 2 version 5, this for loop won't work in previous versions of the language. You'll encounter an error if you attempt to compile the code examples from this section with a development tool that isn't current.

The hour's next project takes vectors and the new for loop for a spin, presenting a list of strings in alphabetical order. The list comes from an array and command-line arguments.

Enter the text of Listing 12.1 into your text editor, saving the file as StringLister.java.

Listing 12.1. The Full Text of StringLister.java

 1: import java.util.*;

 2:

 3: public class StringLister {

 4:     String[] names = { "Spanky", "Alfalfa", "Buckwheat", "Daria",

 5:         "Stymie", "Marianne", "Scotty", "Tommy", "Chubby" };

 6:

 7:     public StringLister(String[] moreNames) {

 8:         Vector<String> list = new Vector<String>();

 9:         for (int i = 0; i < names.length; i++) {

10:             list.add(names[i]);

11:         }

12:         for (int i = 0; i < moreNames.length; i++) {

13:             list.add(moreNames[i]);

14:         }

15:         Collections.sort(list);

16:         for (String name : list) {

17:             System.out.println(name);

18:         }

19:     }

20:

21:     public static void main(String[] arguments) {

22:         StringLister lister = new StringLister(arguments);

23:     }

24: }

Compile the StringLister application, a program that displays strings in alphabetical order.

When you run the application, specify one or more names as command-line arguments, as in this command:

java StringLister Jackie Mickey Farina Woim

The names specified at the command line are added to the names stored in an array in Lines 4–5. Because the total number of names is not known until the program runs, a vector serves as a better storage place for these strings than an array.

The vector's strings are sorted in alphabetical order using a method of the Collections class:

Collections.sort(list);

This class, like Vector, belongs to the java.util package. Vectors and other useful data structures are called collections in Java.

Example output for the StringLister application follows:

Alfalfa

Buckwheat

Chubby

Daria

Farina

Jackie

Marianne

Mickey

Scotty

Spanky

Stymie

Tommy

Woim


Workshop: Creating a Subclass

To see an example of inheritance at work, you will create a class called Point3D that represents a point in three-dimensional space. A two-dimensional point can be expressed with an (x,y) coordinate. Applets use an (x,y) coordinate system to determine where text and graphics should be displayed. Three-dimensional space adds a third coordinate, which can be called z.

The Point3D class of objects should do three things:

  • Keep track of an object's (x,y,z) coordinate.

  • Move an object to a new (x,y,z) coordinate when needed.

  • Move an object by a certain amount of x, y, and z values as needed.

Java already has a standard class that represents two-dimensional points; it's called Point. It has two integer variables called x and y that store a Point object's (x,y) location. It also has a move() method to place a point at the specified location, and a translate() method to move an object by an amount of x and y values.

Run your word processor and create a new file called Point3D.java. Enter the text of Listing 12.2 into the file, and save it when you're done.

Listing 12.2. The Full Text of Point3D.java

 1: import java.awt.*;

 2:

 3: public class Point3D extends Point {

 4:     public int z;

 5:

 6:     public Point3D(int x, int y, int z) {

 7:         super(x,y);

 8:         this.z = z;

 9:     }

10:

11:     public void move(int x, int y, int z) {

12:         this.z = z;

13:         super.move(x, y);

14:     }

15:

16:     public void translate(int x, int y, int z) {

17:         this.z += z;

18:         super.translate(x, y);

19:     }

20: }

After you compile this file with a Java compiler such as javac, you will have a class you can use in programs. The Point3D class does not have a main() block statement, so you cannot run it with the java interpreter.

The Point3D class only has to do work that isn't being done by its superclass, Point. This primarily involves keeping track of the integer variable z, and receiving it as an argument to the move() method, translate() method, and Point3D() constructor method.

All of the methods use the keywords super and this. The this statement is used to refer to the current Point3D object, so this.z = z; in Line 8 sets the object variable z equal to the z value that was sent as an argument to the method in Line 6.

The super statement refers to the superclass of the current object, Point. It is used to set variables and call methods that were inherited by Point3D. The statement super(x,y) in Line 7 calls the Point(x,y) constructor in the superclass, which then sets the (x,y) coordinates of the Point3D object. Because Point already is equipped to handle the x and y axes, it would be redundant for the Point3D class of objects to do the same thing.

To test out the Point3D class you have compiled, create a program that uses Point and Point3D objects and moves them around. Create a new file in your word processor and enter Listing 12.3 into it. Save the file as TRyPoints.java.

Listing 12.3. The Full Text of tryPoints.java

 1: import java.awt.*;

 2:

 3: class TryPoints {

 4:     public static void main(String[] arguments) {

 5:         Point object1 = new Point(11,22);

 6:         Point3D object2 = new Point3D(7,6,64);

 7:

 8:         System.out.println("The 2D point is located at (" + object1.x

 9:             + ", " + object1.y + ")");

10:         System.out.println("\tIt's being moved to (4, 13)");

11:         object1.move(4,13);

12:         System.out.println("The 2D point is now at (" + object1.x

13:             + ", " + object1.y + ")");

14:         System.out.println("\tIt's being moved -10 units on both the x "

15:             + "and y axes");

16:         object1.translate(-10,-10);

17:         System.out.println("The 2D point ends up at (" + object1.x

18:             + ", " + object1.y + ")\n");

19:

20:         System.out.println("The 3D point is located at (" + object2.x

21:             + ", " + object2.y + ", " + object2.z +")");

22:         System.out.println("\tIt's being moved to (10, 22, 71)");

23:         object2.move(10,22,71);

24:         System.out.println("The 3D point is now at (" + object2.x

25:             + ", " + object2.y + ", " + object2.z +")");

26:         System.out.println("\tIt's being moved -20 units on the x, y "

27:             + "and z axes");

28:         object2.translate(-20,-20,-20);

29:         System.out.println("The 3D point ends up at (" + object2.x

30:             + ", " + object2.y + ", " + object2.z +")");

31:     }

32: }

After you compile this file and run it with a Java interpreter, the following output should be displayed:

The 2D point is located at (11, 22)

    It's being moved to (4, 13)

The 2D point is now at (4, 13)

    It's being moved -10 units on both the x and y axes

The 2D point ends up at (-6, 3)

The 3D point is located at (7, 6, 64)

    It's being moved to (10, 22, 71)

The 3D point is now at (10, 22, 71)

    It's being moved -20 units on the x, y and z axes

The 3D point ends up at (-10, 2, 51)


Summary

When people talk about the miracle of birth, they're probably not speaking of the way a superclass can give birth to subclasses or the way behavior and attributes are inherited in a hierarchy of classes.

If the real world worked the same way that object-oriented programming does, every grandchild of Mozart could choose to be a brilliant composer. All descendants of Mark Twain could wax poetic about Mississippi riverboat life. Every skill your ancestors worked to achieve would be handed to you without an ounce of toil.

On the scale of miracles, inheritance isn't quite up to par with continuing the existence of a species or getting a good tax break. However, it's an effective way to design software with a minimum of redundant work.


Q&A

Q1:

Can a class have more than one superclass so that it inherits additional methods and behavior?

A1:

It is possible with some object-oriented programming languages, but not Java. One of the goals when Java was developed was to provide a simpler language than an object-oriented language such as C++, and limiting inheritance to a single superclass was one way to achieve this. You can use a special type of class called an interface to inherit behavior that isn't received from superclasses.

Q2:

Most Java programs created up to this point have not used extends to inherit from a superclass. Does this mean they exist outside of the class hierarchy?

A2:

All classes you create in Java are part of the hierarchy because the default superclass for the programs you write is Object when the extends keyword is not used. The equals() and toString() methods of all classes are part of the behavior that automatically is inherited from Object.

Q3:

When is the full name of a class, such as java.applet.Applet, needed in an extends clause instead of a shorter name such as Applet?

A3:

You must use the full name whenever you don't use an import javax.swing.JApplet; or import.javax.swing.*; statement at the beginning of your program. The import statement is used solely to make it easier to refer to class names in programs. Each class of objects in Java has a full name that identifies the group of classes to which it belongs. For instance, the Math class is part of the java.lang group of classes. A group of classes is also called a package.

Q4:

Is there any difference between sea salt and table salt?

A4:

Sea salt, table salt, and a third kind—kosher salt—are chemically identical but produced by different means.

Sea salt is reclaimed from large quantities of salt water. Table salt and kosher salt are collected from salt deposits, and the main difference between the two is that kosher salt is raked continuously during the evaporation process.

The choice of salt is largely a personal preference, because the three different production methods result in largely the same product. Some health advocates believe that sea salt contains more trace minerals than the other kinds.


Quiz

To determine what kind of knowledge you inherited from the past hour's work, answer the following questions.

Questions

1:

If a superclass handles a method in a way you don't want to use in the subclass, what can you do?

  1. Delete the method in the superclass.

  2. Override the method in the subclass.

  3. Write a nasty letter to the editor of the San Jose Mercury News hoping that Java's developers will read it.

2:

What methods can be used to retrieve an element stored in a vector?

  1. get()

  2. read()

  3. elementAt()

3:

What statement can you use to refer to the methods and variables of the current object?

  1. this

  2. that

  3. theOther

Answers

A1: | b. Because you can override the method, you don't have to change any aspect of the superclass or the way it works.
A2: | a. The get() method has one argument, the index number of the element.
A3: | a. The this keyword refers to the object in which it appears.


Activities

If a fertile imagination has birthed in you a desire to learn more, you can spawn more knowledge of inheritance with the following activities:

  • Create a Point4D class that adds a t coordinate to the (x,y,z) coordinate system created by the Point3D class. The t coordinate stands for time, so you will need to ensure that it is never set to a negative value.

  • Use the members of a football team's offense—lineman, wide receiver, tight end, running back, and quarterback, and design a hierarchy of classes that represent the skills of these players, putting common skills higher up in the hierarchy. For example, blocking is behavior that should probably be in herited by the linemen and tight end classes, and speed is something that should be inherited by wide receivers and running backs.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


    Part IV: Programming a Graphical User Interface

    HOUR 13 Building a Simple User Interface

    HOUR 14 Laying Out a User Interface

    HOUR 15 Responding to User Input

    HOUR 16 Building a Complex User Interface


Hour 13. Building a Simple User Interface

Because of the popularity of Microsoft Windows and Apple Macintosh systems, computer users have come to expect certain things from their software. It should feature a graphical user interface, take user input from a mouse, and work like other programs.

These expectations are a far cry from the heyday of MS-DOS and other command-line systems, when the user interface varied greatly with each program you used, and point-and-click was something photographers did.

Programs that use a graphical user interface and mouse control are called windowing software. Although you probably have been using a command-line interface to write Java programs, during this hour you create windowing programs using a group of classes called Swing.

The following topics will be covered:

  • Using user interface components such as buttons

  • Using labels, text fields, and other components

  • Grouping components together

  • Putting components inside other components

  • Opening and closing windows

  • Testing an interface


Swing and the Abstract Windowing Toolkit

Because Java is a cross-platform language that enables you to write programs for many different operating systems, its windowing software must be flexible. Instead of catering only to the Microsoft Windows-style of windowing or the Apple Macintosh version, it must handle both along with other platforms.

With Java, the development of a program's user interface is based on two sets of classes: the Abstract Windowing Toolkit and Swing. These classes enable you to create a graphical user interface and receive input from the user.

Swing and the Abstract Windowing Toolkit include everything you need to write programs that use a graphical user interface, which is also called a GUI (pronounced gooey, as in Huey, Dewey, and Louie). With Java's windowing classes, you can create a GUI that includes all of the following and more:

  • Buttons, check boxes, labels, and other simple components

  • Text fields, sliders, and other more complex components

  • Pull-down menus and pop-up menus

  • Windows, frames, dialog boxes, and applet windows

During this hour and the next, you will create and organize graphical user interfaces in Java. Afterwards in Hour 15, "Responding to User Input," you will enable those interfaces to receive mouse clicks and other user input.


Using Components

In Java, every part of a graphical user interface is represented by a class in the Swing or Abstract Windowing Toolkit packages. There is a JButton class for buttons, a JWindow class for windows, a JTextField class for text fields, and so on.

To create and display an interface, you create objects, set their variables, and call their methods. The techniques are the same as those you used during the previous three hours as you were introduced to object-oriented programming.

When you are putting a graphical user interface together, you work with two kinds of objects: components and containers. A component is an individual element in a user interface, such as a button or slider. A container is a component that can be used to hold other components.

The first step in creating an interface is to create a container that can hold components. In an application, this container is often a frame or a window. You will use another, the applet window, in Hour 17, "Creating Interactive Web Programs."

Frames and Windows

Windows and frames are containers that can be displayed on a user's desktop. Windows are simple containers that do not have a title bar or any of the other buttons normally along the top edge of a graphical user interface. Frames are windows that include all of these common windowing features users expect to find when they run software—such as buttons to close, expand, and shrink the window.

These containers are created using Swing's JWindow and JFrame classes. To make the Swing package of classes available in a Java program, use the following statement:

import javax.swing.*;

One way to make use of a frame in a Java application is to make the application a subclass of JFrame. Your program will inherit the behavior it needs to function as a frame. The following statements create a subclass of JFrame:

import javax.swing.*;

public class MainFrame extends JFrame {

    public MainFrame() {

        // set up the frame

    }

}

This class creates a frame, but doesn't set it up completely. In the frame's constructor method, you must do several actions when creating a frame:

  • Call a constructor method of the superclass, JFrame.

  • Set up the title of the frame.

  • Set up the size of the frame.

  • Define what happens when the frame is closed by a user.

You also must make the frame visible, unless for some reason it should not be displayed when the application begins running.

All of these things can be handled in the frame's constructor method. The first thing the method must contain is a call to one of the constructor methods of JFrame, using the super statement. Here's an example:

super();

The preceding statement calls the JFrame constructor with no arguments. You also can call it with the title of your frame as an argument:

super("Main Frame");

This sets the title of the frame, which appears in the title bar along the top edge, to the specified string. In this example, the text greeting "Main Frame" will appear.

If you don't set up a title in this way, you can call the frame's setTitle() method with a String as an argument:

setTitle("Main Frame");

The size of the frame can be established by calling its setSize() method with two arguments: the width and height. The following statement sets up a frame that is 350 pixels wide and 125 pixels tall:

setSize(350, 125);

Another way to set the size of a frame is to fill it with components and then call the frame's pack() method with no arguments, as in this example:

pack();

The pack() method sets the frame up based on the preferred size of each component inside the frame. Every interface component has a preferred size, though this is sometimes disregarded, depending on how components have been arranged within a container. You don't need to explicitly set the size of a frame before calling pack()—the method sets it to an adequate size before the frame is displayed.

Every frame is displayed with a button along the title bar that can be used to close the frame. On a Windows system, this button appears as an X in the upper-right corner of the frame. To define what happens when this button is clicked, call the frame's setDefaultCloseOperation() method with one of four JFrame class variables as an argument:

  • setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)— Exit the program when the button is clicked.

  • setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)— Close the frame, dispose of the frame object, and keep running the application.

  • setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)— Keep the frame open and continue running.

  • setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)— Close the frame and continue running.

The last thing that's required is to make the frame visible: call its setVisible() method with true as an argument:

setVisible(true);

This opens the frame at the defined width and height. You also can call it with false to stop displaying a frame.

Listing 13.1 contains the source code described in this section. Enter these statements and save the file as SalutonFrame.java.

Listing 13.1. The Full Text of SalutonFrame.java

 1: import javax.swing.*;

 2:

 3: public class SalutonFrame extends JFrame {

 4:     public SalutonFrame() {

 5:         super("Saluton mondo!");

 6:         setSize(350, 100);

 7:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 8:         setVisible(true);

 9:     }

10:

11:     public static void main(String[] arguments) {

12:         SalutonFrame sal = new SalutonFrame();

13:     }

14: }

Lines 11–13 of Listing 13.1 contain a main() method, which turns this frame class into an application that can be run at the command line. After you compiling this into a class, run the application with the following command:

java SalutonFrame

Figure 13.1 shows the result.

Figure 13.1. Displaying a frame in an application.

The only thing that SalutonFrame displays is a title—the Esperanto greeting "Saluton mondo!" The frame is an empty window, because it doesn't contain any other components yet.

To add components to a frame, window, or an applet, you must create the component and add it to the container. Each container has an add() method that takes one argument: the component to display.

Buttons

One simple component you can add to a container is a JButton object. JButton, like the other components you'll be working with during this hour, is part of the java.awt.swing package. A JButton object is a clickable button with a label that describes what clicking the button will do. This label can be text, graphics, or both. The following statement creates a JButton called okButton and gives it the text label OK:

JButton okButton = new JButton("OK");

After a component such as JButton is created, it should be added to a container by calling its add() method:

add(okButton);

When you add components to a container, you do not specify the place in the container where the component should be displayed. The arrangement of components is decided by an object called a layout manager. The simplest of these managers is the FlowLayout class, which is part of the java.awt package.

To make a container use a specific layout manager, you must first create an object of that layout manager's class. A FlowLayout object is created with a statement, such as the following:

FlowLayout fff = new FlowLayout();

Once a layout manager has been created, the container's setLayout() method is called to associate the manager with the container. The only argument to this method should be the layout manager object, as in the following example:

pane.setLayout(fff);

This statement designates the fff object as the layout manager for the pane container.

Listing 13.2 contains a Java application that displays a frame with three buttons.

Listing 13.2. The Full Text of Playback.java

 1: import javax.swing.*;

 2: import java.awt.*;

 3:

 4: public class Playback extends JFrame {

 5:     public Playback() {

 6:         super("Playback");

 7:         setSize(225, 80);

 8:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 9:         setVisible(true);

10:         FlowLayout flo = new FlowLayout();

11:         setLayout(flo);

12:         JButton play = new JButton("Play");

13:         JButton stop = new JButton("Stop");

14:         JButton pause = new JButton("Pause");

15:         add(play);

16:         add(stop);

17:         add(pause);

18:         setVisible(true);

19:     }

20:

21:     public static void main(String[] arguments) {

22:         Playback pb = new Playback();

23:     }

When you run this application at a command line, your output should resemble Figure 13.2. You can click each of the buttons, but nothing happens in response because your program does not contain any methods to receive user input—that's covered during Hour 15.

Figure 13.2. Displaying buttons on a graphical user interface.

Many of the user components available as part of Swing can be added to a container in this manner.

By the Way

Because so many different user interface components must be introduced during this hour, the full source code used to create each figure is not listed here. You can find full versions of each program on the book's website at http://www.java24hours.com on the Hour 13 page.

Labels and Text Fields

A JLabel component displays information that cannot be modified by the user. This information can be text, a graphic, or both. These components are often used to label other components in an interface, hence the name. They often are used to identify text fields.

A JTextField component is an area where a user can enter a single line of text. You can set up the width of the box when you create the text field.

The following statements create a JLabel component and JTextField object and add them to a container:

JLabel pageLabel = new JLabel("Web page address: ", JLabel.RIGHT);

JTextField pageAddress = new JTextField(20);

FlowLayout flo = new FlowLayout();

setLayout(flo);

add(pageLabel);

add(pageAddress);

Figure 13.3 shows this label and text field side-by-side. Both of the statements in this example use an argument to configure how the component should look.

Figure 13.3. Displaying labels and text fields.

The pageLabel label is set up with the text Web page address: and a JLabel.RIGHT argument. This last value indicates that the label should appear flush right. JLabel.LEFT aligns the label text flush left, and JLabel.CENTER centers it. The argument used with JTextField indicates that the text field should be approximately 20 characters wide. You also can specify default text that will appear in the text field with a statement such as the following:

JTextField country = new JTextField("US", 29);

This statement would create a JTextField object that is 20 characters wide and has the text US in the field.

The text contained within the object can be retrieved with the getText() method, which returns a string:

String countryChoice = country.getText();

As you might have guessed, you also can set the text with a corresponding method:

countryChoice.setText("Socialist People's Libyan Arab Jamahiriya");

This sets the text to the official name of Libya, which is the longest in the world, edging out the second-place finisher: the United Kingdom of Great Britain and Northern Ireland.

Check Boxes

A JCheckBox component is a box next to a line of text that can be checked or unchecked by the user. The following statements create a JCheckBox object and add it to a container:

JCheckBox jumboSize = new JCheckBox("Jumbo Size");

FlowLayout flo = new FlowLayout();

setLayout(flo);

add(jumboSize);

The argument to the JCheckBox() constructor method indicates the text to be displayed alongside the box. If you wanted the box to be checked, you could use the following statement instead:

JCheckBox jumboSize = new JCheckBox("Jumbo Size", true);

A JCheckBox can be presented singly or as part of a group. In a group of check boxes, only one can be checked at a time. To make a JCheckBox object part of a group, you have to create a ButtonGroup object. Consider the following:

JCheckBox frogLegs = new JCheckBox("Frog Leg Grande", true);

JCheckBox fishTacos = new JCheckBox("Fish Taco Platter", false);

JCheckBox emuNuggets = new JCheckBox("Emu Nuggets", false);

FlowLayout flo = new FlowLayout();

ButtonGroup meals = new ButtonGroup();

meals.add(frogLegs);

meals.add(fishTacos);

meals.add(emuNuggets);

setLayout(flo);

add(jumboSize);

add(frogLegs);

add(fishTacos);

add(emuNuggets);

This creates three check boxes that are all grouped under the ButtonGroup object called meals. The Frog Leg Grande box is checked initially, but if the user checked one of the other meal boxes, the check next to Frog Leg Grande would disappear automatically. Figure 13.4 shows the different check boxes from this section.

Figure 13.4. Displaying check box components.

Combo Boxes

A JComboBox component is a pop-up list of choices that also can be set up to receive text input. When both options are enabled, you can select an item with your mouse or use the keyboard to enter text instead. The combo box serves a similar purpose to a group of check boxes, except that only one of the choices is visible unless the pop-up list is being displayed.

To create a JComboBox object, you have to add each of the choices after creating the object, as in the following example:

JComboBox profession = new JComboBox();

FlowLayout flo = new FlowLayout();

profession.addItem("Butcher");

profession.addItem("Baker");

profession.addItem("Candlestick maker");

profession.addItem("Fletcher");

profession.addItem("Fighter");

profession.addItem("Technical writer");

setLayout(flo);

add(profession);

This example creates a single JComboBox component that provides six choices from which the user can select. When one is selected, it appears in the display of the component. Figure 13.5 shows this example while the pop-up list of choices is being displayed.

Figure 13.5. Displaying combo box components.

To enable a JComboBox component to receive text input, its setEditable() method must be called with an argument of TRue, as in the following statement:

profession.setEditable(true);

This method must be called before the component is added to a container.

Text Areas

A JTextArea component is a text field that enables the user to enter more than one line of text. You can specify the width and height of the component. For example, the following statements create a JTextArea component with an approximate width of 40 characters and a height of 8 lines, and then add the component to a container:

JTextArea comments = new JTextArea(8, 40);

FlowLayout flo = new FlowLayout();

setLayout(flo);

add(comments);

Figure 13.6 shows this example in a frame.

Figure 13.6. Displaying text area components.

You can specify a string in the JTextArea() constructor method to be displayed in the text area. You can use the newline character ("\n") to send text to the next line, as in the following:

JTextArea desire = new JTextArea("I should have been a pair\n"

    + "of ragged claws.", 10, 25);

Watch Out!

Text area components behave in ways you might not expect—they expand in size when the user reaches the bottom of the area, and do not include scrollbars along the right edge or bottom edge. To implement the kind of text areas you see in other windowing software, you must place the area inside a container called a scroll pane, as you will see in Hour 16, "Building a Complex User Interface."

Panels

The last of the components you'll learn to create during this hour are panels, which are created in Swing using the JPanel class. JPanel objects are the simplest kind of container you can use in a Swing interface. The purpose of JPanel objects is to subdivide a display area into different groups of components. When the display is divided into sections, you can use different rules for how each section is organized.

You can create a JPanel object and add it to a container with the following statements:

JPanel topRow = new JPanel();

FlowLayout flo = new FlowLayout();

setLayout(flo);

add(topRow);

Panels are often used when arranging the components in an interface, as you'll see in Hour 14, "Laying Out a User Interface."

Unlike other containers, panels do not have a content pane. Instead, you can add components by calling the panel's add() method directly. You also can assign a layout manager directly to the panel by calling its setLayout() method.

Panels also can be used when you need an area in an interface to draw something, such as an image from a graphics file.

Another convenient use of JPanel is to create your own components that can be added to other classes. This is demonstrated in this hour's workshop.


Workshop: Creating Your Own Component

As you may recall, one of the main advantages of object-oriented programming is the capability to reuse classes in different projects. For this hour's workshop, you will create a special panel component that can be reused in different Java programs. The component, ClockPanel, displays the current date and time in a manner similar to the ClockTalk project from Hour 7, "Using Conditional Tests to Make Decisions."

The first step in creating your own user interface component is to decide the existing component from which to inherit. The ClockPanel component is most like a panel, so it will be a subclass of JPanel.

The ClockPanel class is defined in Listing 13.3. This class represents panel components that include a label displaying the current date and time. Enter the text of Listing 13.3 and save the file as ClockPanel.java.

Listing 13.3. The Full Text of ClockPanel.java

 1: import javax.swing.*;

 2: import java.awt.*;

 3: import java.util.*;

 4:

 5: public class ClockPanel extends JPanel {

 6:     public ClockPanel() {

 7:         super();

 8:         String currentTime = getTime();

 9:         JLabel time = new JLabel("Time: ");

10:         JLabel current = new JLabel(currentTime);

11:         add(time);

12:         add(current);

13:     }

14:

15:     String getTime() {

16:         String time;

17:         // get current time and date

18:         Calendar now = Calendar.getInstance();

19:         int hour = now.get(Calendar.HOUR_OF_DAY);

20:         int minute = now.get(Calendar.MINUTE);

21:         int month = now.get(Calendar.MONTH) + 1;

22:         int day = now.get(Calendar.DAY_OF_MONTH);

23:         int year = now.get(Calendar.YEAR);

24:

25:         String monthName = "";

26:         switch (month) {

27:             case (1):

28:                 monthName = "January";

29:                 break;

30:             case (2):

31:                 monthName = "February";

32:                 break;

33:             case (3):

34:                 monthName = "March";

35:                 break;

36:             case (4):

37:                 monthName = "April";

38:                 break;

39:             case (5):

40:                 monthName = "May";

41:                 break;

42:             case (6):

43:                 monthName = "June";

44:                 break;

45:             case (7):

46:                 monthName = "July";

47:                 break;

48:             case (8):

49:                 monthName = "August";

50:                 break;

51:             case (9):

52:                 monthName = "September";

53:                 break;

54:             case (10):

55:                 monthName = "October";

56:                 break;

57:             case (11):

58:                 monthName = "November";

59:                 break;

60:             case (12):

61:                 monthName = "December";

62:         }

63:         time = monthName + " " + day + ", " + year + " "

64:             + hour + ":" + minute;

65:         return time;

66:     }

67: }

The getTime() method in Lines 15–66 contains the same technique for retrieving the current date and time as the ClockTalk application from Hour 7. The panel is created in the constructor method in Lines 6–13. The following things are taking place:

  • Line 8— The date and time are retrieved by calling getTime() and storing the value it returns in a String variable called currentTime.

  • Line 9— A new label named time is created with the text "Time: ".

  • Line 10— currentTime is used as the text of new label component called current.

  • Line 11— The time label is added to the clock panel by calling the panel's add() method with the label as an argument.

  • Line 12— The current label is added to the panel in the same manner.

The ClockPanel class cannot be run at a command line. To use it, you must create a Java program that includes an object of this class in its graphical user interface. This could be an application that displays a frame, an applet, or any other kind of program that features a GUI.

To try out this panel, create the ClockFrame application, which is contained in Listing 13.4.

Listing 13.4. The Full Text of ClockFrame.java

 1: import java.awt.*;

 2: import javax.swing.*;

 3:

 4: public class ClockFrame extends JFrame {

 5:     public ClockFrame() {

 6:         super("Clock");

 7:         setSize(225, 125);

 8:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 9:         FlowLayout flo = new FlowLayout();

10:         setLayout(flo);

11:         ClockPanel time = new ClockPanel();

12:         add(time);

13:         setVisible(true);

14:     }

15:

16:     public static void main(String[] arguments) {

17:         ClockFrame clock = new ClockFrame();

18:     }

19: }

When you run the application, it should resemble Figure 13.7.

Figure 13.7. Displaying a clock panel component.

    Previous Section < Day Day Up > Next Section


Summary

Users have come to expect a point-and-click, visual environment for the programs they run. This expectation makes creating software more of a challenge, but Java puts these capabilities into your hands with the windowing toolkit. Swing and the Abstract Windowing Toolkit provide all the classes you will need to provide a working, useful GUI in the tradition of Windows and Macintosh software—regardless of what kind of setup you're using to run Java programs.

During the next hour, you'll learn more about the design of a graphical user interface as you work with layout managers, classes that are used to specify how components are arranged within a container.


Q&A

Q1:

How are components arranged if I don't assign a layout manager to a container?

A1:

In a simple container such as a panel, components are arranged using FlowLayout by default—each component is added in the same manner that words are displayed on a page, from left to right until there is no more room, then on the next line down in the same manner. Frames, windows, and applets use the GridLayout default layout style you will learn about during the next hour.

Q2:

Why does the time in the ClockFrame program never change?

A2:

The time that is displayed in a ClockPanel object is set up when the panel is created. For the date and time to change over a period of time, you need to call getTime() frequently and change what the panel displays each time. This involves some techniques you will learn during Hour 24, "Creating Animation."

Q3:

Was Jimmy Carter attacked by a rabbit when he was president?

A3:

On April, 20, 1979, President Carter was fishing in Plains, Georgia, when an enraged rabbit swam towards his canoe making hissing noises and baring its teeth.

The president responded by either hitting the animal with his paddle or splashing water at it until it swam away. The incident did not become public until August 1979, when Press Secretary Jody Powell let the rabbit out of the hat.

A picture of the rabbit fleeing the president can be viewed at http://narsil.org/politics/carter/killer_rabbit.html.


Quiz

If your brain hasn't been turned into a GUI mush with this hour's toil, test your skills by answering the following questions.

Questions

1:

Which user component is used as a container to hold other components?

  1. TupperWare

  2. JPanel

  3. Choice

2:

Which of the following must be done first within a container?

  1. Establish a layout manager

  2. Add components

  3. Doesn't matter

3:

What method determines how components will be arranged within a container?

  1. setLayout()

  2. setLayoutManager()

  3. setVisible()

Answers

A1: | b. JPanel. You can add components to the panel, and then add the panel to another container such as a frame.
A2: | a. You must specify the layout manager before the components so you can add them in the correct way.
A3: | a. The setLayout() method takes one argument: the layout manager object that has the job of deciding where components should be displayed.


Activities

To interface further with the subject of GUI design, undertake the following activity:

  • Modify the SalutonFrame application so that it displays "Saluton Mondo!" in the frame's main area instead of the title bar.

  • Create a frame that contains another frame and make both of them visible at the same time.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


Hour 14. Laying Out a User Interface

When you begin designing graphical user interfaces for your Java programs, one obstacle you face is that your components can move around. Whenever a container changes size—such as when a user resizes a frame—the components within the container will rearrange themselves to fit within its new dimensions.

This fluidity works in your favor, because it takes into account the differences in how interface components are displayed on different operating systems. On the same Java program, a clickable button might look different in Windows than it does in Linux or Mac OS. This is a departure from languages such as Microsoft Visual Basic, where you specify exactly where a component will appear and what it looks like.

Components are organized in an interface by using a set of classes called layout managers. These classes define how components will be displayed within a container—during the previous hour, you used the FlowLayout class to arrange components. Each container in an interface can have its own layout manager.

The following topics will be covered:

  • Creating a layout manager

  • Assigning a layout manager to a container

  • Using panels to organize components in an interface

  • Working with unusual layouts

  • Creating a prototype for a Java application


Using Layout Managers

In Java, the placement of components within a container depends on the size of other components and the height and width of the container. The layout of buttons, text fields, and other components can be affected by the following things:

  • The size of the container

  • The size of other components and containers

  • The layout manager that is being used

There are several layout managers you can use to affect how components are shown. The default manager for panels is the FlowLayout class in the java.awt package, which was used during the previous hour.

Under FlowLayout, components are dropped onto an area in the same way words are organized on a printed page in English—from left to right, then on to the next line when there's no more space.

To set up a container to work under FlowLayout, set up the container's layout manager by calling the Container object's setLayout() method with the FlowLayout object as an argument.The following example could be used in a frame so that it will employ flow layout when components are added:

FlowLayout topLayout = new FlowLayout();

setLayout(topLayout);

You also can set up a layout manager to work within a specific container, such as a JPanel object. You can do this by using the setLayout() method of that container object. The following statements create a JPanel object called inputArea and set it up to use FlowLayout as its layout manager:

JPanel inputArea = new JPanel();

FlowLayout inputLayout = new FlowLayout();

inputArea.setLayout(inputLayout);

To give you an idea of how the different layout managers work, a simple application will be shown under each of the classes. The Crisis application has a graphical user interface with five buttons. Load your word processor and open up a new file called Crisis.java. Enter Listing 14.1 and save the file when you're done.

Listing 14.1. The Full Text of Crisis.java

 1: import java.awt.*;

 2: import javax.swing.*;

 3:

 4: public class Crisis extends JFrame {

 5:     JButton panicButton = new JButton("Panic");

 6:     JButton dontPanicButton = new JButton("Don't Panic");

 7:     JButton blameButton = new JButton("Blame Others");

 8:     JButton mediaButton = new JButton("Notify the Media");

 9:     JButton saveButton = new JButton("Save Yourself");

10:

11:     public Crisis() {

12:         super("Crisis");

13:         setSize(308, 128);

14:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

15:         FlowLayout flo = new FlowLayout();

16:         setLayout(flo);

17:         add(panicButton);

18:         add(dontPanicButton);

19:         add(blameButton);

20:         add(mediaButton);

21:         add(saveButton);

22:         setVisible(true);

23:     }

24:

25:     public static void main(String[] arguments) {

26:         Crisis cr = new Crisis();

27:     }

28: }

After compiling the Crisis application, you can run it with the following command:

java Crisis

Figure 14.1 shows the application running.

Figure 14.1. Arranging components using flow layout.

The FlowLayout class uses the dimensions of its container as the only guideline for how to lay out components. Resize the window of the application to see how components are instantly rearranged. Make the window twice as wide, and you'll see all of the JButton components are now shown on the same line. Java programs often will behave differently when their display area is resized.

The GridLayout Manager

The GridLayout class in the java.awt package organizes all components in a container into a specific number of rows and columns. All components are allocated the same amount of size in the display area, so if you specify a grid that is three columns wide and three rows tall, the container will be divided into nine areas of equal size.

The following statements create a container and set it to use a grid layout that is two rows wide and three columns tall:

GridLayout grid = new GridLayout(2, 3);

setLayout(grid);

Figure 14.2 shows what the Crisis application would look like if it used grid layout.

Figure 14.2. Arranging components using grid layout.

Some of the labels in Figure 14.2 display text that has been shortened—if the text is wider than the area available in the component, the label will be shortened using ellipses (…).

GridLayout places all components as they are added into a place on a grid. Components are added from left to right until a row is full and then the leftmost column of the next grid is filled.

The BorderLayout Manager

The next layout manager to experiment with is the BorderLayout class, also in java.awt. The following statements create a container that uses border layout, placing components at specific locations within the layout:

BorderLayout crisisLayout = new BorderLayout();

setLayout(crisisLayout);

add(panicButton, BorderLayout.NORTH);

add(dontPanicButton, BorderLayout.SOUTH);

add(blameButton, BorderLayout.EAST);

add(mediaButton, BorderLayout.WEST);

add(saveButton, BorderLayout.CENTER);

Figure 14.3 shows how this looks in the Crisis application.

Figure 14.3. Arranging components using border layout.

The BorderLayout manager arranges components into five areas: four denoted by compass directions and one for the center area. When you add a component under this layout, the add() method includes a second argument to specify where the component should be placed. This argument should be one of five class variables of the BorderLayout class: NORTH, SOUTH, EAST, WEST, and CENTER are used for this argument.

Like the GridLayout class, BorderLayout devotes all available space to the components. The component placed in the center is given all the space that isn't needed for the four border components, so it's usually the largest.

The BoxLayout Manager

Another handy layout manager, BoxLayout, makes it possible to stack components in a single row horizontally or vertically.

Unlike the other layout managers described during this hour, the BoxLayout class is in the javax.swing package.

When components are lined up in FlowLayout, they hit the right margin and wrap around to the next line, just like the words in this paragraph.

For the times when you want components on a single left-to-right or top-to-bottom line, they can be placed in a panel arranged with BoxLayout.

Create the panel, then create a layout manager with two arguments:

  • The component to organize in box layout

  • The value BoxLayout.Y_AXIS for vertical alignment and BoxLayout.X_AXIS for horizontal alignment

Here's code to stack the Crisis components:

JPanel pane = new JPanel();

BoxLayout box = new BoxLayout(pane, BoxLayout.Y_AXIS);

pane.setLayout(box);

pane.add(panicButton);

pane.add(dontPanicButton);

pane.add(blameButton);

pane.add(mediaButton);

pane.add(saveButton);

add(pane);

Figure 14.4 shows how this turns out.

Figure 14.4. Stacking components using box layout.

Separating Components with Insets

As you are arranging components within a container, you might want to move components away from the edges of the container. This is accomplished using Insets, an object that represents the border area of a container.

The Insets class, which is part of the java.awt package, has a constructor method that takes four arguments: the space to leave at the top, left, bottom, and right on the container. Each argument is specified using pixels, the same unit of measure employed when defining the size of a frame.

The following statement creates an Insets object:

Insets around = new Insets(10, 6, 10, 3);

The around object represents a container border that is 10 pixels inside the top edge, 6 pixels inside the left, 10 pixels inside the bottom, and 3 pixels inside the right.

To make use of an Insets object in a container, you must override the container's getInsets() method. This method has no arguments and returns an Insets object, as in the following example:

public Insets getInsets() {

    Insets squeeze = new Insets(50, 15, 10, 15);

    return squeeze;

}

Figure 14.5 shows how this would change one of the preceding examples, the BorderLayout-managed interface shown in Figure 14.3.

Figure 14.5. Using insets to add space around components.

The container shown in Figure 14.5 has an empty border that's 15 pixels from the left edge, 10 pixels from the bottom edge, 15 pixels from the right edge, and 50 pixels from the top edge.

By the Way

A JFrame container has a built-in inset to make room for the frame's title bar. When you override getInsets() and set your own values, a low inset value will cause the container to display components underneath the title bar.


Workshop: Laying Out an Application

The layout managers you have seen thus far were applied to an entire frame; the setLayout() method of the frame was used, and all components followed the same rules. This setup can be suitable for some programs, but as you try to develop a graphical user interface with Swing and the Abstract Windowing Toolkit, you often will find that none of the layout managers fit.

One way around this problem is to use a group of JPanel objects as containers to hold different parts of a graphical user interface. You can set up different layout rules for each of these parts by using the setLayout() methods of each JPanel. Once these panels contain all of the components they need to contain, the panels can be added directly to the frame.

This hour's workshop will be to develop a full interface for the program you will write during the next hour. The program is a Lotto number cruncher that will assess a user's chance of winning one of the multimillion-dollar Lotto contests in the span of a lifetime. This chance will be determined by running random six-number Lotto drawings again and again until the user's numbers turn up as a big winner. Figure 14.6 shows the GUI you will be developing for the application.

Figure 14.6. Displaying the graphical user interface of the LottoMadness application.

Create a new file in your word processor called LottoMadness.java. Enter Listing 14.2 and save the file when you're done.

Listing 14.2. The Full Text of LottoMadness.java

  1: import java.awt.*;

  2: import javax.swing.*;

  3:

  4: public class LottoMadness extends JFrame {

  5:

  6:     // set up row 1

  7:     JPanel row1 = new JPanel();

  8:     ButtonGroup option = new ButtonGroup();

  9:     JCheckBox quickpick = new JCheckBox("Quick Pick", false);

 10:     JCheckBox personal = new JCheckBox("Personal", true);

 11:     // set up row 2

 12:     JPanel row2 = new JPanel();

 13:     JLabel numbersLabel = new JLabel("Your picks: ", JLabel.RIGHT);

 14:     JTextField[] numbers = new JTextField[6];

 15:     JLabel winnersLabel = new JLabel("Winners: ", JLabel.RIGHT);

 16:     JTextField[] winners = new JTextField[6];

 17:     // set up row 3

 18:     JPanel row3 = new JPanel();

 19:     JButton stop = new JButton("Stop");

 20:     JButton play = new JButton("Play");

 21:     JButton reset = new JButton("Reset");

 22:     // set up row 4

 23:     JPanel row4 = new JPanel();

 24:     JLabel got3Label = new JLabel("3 of 6: ", JLabel.RIGHT);

 25:     JTextField got3 = new JTextField("0");

 26:     JLabel got4Label = new JLabel("4 of 6: ", JLabel.RIGHT);

 27:     JTextField got4 = new JTextField("0");

 28:     JLabel got5Label = new JLabel("5 of 6: ", JLabel.RIGHT);

 29:     JTextField got5 = new JTextField("0");

 30:     JLabel got6Label = new JLabel("6 of 6: ", JLabel.RIGHT);

 31:     JTextField got6 = new JTextField("0", 10);

 32:     JLabel drawingsLabel = new JLabel("Drawings: ", JLabel.RIGHT);

 33:     JTextField drawings = new JTextField("0");

 34:     JLabel yearsLabel = new JLabel("Years: ", JLabel.RIGHT);

 35:     JTextField years = new JTextField();

 36:

 37:     public LottoMadness() {

 38:         super("Lotto Madness");

 39:         setSize(550, 270);

 40:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 41:         GridLayout layout = new GridLayout(5, 1, 10, 10);

 42:         setLayout(layout);

 43:

 44:         FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER,

 45:             10, 10);

 46:         option.add(quickpick);

 47:         option.add(personal);

 48:         row1.setLayout(layout1);

 49:         row1.add(quickpick);

 50:         row1.add(personal);

 51:         add(row1);

 52:

 53:         GridLayout layout2 = new GridLayout(2, 7, 10, 10);

 54:         row2.setLayout(layout2);

 55:         row2.add(numbersLabel);

 56:         for (int i = 0; i < 6; i++) {

 57:             numbers[i] = new JTextField();

 58:             row2.add(numbers[i]);

 59:         }

 60:         row2.add(winnersLabel);

 61:         for (int i = 0; i < 6; i++) {

 62:             winners[i] = new JTextField();

 63:             winners[i].setEditable(false);

 64:             row2.add(winners[i]);

 65:         }

 66:         add(row2);

 67:

 68:         FlowLayout layout3 = new FlowLayout(FlowLayout.CENTER,

 69:             10, 10);

 70:         row3.setLayout(layout3);

 71:         stop.setEnabled(false);

 72:         row3.add(stop);

 73:         row3.add(play);

 74:         row3.add(reset);

 75:         add(row3);

 76:

 77:         GridLayout layout4 = new GridLayout(2, 3, 20, 10);

 78:         row4.setLayout(layout4);

 79:         row4.add(got3Label);

 80:         got3.setEditable(false);

 81:         row4.add(got3);

 82:         row4.add(got4Label);

 83:         got4.setEditable(false);

 84:         row4.add(got4);

 85:         row4.add(got5Label);

 86:         got5.setEditable(false);

 87:         row4.add(got5);

 88:         row4.add(got6Label);

 89:         got6.setEditable(false);

 90:         row4.add(got6);

 91:         row4.add(drawingsLabel);

 92:         drawings.setEditable(false);

 93:         row4.add(drawings);

 94:         row4.add(yearsLabel);

 95:         years.setEditable(false);

 96:         row4.add(years);

 97:         add(row4);

 98:

 99:         setVisible(true);

100:     }

101:

102:     public static void main(String[] arguments) {

103:         LottoMadness frame = new LottoMadness();

104:     }

105: }

After you compile this application, run it to see how the LottoMadness application will work. Even though you haven't added any statements that make the program do anything yet, you can make sure that the graphical interface is organized correctly and collects the information you need.

This application uses several different layout managers. If you look carefully at each of the components, you might be able to determine which manager is in use in the different areas of the program. To get a clearer picture of how the application's user interface is laid out, take a look at Figure 14.7. The interface is divided into five horizontal rows that are separated by horizontal black lines in the figure. Each of these rows is a JPanel object, and the overall layout manager of the application organizes these rows into a GridLayout of five rows and one column.

Figure 14.7. Dividing the LottoMadness application into panels.

Within the rows, different layout managers are used to determine how the components should appear. Rows 1 and 3 use FlowLayout objects. Lines 44–45 of the program show how these are created:

FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER,

    10, 10);

Three arguments are used with the FlowLayout() constructor method. The first argument, FlowLayout.CENTER, indicates that the components should be centered within their container—the horizontal JPanel on which they are placed. The last two components specify the width and height that each component should be moved away from other components. Using a width of 10 pixels and a height of 10 pixels puts a small amount of extra distance between the components.

Row 2 of the interface is laid out into a grid that is two rows tall and seven columns wide. The GridLayout() constructor also specifies that components should be set apart from other components by 10 pixels in each direction. Lines 53–54 set up this grid:

GridLayout layout2 = new GridLayout(2, 7, 10, 10);

row2.setLayout(layout2);

Row 4 uses GridLayout to arrange components into a grid that is two rows tall and three columns wide.

The LottoMadness application uses several of the components described during this hour. Lines 7–35 are used to set up objects for all of the components that make up the interface. The statements are organized by row. First, a JPanel object for the row is created, and then each component that will go on the row is set up. This code creates all of the components and containers, but they will not be displayed unless an add() method is used to add them to the application's main frame.

In Lines 44–97, the components are added. Lines 44–51 are indicative of the entire LottoMadness() constructor method:

FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER,

    10, 10);

option.add(quickpick);

option.add(personal);

row1.setLayout(layout1);

row1.add(quickpick);

row1.add(personal);

add(row1);

After a layout manager object is created, it is used with the setLayout() method of the row's JPanel object—row1 in this case. Once the layout has been specified, components are added to the JPanel by using its add() method. Once all of the components have been placed, the entire row1 object is added to the frame by calling its own add() method.


Summary

When you design a Java program's graphical user interface for the first time, you may have trouble believing that it's an advantage for components to move around. There's an appeal to seeing something exactly in the way you designed it—a feature that's called WYSIWYG, an acronym for "What You See Is What You Get."

Because Java was designed to run on a wide variety of operating systems and computing environments, interface layout was designed to be TNTWTMLL—There's No Telling What This Might Look Like.

Layout managers provide a way to develop an attractive graphical user interface that is flexible enough to handle differences in presentation.

During the next hour, you'll learn more about the function of a graphical user interface. You'll get a chance to see the LottoMadness interface in use as it churns through lottery drawings and tallies up winners.


Q&A

Q1:

Why are some of the text fields in the LottoMadness application shaded in gray while others are white?

A1:

The setEditable() method has been used on the gray fields to make them impossible to edit. The default behavior of a text field is to enable users to change the value of the text field by clicking within its borders and typing any desired changes. However, some fields are intended to display information rather than take input from the user. The setEditable() method prevents users from changing a field they should not modify.

Q2:

Why do some cities have time that varies by a half-hour from time zones, such as Rangoon, Kabul, and Tehran?

A2:

Half- and quarter-hour differences are usually because of local authorities that didn't fully support the change to Greenwich Mean Time (GMT) in the 1880s.

India, which lies between two time lines, adopted the 30-minute mark to keep sunrise and sunset from occurring too early or too late on the edges of the country.

The time in Greenwich, England, was used beginning in the 15th century to aid ocean navigation. The International Meridian Conference in 1884 extended this, creating an International Date Line and 24 time zones for each hour.

Before this, cities kept their own clocks—the U.S. had more than 300 different local times before GMT took effect on Nov. 18, 1883. Telegraph lines were used to synchronize the country.


Quiz

To see whether your brain cells are laid out properly, test your Java layout management skills by answering the following questions.

Questions

1:

What container is often used when subdividing an interface into different layout managers?

  1. JWindow

  2. JPanel

  3. Container

2:

What is the default layout manager for a panel?

  1. FlowLayout

  2. GridLayout

  3. There is no default

3:

The BorderLayout class gets its name from where?

  1. The border of each component

  2. The way components are organized along the borders of a container

  3. Sheer capriciousness on the part of Java's developers

Answers

A1: | b. JPanel.
A2: | a. Panels use flow layout, but the default manager for frames, windows, and an applet window is grid layout.
A3: | b. The border position of components must be specified as they are added to a container with the use of directional variables such as BorderLayout.WEST and BorderLayout.EAST.


Activities

If you would like to keep going with the flow (and the grid and the border), undertake the following activities:

  • Create a modified version of the Crisis application with the panic and dontPanic objects organized under one layout manager and the remaining three buttons under another.

  • Make a copy of the LottoMadness.java file that you can rename to NewMadness.java. Make changes to this program so the quick pick or personal choice is a combo box and the start, stop, and reset buttons are check boxes.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


Hour 15. Responding to User Input

The graphical user interface you developed during the past two hours can run on its own without any changes. Buttons can be clicked, text fields filled with text, and the window can be resized with wild abandon.

Sooner or later, even the least discriminating user is going to be left wanting more. The graphical user interface that a program offers has to cause things to happen when a mouse-click or keyboard entry occurs. Text areas and other components must be updated to show what's happening as the program runs.

These things are possible when your Java program can respond to user events. An event is something that happens when a program runs, and user events are things a user causes to happen by using the mouse, keyboard, or another input device. Responding to user events often is called event handling, and it's the activity you'll be learning about during this hour.

The following topics will be covered:

  • Making your programs aware of events

  • Setting up a component so it can cause events

  • Ignoring some components

  • Finding out where events end up in a program

  • Storing information in the interface

  • Converting values stored in text fields


Getting Your Programs to Listen

Before you can receive user input in a Java program, you must learn how to teach an object to listen. Responding to user events in a Java program requires the use of one or more EventListener interfaces. Interfaces are special classes that enable a class of objects to inherit behavior it would not be able to use otherwise.

Adding an EventListener interface requires two things right away. First, because the listening classes are part of the java.awt.event group of classes, you must make them available with the following statement:

import java.awt.event.*;

Second, the class must use the implements statement to declare that it supports one or more listening interfaces. The following statement creates a class that uses ActionListener, an interface for responding to button and menu clicks:

public class Graph implements ActionListener {

EventListener interfaces enable a component of a graphical user interface to generate user events. Without one of the listeners in place, a component cannot do anything that can be heard by other parts of a program. A program must include a listener interface for each type of component to which it wants to listen. To have the program respond to a mouse-click on a button or the Enter key being pressed in a text field, you must include the ActionListener interface. To respond to the use of a choice list or check boxes, you need the ItemListener interface to respond to the use of a choice list or check boxes.

When you require more than one interface in the same class, separate their names with commas after the implements statement, as in this code:

public class Graph3D implements ActionListener, MouseListener {

    // ...

}


Setting Up Components to Be Heard

After you have implemented the interface needed for a particular component, you have to set that component to generate user events. A good example is the use of JButton objects as components. When you use a button in an interface, something has to happen in response to the click of the button.

The program that should respond to the button-click must implement the ActionListener interface. This interface listens for action events, such as a button-click or the press of the Enter key. To make a JButton object generate an event, employ the addActionListener() method, as in the following:

JButton fireTorpedos = new JButton("Fire torpedos");

fireTorpedos.addActionListener(this);

This code creates the fireTorpedos button and then calls the button's addActionListener() method. The this statement used as an argument to the addActionListener() method indicates that the current object will receive the user event and handle it as needed.

By the way

Reader mail for past editions indicates that this throws a lot of people when they are introduced to it for the first time. The this keyword refers to the object in which the keyword appears. So if you create a LottoMadness class and use this in a statement, it's the LottoMadness object executing the statement.


Handling User Events

When a user event is generated by a component that has a listener, a method will be called automatically. The method must be found in the class that was specified when the listener was attached to the component. For instance, in the example of the fireTorpedos object, the method must be located in the same program because the this statement was used.

Each listener has different methods that are called to receive their events. The ActionListener interface sends events to a class called actionPerformed(). The following is a short example of an actionPerformed() method:

public void actionPerformed(ActionEvent evt) {

    // method goes here

}

All action events sent in the program will go to this method. If only one component in a program can possibly send action events, you can put statements in this method to handle the event. If more than one component can send these events, you need to use the object that is sent to the method.

In this case, an ActionEvent object is sent to the actionPerformed() method. There are several different classes of objects that represent the user events that can be sent in a program. These classes have methods you can use to determine which component caused the event to happen. In the actionPerformed() method, if the ActionEvent object is named evt, you can identify the component with the following statement:

String cmd = evt.getActionCommand();

The getActionCommand() method sends back a string. If the component is a button, the string will be the label that is on the button. If it's a text field, the string will be the text entered in the field. The getSource() method sends back the object that caused the event.

You could use the following actionPerformed() method to receive events from three components: a JButton object called start, a JTextField called speed, and another JTextField called viscosity:

public void actionPerformed(ActionEvent evt) {

    Object source = evt.getSource();

    if (source == speed) {

        // speed field caused event

    } else if (source == viscosity) {

        // viscosity caused event

    } else {

        // start caused event

    }

}

You can use the getSource() method with all types of user events to identify the specific object that caused the event.

Check Box and Combo Box Events

Combo boxes and check boxes require the ItemListener interface. Call the component's addItemListener() method to make it generate these events. For example, the following statements create a check box called superSize and cause it to send out user events when selected or deselected:

JCheckBox superSize = new JCheckBox("Super Size", true);

superSize.addItemListener(this);

These events are received by the itemStateChanged() method, which takes an ItemEvent object as an argument. To see which object caused the event, you can use the getItem() method.

To determine whether a check box is selected or deselected, use the getStateChange() method with the constants ItemEvent.SELECTED and ItemEvent.DESELECTED. The following is an example for an ItemEvent object called item:

int status = item.getStateChange();

if (status == ItemEvent.SELECTED) {

    // item was selected

}

To determine the value that has been selected in a JComboBox object, use getItem() and convert that value to a string, as in the following:

Object which = item.getItem();

String answer = which.toString();

Keyboard Events

One thing that's common in a game program is for the program to react immediately when a key is pressed. Several game programmers, such as Karl Hörnell, have created arcade-style Java applets on web pages that you control through the keyboard using the arrow keys, numeric keypad, spacebar, and other keys. Keyboard events of this kind are handled through the KeyListener interface.

The first step is to register the component that receives presses of the keyboard by calling its addKeyListener() method. The argument of the method should be the object that implements the KeyListener interface—if it is the current class, you can use this as the argument.

An object that handles keyboard events must implement three methods:

  • void keyPressed(KeyEvent)— This method is called the moment a key is pressed.

  • void keyReleased(KeyEvent)— This method is called the moment a key is released.

  • void keyTyped(KeyEvent)— This method is called after a key has been pressed and released.

Each of these has a KeyEvent object as an argument, and you can call this object's methods to find out more about the event. Call the getKeyChar() method to find out which key was pressed. This key is returned as a char value, and it only can be used with letters, numbers, and punctuation.

To monitor any key on the keyboard, including Enter, Home, Page Up, and Page Down, you can call getKeyCode() instead. This method returns an integer value representing the key. You can then call getKeyText() with that integer as an argument to receive a String object containing the name of the key (such as Home, F1, and so on).

Listing 15.1 contains a Java application that draws the most recently pressed key in a label by using the getKeyChar() method. The application implements the KeyListener interface, so there are keyTyped(), keyPressed(), and keyReleased() methods in the class. The only one of these that does anything is keyTyped() in Lines 21–24.

Listing 15.1. The Full Text of KeyView.java

 1: import javax.swing.*;

 2: import java.awt.event.*;

 3: import java.awt.*;

 4:

 5: public class KeyView extends JFrame implements KeyListener {

 6:     JTextField keyText = new JTextField(80);

 7:     JLabel keyLabel = new JLabel("Press any key in the text field.");

 8:

 9:     KeyView() {

10:         super("KeyView");

11:         setSize(350, 100);

12:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

13:         keyText.addKeyListener(this);

14:         BorderLayout bord = new BorderLayout();

15:         setLayout(bord);

16:         add(keyLabel, BorderLayout.NORTH);

17:         add(keyText, BorderLayout.CENTER);

18:         setVisible(true);

19:     }

20:

21:     public void keyTyped(KeyEvent input) {

22:         char key = input.getKeyChar();

23:         keyLabel.setText("You pressed " + key);

24:     }

25:

26:     public void keyPressed(KeyEvent txt) {

27:         // do nothing

28:     }

29:

30:     public void keyReleased(KeyEvent txt) {

31:         // do nothing

32:     }

33:

34:     public static void main(String[] arguments) {

35:         KeyView frame = new KeyView();

36:     }

37: }

When you run the application, it should resemble Figure 15.1.

Figure 15.1. Handling keyboard events in a program.

By the way

To play Karl Hörnell's Java applets, visit his website at http://www.javaonthebrain.com. He publishes the source code to more than a dozen programs he has written, and provides some explanatory notes for people trying to develop their own games.

Enabling and Disabling Components

You may have seen a component in a program that appears shaded instead of its normal appearance.

By the way

If you haven't seen a shaded component yet, you must have skipped Hour 14, "Laying Out a User Interface." I'm sorry to hear that. Sams Teach Yourself Programming with Java in 23 Hours doesn't have the same ring to it.

Shading indicates that users cannot do anything to the component because it is disabled. Disabling and enabling components as a program runs is done with the setEnabled() method of the component. A Boolean value is sent as an argument to the method, so setEnabled(true) enables a component for use, and setEnabled(false) disables a component.

The following statement creates three buttons with the labels Previous, Next, and Finish, and disables the first button:

JButton previousButton = new JButton("Previous");

JButton nextButton = new JButton("Next");

JButton finishButton = new JButton("Finish");

previousButton.setEnabled(false);

This method is an effective way to prevent a component from sending a user event when it shouldn't. For example, if you're writing a Java application that takes a user's address in text fields, you might want to disable a Save button until all of the fields have some kind of value.


Workshop: A Little Lotto Madness

To see how Swing's event-handling classes work in a Java program, you will finish LottoMadness, the lottery simulation that was begun during Hour 14.

By the way

See what you missed if you didn't read Hour 14? It may have been my finest hour.

At this point, LottoMadness is just a graphical user interface. You can click buttons and enter text into text boxes, but nothing happens in response. In this workshop, you will create LottoEvent, a new class that receives user input, conducts lotto drawings, and keeps track of the number of times you win anything. Once the class is complete, you will add a few lines to LottoMadness so that it makes use of LottoEvent. It is often convenient to divide Swing projects in this manner, with the graphical user interface in one class, and the event-handling methods in another.

The purpose of this application is to assess the user's chances of winning a six-number lotto drawing in a lifetime. Figure 15.2 shows a screen capture of the program as it continues to run.

Figure 15.2. Running the LottoMadness application.

Instead of using probability to figure this problem out, the computer will take a more anecdotal approach: It will conduct drawing after drawing after drawing until you win. Because the 6-out-of-6 win is extremely unlikely, the program also will report on any combination of three, four, or five winning numbers.

The interface you created includes 12 text fields for Lotto numbers and two check boxes labeled Quick Pick and Personal. Six of the text fields are disabled from input, and they will be used to display the winning numbers of each drawing. The other six text fields are for the user's choice of numbers. If the user wants to select six numbers manually, he should select the Personal check box. If he selects the Quick Pick box instead, six random numbers will appear in the text fields.

Three buttons control the activity of the program: Stop, Play, and Reset. When the Play button is clicked, the program starts a thread called playing and generates Lotto drawings as fast as it can. Clicking the Stop button stops the thread, and clicking Reset clears all fields so the user can start all the number-crunching over again.

The LottoEvent class implements three interfaces: ActionListener, ItemListener, and Runnable. The first two are needed to listen to user events generated by the buttons and check boxes on the application. The program does not need to listen to any events related to the text fields because they will be used strictly to store the user's choice of numbers. The user interface handles this function automatically.

The class requires the use of two packages from the Java class library: the main Swing package, javax.swing, and Java's event-handling package, java.awt.event.

The class has two instance variables:

  • gui, a LottoMadness object

  • playing, a Thread object that will be used to conduct continuous lotto drawings

The gui variable will be used to communicate with the LottoMadness object that contains the project's graphical user interface. When you need to make a change to the interface or retrieve a value from one of its text fields, you will use the gui object's instance variables.

For example, the play instance variable of LottoMadness represents the Play button. To disable this button in LottoEvent, the following statement can be used:

gui.play.setEnabled(false);

The following statement can be used to retrieve the value of the JTextField object got3:

String got3value = gui.got3.getText();

Listing 15.2 contains the full text of the LottoEvent class.

Listing 15.2. The Full Text of LottoEvent.java

  1: import javax.swing.*;

  2: import java.awt.event.*;

  3:

  4: public class LottoEvent implements ItemListener, ActionListener,

  5:     Runnable {

  6:

  7:     LottoMadness gui;

  8:     Thread playing;

  9:

 10:     public LottoEvent(LottoMadness in) {

 11:         gui = in;

 12:     }

 13:

 14:     public void actionPerformed(ActionEvent event) {

 15:         String command = event.getActionCommand();

 16:         if (command == "Play") {

 17:             startPlaying();

 18:         }

 19:         if (command == "Stop") {

 20:             stopPlaying();

 21:         }

 22:         if (command == "Reset") {

 23:             clearAllFields();

 24:         }

 25:     }

 26:

 27:     void startPlaying() {

 28:         playing = new Thread(this);

 29:         playing.start();

 30:         gui.play.setEnabled(false);

 31:         gui.stop.setEnabled(true);

 32:         gui.reset.setEnabled(false);

 33:         gui.quickpick.setEnabled(false);

 34:         gui.personal.setEnabled(false);

 35:     }

 36:

 37:     void stopPlaying() {

 38:         gui.stop.setEnabled(false);

 39:         gui.play.setEnabled(true);

 40:         gui.reset.setEnabled(true);

 41:         gui.quickpick.setEnabled(true);

 42:         gui.personal.setEnabled(true);

 43:         playing = null;

 44:     }

 45:

 46:     void clearAllFields() {

 47:         for (int i = 0; i < 6; i++) {

 48:             gui.numbers[i].setText(null);

 49:             gui.winners[i].setText(null);

 50:         }

 51:         gui.got3.setText("0");

 52:         gui.got4.setText("0");

 53:         gui.got5.setText("0");

 54:         gui.got6.setText("0");

 55:         gui.drawings.setText("0");

 56:         gui.years.setText("0");

 57:     }

 58:

 59:     public void itemStateChanged(ItemEvent event) {

 60:         Object item = event.getItem();

 61:         if (item == gui.quickpick) {

 62:             for (int i = 0; i < 6; i++) {

 63:                 int pick;

 64:                 do {

 65:                     pick = (int) Math.floor(Math.random() * 50 + 1);

 66:                 } while (numberGone(pick, gui.numbers, i));

 67:                 gui.numbers[i].setText("" + pick);

 68:             }

 69:         } else {

 70:             for (int i = 0; i < 6; i++) {

 71:                 gui.numbers[i].setText(null);

 72:             }

 73:         }

 74:     }

 75:

 76:     void addOneToField(JTextField field) {

 77:         int num = Integer.parseInt("0" + field.getText());

 78:         num++;

 79:         field.setText("" + num);

 80:     }

 81:

 82:     boolean numberGone(int num, JTextField[] pastNums, int count) {

 83:         for (int i = 0; i < count; i++) {

 84:             if (Integer.parseInt(pastNums[i].getText()) == num) {

 85:                 return true;

 86:             }

 87:         }

 88:         return false;

 89:     }

 90:

 91:     boolean matchedOne(JTextField win, JTextField[] allPicks) {

 92:         for (int i = 0; i < 6; i++) {

 93:             String winText = win.getText();

 94:             if ( winText.equals( allPicks[i].getText() ) ) {

 95:                 return true;

 96:             }

 97:         }

 98:         return false;

 99:     }

100:

101:     public void run() {

102:         Thread thisThread = Thread.currentThread();

103:         while (playing == thisThread) {

104:             addOneToField(gui.drawings);

105:             int draw = Integer.parseInt(gui.drawings.getText());

106:             float numYears = (float)draw / 104;

107:             gui.years.setText("" + numYears);

108:

109:             int matches = 0;

110:             for (int i = 0; i < 6; i++) {

111:                 int ball;

112:                 do {

113:                     ball = (int)Math.floor(Math.random() * 50 + 1);

114:                 } while (numberGone(ball, gui.winners, i));

115:                 gui.winners[i].setText("" + ball);

116:                 if (matchedOne(gui.winners[i], gui.numbers)) {

117:                     matches++;

118:                 }

119:             }

120:             switch (matches) {

121:                 case 3:

122:                     addOneToField(gui.got3);

123:                     break;

124:                 case 4:

125:                     addOneToField(gui.got4);

126:                     break;

127:                 case 5:

128:                     addOneToField(gui.got5);

129:                     break;

130:                 case 6:

131:                     addOneToField(gui.got6);

132:                     gui.stop.setEnabled(false);

133:                     gui.play.setEnabled(true);

134:                     playing = null;

135:             }

136:             try {

137:                 Thread.sleep(100);

138:             } catch (InterruptedException e) {

139:                 // do nothing

140:             }

141:         }

142:     }

143: }

Save Listing 15.2 as LottoEvent.java and compile it into a class file. This class cannot be run as an application—it lacks a main() method. Instead, you will create an object of this class in LottoMadness later in this workshop, and work with that object.

The LottoEvent class has one constructor: LottoEvent(LottoMadness). The LottoMadness object specified as an argument to the constructor identifies the object that is relying on LottoEvent to handle user events and conduct drawings.

The following methods are used in the class to accomplish specific tasks:

  • Lines 46–57: The clearAllFields() method causes all text fields in the application to be emptied out. This method is handled when the Reset button is clicked.

  • Lines 76–80: The addOneToField() method converts a text field to an integer, increments it by one, and converts it back into a text field. Because all text fields are stored as strings, you have to take special steps to use some of them as numbers.

  • Lines 82–89: The numberGone() method takes three arguments—a single number from a Lotto drawing, an array that holds several JTextField objects, and a count integer. This method makes sure that each number in a drawing hasn't been selected already in the same drawing.

  • Lines 91–99: The matchedOne() method takes two arguments—a JTextField object and an array of six JTextField objects. This method checks to see whether one of the user's numbers matches the numbers from the current lotto drawing.

The actionPerformed() method of the application receives the action events caused when the user clicks Stop, Play, or Reset. The getActionCommand() method retrieves the label of the button that is used to determine which component was pressed. Clicking the Play button causes the startPlaying() method in Lines 27–35 to be called. This method disables four components so they do not interfere with the drawings as they are taking place. Clicking Stop causes the stopPlaying() method in Lines 37–44 to be called, which enables every component except for the Stop button.

The itemStateChanged() method receives the user events triggered by the selection of the Quick Pick or Personal check boxes. The getItem() method sends back an Object that represents the check box that was clicked. If it's the Quick Pick check box, six random numbers from 1 to 50 are assigned to the user's lotto numbers. Otherwise, the text fields that hold the user's numbers are cleared out.

The LottoEvent class uses numbers from 1 to 50 for each ball in the lotto drawings. This is established in Line 113, which multiplies the Math.random() method by 50, adds 1 to the total, and uses this as an argument to the Math.floor() method. The end result is a random integer from 1 to 50. If you replaced 50 with a different number here and on Line 65, you could use LottoMadness for lottery contests that generate a wider or smaller range of values.

One thing to note about the LottoMadness project is the lack of variables used to keep track of things like the number of drawings, winning counts, and lotto number text fields. This element of user interface programming differs from other types of programs. You can use the interface to store values and display them automatically.

To finish the project, load the LottoMadness.java file you created during the last hour into your word processor. You only need to add six lines to make it work with the LottoEvent class.

First, add a new instance variable to hold a LottoEvent object, using the following statement:

LottoEvent lotto = new LottoEvent(this);

Next, in the LottoMadness() constructor, call the addItemListener() and addActionListener() methods of each user interface component that can receive user input:

// Add listeners

quickpick.addItemListener(lotto);

personal.addItemListener(lotto);

stop.addActionListener(lotto);

play.addActionListener(lotto);

reset.addActionListener(lotto);

Listing 15.3 contains the full text of LottoMadness.java after you have made the changes. The lines you added are shaded—the rest is unchanged from the previous hour.

Listing 15.3. The Full Text of LottoMadness.java

  1: import java.awt.*;

  2: import javax.swing.*;

  3:

  4: public class LottoMadness extends JFrame {

  5:     LottoEvent lotto = new LottoEvent(this);

  6:

  7:     // set up row 1

  8:     JPanel row1 = new JPanel();

  9:     ButtonGroup option = new ButtonGroup();

 10:     JCheckBox quickpick = new JCheckBox("Quick Pick", false);

 11:     JCheckBox personal = new JCheckBox("Personal", true);

 12:     // set up row 2

 13:     JPanel row2 = new JPanel();

 14:     JLabel numbersLabel = new JLabel("Your picks: ", JLabel.RIGHT);

 15:     JTextField[] numbers = new JTextField[6];

 16:     JLabel winnersLabel = new JLabel("Winners: ", JLabel.RIGHT);

 17:     JTextField[] winners = new JTextField[6];

 18:     // set up row 3

 19:     JPanel row3 = new JPanel();

 20:     JButton stop = new JButton("Stop");

 21:     JButton play = new JButton("Play");

 22:     JButton reset = new JButton("Reset");

 23:     // set up row 4

 24:     JPanel row4 = new JPanel();

 25:     JLabel got3Label = new JLabel("3 of 6: ", JLabel.RIGHT);

 26:     JTextField got3 = new JTextField("0");

 27:     JLabel got4Label = new JLabel("4 of 6: ", JLabel.RIGHT);

 28:     JTextField got4 = new JTextField("0");

 29:     JLabel got5Label = new JLabel("5 of 6: ", JLabel.RIGHT);

 30:     JTextField got5 = new JTextField("0");

 31:     JLabel got6Label = new JLabel("6 of 6: ", JLabel.RIGHT);

 32:     JTextField got6 = new JTextField("0", 10);

 33:     JLabel drawingsLabel = new JLabel("Drawings: ", JLabel.RIGHT);

 34:     JTextField drawings = new JTextField("0");

 35:     JLabel yearsLabel = new JLabel("Years: ", JLabel.RIGHT);

 36:     JTextField years = new JTextField("0");

 37:

 38:     public LottoMadness() {

 39:         super("Lotto Madness");

 40:         setSize(550, 270);

 41:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 42:         GridLayout layout = new GridLayout(5, 1, 10, 10);

 43:         setLayout(layout);

 44:

 45:         // Add listeners

 46:         quickpick.addItemListener(lotto);

 47:         personal.addItemListener(lotto);

 48:         stop.addActionListener(lotto);

 49:         play.addActionListener(lotto);

 50:         reset.addActionListener(lotto);

 51:

 52:         FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER,

 53:             10, 10);

 54:         option.add(quickpick);

 55:         option.add(personal);

 56:         row1.setLayout(layout1);

 57:         row1.add(quickpick);

 58:         row1.add(personal);

 59:         add(row1);

 60:

 61:         GridLayout layout2 = new GridLayout(2, 7, 10, 10);

 62:         row2.setLayout(layout2);

 63:         row2.add(numbersLabel);

 64:         for (int i = 0; i < 6; i++) {

 65:             numbers[i] = new JTextField();

 66:             row2.add(numbers[i]);

 67:         }

 68:         row2.add(winnersLabel);

 69:         for (int i = 0; i < 6; i++) {

 70:             winners[i] = new JTextField();

 71:             winners[i].setEditable(false);

 72:             row2.add(winners[i]);

 73:         }

 74:         add(row2);

 75:

 76:         FlowLayout layout3 = new FlowLayout(FlowLayout.CENTER,

 77:             10, 10);

 78:         row3.setLayout(layout3);

 79:         stop.setEnabled(false);

 80:         row3.add(stop);

 81:         row3.add(play);

 82:         row3.add(reset);

 83:         add(row3);

 84:

 85:         GridLayout layout4 = new GridLayout(2, 3, 20, 10);

 86:         row4.setLayout(layout4);

 87:         row4.add(got3Label);

 88:         got3.setEditable(false);

 89:         row4.add(got3);

 90:         row4.add(got4Label);

 91:         got4.setEditable(false);

 92:         row4.add(got4);

 93:         row4.add(got5Label);

 94:         got5.setEditable(false);

 95:         row4.add(got5);

 96:         row4.add(got6Label);

 97:         got6.setEditable(false);

 98:         row4.add(got6);

 99:         row4.add(drawingsLabel);

100:         drawings.setEditable(false);

101:         row4.add(drawings);

102:         row4.add(yearsLabel);

103:         years.setEditable(false);

104:         row4.add(years);

105:         add(row4);

106:

107:         setVisible(true);

108:     }

109:

110:     public static void main(String[] arguments) {

111:         LottoMadness frame = new LottoMadness();

112:     }

After you compile the LottoMadness class, run the application. If you are using the JDK, you can run it with the following command:

java LottoMadness

The application can test your lotto-playing skills for thousands of years. As you might expect, it's an exercise in futility—the chances of winning a 6-out-of-6 lotto drawing in a lifetime is extremely slim, even if you live as long as a biblical figure.

Did you Know?

The book's website at http://www.java24hours.com contains a link to an applet version of the LottoMadness program. At the time of this printing, 5,079,684 drawings have been conducted, which equals 48,843 years of twice-weekly drawings. There have been 78,198 3-out-of-6 winners, 4,135 4-out-of-6 winners, 100 5-out-of-6 winners, and 1 6-out-of-6 winner. The first person to win this fictional lottery was Bill Teer on Aug. 14, 2000, more than four years after the applet went online. His numbers were 3, 7, 1, 15, 34, and 43, and it only took him 241,225 drawings (2,319.47 years) to win.


Summary

You can create a professional-looking program with a reasonably modest amount of programming by using Swing and Java's event-handling features. Although the LottoMadness application is longer than many of the examples you have worked in during the last 14 hours, half of the program was comprised of statements to build the interface.

If you spend some time running the application, you will become even more bitter and envious about the good fortune of the people who win these six-number lottery drawings.

My most recent run of the program indicates that I could blow $27 grand and the best 266 years of my life buying tickets, only to win a handful of 4-of-6 and 3-of-6 prizes. In comparison to those odds, the chance to make Java programming skills pay off almost seems like a sure thing.


Q&A

Q1:

Is there a way to use different colors in an interface?

A1:

You can use Color objects to change the appearance of each component in several ways. The setBackground() method designates the background elements, and setForeground() sets foreground elements. You must use these methods with the components themselves. The setBackground() method of the applet will not change the color of containers and components within the applet.

Q2:

Do you need to do anything with the paint() method or repaint() to indicate that a text field has been changed?

A2:

After the setText() method of a text component is used to change its value, nothing else needs to be done. Swing handles the updating necessary to show the new value.

Q3:

Why do you often import a class and also one of its sub-classes, as in Listing 15.1 when you import java.awt.* and java.awt.event.*. Couldn't the first of these statements include the second?

A3:

Though the names of the java.awt and java.awt.event packages look like they are related, there's no such thing as inheritance for packages in Java. One package cannot be a subpackage of another.

When you use an asterisk in an import statement, you are making all of the classes in a package available in a program.

The asterisk only works on classes, not packages. The most a single import statement can load is the classes of a single package.

Q4:

Why is Massachusetts referred to as a commonwealth instead of a state?

A4:

A commonwealth is a government formed by common consent of its people, and the term was preferred over state by the founders of Kentucky, Massachusetts, Pennsylvania, and Virginia.

When John Adams wrote the second draft of the Massachusetts state constitution in 1780, it was retitled from the "State of Massachusetts-Bay" to the "Commonwealth of Massachusetts."

Other than the name, there's no legal difference between commonwealths and states. The 17th century meaning of the term commonwealth is comparable to today's definition for a republic.

The U.S. government also uses commonwealth to describe territories under Congressional control that have limited self-government over internal affairs, such as the Northern Marian Islands and Puerto Rico.


Quiz

After the LottoMadness program has soured you on games of chance, play a game of skill by answering the following questions.

Questions

1:

Why are action events called by that name?

  1. They occur in reaction to something else.

  2. They indicate that some kind of action should be taken in response.

  3. They honor cinematic adventurer Action Jackson.

2:

What does this signify as the argument to an addActionListener() method?

  1. This listener should be used when an event occurs.

  2. This event takes precedence over others.

  3. This object will handle the events.

3:

Which component stores user input as integers?

  1. JButton

  2. JTextField

  3. Neither does.

Answers

A1: | b. Action events include the click of a button and the selection of an item from a pull-down menu.
A2: | c. The this keyword refers to the current object. If the name of an object were used as an argument instead of the this statement, that object would receive the events and be expected to handle them.
A3: | c. JTextField and JTextArea components store their values as text, so their values must be converted before they can be used as integers, floating-point numbers, or other non-text values.


Activities

If the main event of this hour didn't provide enough action for your tastes, interface with the following activities:

  • Add a text field to the LottoMadness application that works in conjunction with the THRead.sleep() statement in the LottoEvent class to slow down the rate that drawings are conducted.

  • Modify the LottoMadness project so that it draws five numbers from 1 to 90.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


Hour 16. Building a Complex User Interface

Creating a graphical user interface with Swing involves more than learning how to use the different interface components, layout managers, and event-handling methods. You also have to spend some time familiarizing yourself with everything that Swing offers.

More than 400 different classes make Swing's javax.swing library and other related libraries the most extensive in Java 2. Many of these classes can be implemented using the same techniques you have used in the preceding three hours—all Swing containers and components share superclasses with each other, which gives them common behavior.

During this hour, you will learn about some additional components that you can use in your Swing programs:

  • Scroll panes— Containers that add support for vertical and horizontal scrolling to other components

  • Sliders— Components that can be used to select a number within a range of numbers

  • Change listeners— Objects that can monitor changes in sliders

  • Image icons— Graphics that can be used on labels, buttons, and other components

  • Toolbars— Containers that can be moved around to different parts of an interface

  • Menu bars, menus, and menu items— Two containers and a component used to create pull-down menus


Scroll Panes

Components in a graphical user interface are often bigger than the area available to display them. To move from one part of the component to another, vertical and horizontal scrollbars are used—this is standard behavior for a text area in software such as word processors and email programs.

In Swing, you offer scrolling by adding a component to a scroll pane, a container that is represented by the JScrollPane class in Swing.

You can create a scroll pane with the following constructors:

  • JScrollPane()— Create a scroll pane with a horizontal and vertical scrollbar that appear, if they are needed

  • JScrollPane(int, int)— Create a scroll pane with the specified vertical scrollbar and horizontal scrollbars

  • JScrollPane(Component)— Create a scroll pane that contains the specified user interface component

  • JScrollPane(Component, int, int)— Create a scroll pane with the specified component, vertical scrollbar, and horizontal scrollbar

The integers used as arguments to these constructors determine how scrollbars will be used in the pane. Use the following class variables as these arguments:

  • JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED or JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED

  • JScrollPane.VERTICAL_SCROLLBAR_NEVER or JScrollPane.HORIZONTAL_ SCROLLBAR_NEVER

  • JScrollPane.VERTICAL_SCROLLBAR_ALWAYS or JScrollPane.HORIZONTAL_ SCROLLBAR_ALWAYS

If you have created a scroll pane without a component in it, you can use the pane's add(Component) method to add components.

After you have finished setting up a scroll pane, it should be added to a container in place of the component.

To see an application that includes a scroll pane, enter Listing 16.1 into a text editor and save it as WriteMail.java.

Listing 16.1. The Full Text of WriteMail.java

 1: import javax.swing.*;

 2: import java.awt.*;

 3:

 4: public class WriteMail extends JFrame {

 5:

 6:     public WriteMail() {

 7:         super("Write an E-Mail");

 8:         setSize(370, 270);

 9:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

10:         FlowLayout flow = new FlowLayout(FlowLayout.RIGHT);

11:         setLayout(flow);

12:

13:         JPanel row1 = new JPanel();

14:         JLabel toLabel = new JLabel("To:");

15:         row1.add(toLabel);

16:         JTextField to = new JTextField(24);

17:         row1.add(to);

18:         add(row1);

19:

20:         JPanel row2 = new JPanel();

21:         JLabel subjectLabel = new JLabel("Subject:");

22:         row2.add(subjectLabel);

23:         JTextField subject = new JTextField(24);

24:         row2.add(subject);

25:         add(row2);

26:

27:         JPanel row3 = new JPanel();

28:         JLabel messageLabel = new JLabel("Message:");

29:         row3.add(messageLabel);

30:         JTextArea message = new JTextArea(4, 22);

31:         message.setLineWrap(true);

32:         message.setWrapStyleWord(true);

33:         JScrollPane scroll = new JScrollPane(message,

34:             JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

35:             JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

36:         row3.add(scroll);

37:         add(row3);

38:

39:         JPanel row4 = new JPanel();

40:         JButton send = new JButton("Send");

41:         row4.add(send);

42:         add(row4);

43:

44:         setVisible(true);

45:     }

46:

47:     public static void main(String[] arguments) {

48:         WriteMail mail = new WriteMail();

49:     }

50: }

After you compile and run the application, you should see a window like the one in Figure 16.1.

Figure 16.1. Displaying a scrolling text area in an application.

The WriteMail application is a graphical user interface that is used to compose an email. There is no event-handling code in the program, so you can't do anything with the data entered in the form.

The text of an email is entered in a scrolling text area, which is implemented with the following statements:

JTextArea message = new JTextArea(4, 22);

message.setLineWrap(true);

message.setWrapStyleWord(true);

JScrollPane scroll = new JScrollPane(message,

JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

row3.add(scroll);


Sliders

One of the easiest ways for a user to enter numeric input is by using a slider, a component that can be dragged from side to side or up and down.

Sliders are represented in Swing by the JSlider class. Figure 16.2 shows what a slider component looks like.

Figure 16.2. Displaying a slider component.

Sliders enable a number to be chosen from between a minimum and maximum range of values. These values can be displayed on a label that includes the minimum value, maximum value, and intermediate values (as shown later in Figure 16.3).

Figure 16.3. Choosing a color using slider components.

You can create a horizontal slider with one of the following constructors:

  • JSlider(int, int)— Create a slider with the specified minimum value and maximum value.

  • JSlider(int, int, int)— Create a slider with the specified minimum value, maximum value, and starting value.

To create a vertical slider, you must use a constructor method with an additional argument—the orientation of the slider. This argument should be the class variables JSlider.VERTICAL or JSlider.HORIZONTAL.

The following statement creates a vertical slider that can be used to pick a number from 1 to 1,000:

JSlider guess = new JSlider(JSlider.VERTICAL, 1, 1000, 500);

This slider starts with the caret—the part of the component used to select a number—at the 500 position.

To display a label for a slider, you must set up the information that the label will contain. Call the slider's setMajorTickSpacing(int) and setMinorTickSpacing(int) methods to determine how often a tick mark will be displayed on the label. Major ticks are displayed as a thicker line than minor ticks.

After you have set up how often tick marks will appear, call the slider's setPaintTicks(boolean) method with true as the argument.

You can also display the numeric value of each major tick by calling the slider's setPaintLabels(boolean) method with TRue.

The following statements can be used to create the slider shown in Figure 16.2:

JSlider percentage = new JSlider(0, 100, 25);

percentage.setMajorTickSpacing(10);

percentage.setMinorTickSpacing(5);

percentage.setPaintTicks(true);

percentage.setPaintLabels(true);

Watch Out!

Like other Swing components, a slider should be set up completely before you add it to the content pane or any other container. Otherwise, it may not be displayed as intended, or might not be displayed at all.


Change Listeners

To monitor the use of a slider in a Java program, you must have a class that implements the ChangeListener interface, which is part of the javax.swing.event package of classes. This interface includes only one method, which takes the following form:

public void stateChanged(ChangeEvent evt) {

    // statements to handle the event

}

To register an object as a change listener, call the addChangeListener(Object) method of the container that holds the slider. When the slider is moved, the listening object's stateChanged() method will be called.

This method is called with a ChangeEvent object that can be used to identify the slider component that was changed in value. Call the object's getSource() method and cast the object to a JSlider, as in the following statement:

JSlider changedSlider = (JSlider)evt.getSource();

In this example, evt is the ChangeEvent object that was an argument to the stateChanged() method.

When you are using a change listener, it's important to note that change events occur throughout the movement of a slider. They begin when the slider is first moved, and don't stop occurring until the slider has been released.

For this reason, you might not want to do anything in the stateChanged() method until the slider has stopped moving.

To see whether a slider is currently being moved around, call its getValueIsAdjusting() method. This method returns true while movement is taking place, and false otherwise.

This technique is demonstrated in your next project, a Java application that uses three sliders to choose a color. Colors are created in Java by using the Color class, which is part of the java.awt package.

One way to create a Color object is to specify the amount of red, green, and blue in the color. Each of these can be an integer from 0 to 255, with 255 representing the maximum amount of that color.

For example, the following statement creates a Color object that represents the color butterscotch:

Color butterscotch = new Color(255, 204, 128);

The red value used to create this Color object is 255, so it contains the maximum amount of red. It also contains a large amount of green and some blue.

Colors can be represented by a range of values, so they are an ideal use for slider components.

Listing 16.2 contains the ColorSlide application, which has three sliders, three labels for the sliders, and a panel where the color is displayed. Enter this source code into your word processor and save the file as ColorSlide.java.

Listing 16.2. The Full Text of ColorSlide.java

 1: import javax.swing.*;

 2: import javax.swing.event.*;

 3: import java.awt.*;

 4:

 5: public class ColorSlide extends JFrame implements ChangeListener {

 6:     ColorPanel canvas = new ColorPanel();

 7:     JSlider red = new JSlider(0, 255, 255);

 8:     JSlider green = new JSlider(0, 255, 0);

 9:     JSlider blue = new JSlider(0, 255, 0);

 10:

 11:     public ColorSlide() {

 12:         super("Color Slide");

 13:         setSize(270, 300);

 14:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 15:         setVisible(true);

 16:

 17:         red.setMajorTickSpacing(50);

 18:         red.setMinorTickSpacing(10);

 19:         red.setPaintTicks(true);

 20:         red.setPaintLabels(true);

 21:         red.addChangeListener(this);

 22:

 23:         green.setMajorTickSpacing(50);

 24:         green.setMinorTickSpacing(10);

 25:         green.setPaintTicks(true);

 26:         green.setPaintLabels(true);

 27:         green.addChangeListener(this);

 28:

 29:         blue.setMajorTickSpacing(50);

 30:         blue.setMinorTickSpacing(10);

 31:         blue.setPaintTicks(true);

 32:         blue.setPaintLabels(true);

 33:         blue.addChangeListener(this);

 34:

 35:         JLabel redLabel = new JLabel("Red: ");

 36:         JLabel greenLabel = new JLabel("Green: ");

 37:         JLabel blueLabel = new JLabel("Blue: ");

 38:         GridLayout grid = new GridLayout(4, 1);

 39:         FlowLayout right = new FlowLayout(FlowLayout.RIGHT);

 40:         setLayout(grid);

 41:

 42:         JPanel redPanel = new JPanel();

 43:         redPanel.setLayout(right);

 44:         redPanel.add(redLabel);

 45:         redPanel.add(red);

 46:         add(redPanel);

 47:

 48:         JPanel greenPanel = new JPanel();

 49:         greenPanel.setLayout(right);

 50:         greenPanel.add(greenLabel);

 51:         greenPanel.add(green);

 52:         add(greenPanel);

 53:

 54:         JPanel bluePanel = new JPanel();

 55:         bluePanel.setLayout(right);

 56:         bluePanel.add(blueLabel);

 57:         bluePanel.add(blue);

 58:         add(bluePanel);

 59:         add(canvas);

 60:

 61:         setVisible(true);

 62:     }

 63:

 64:     public void stateChanged(ChangeEvent evt) {

 65:         JSlider source = (JSlider)evt.getSource();

 66:         if (source.getValueIsAdjusting() != true) {

 67:             Color current = new Color(red.getValue(), green.getValue(),

 68:                 blue.getValue());

 69:             canvas.changeColor(current);

 70:             canvas.repaint();

 71:         }

 72:     }

 73:

 74:     public Insets getInsets() {

 75:         Insets border = new Insets(45, 10, 10, 10);

 76:         return border;

 77:     }

 78:

 79:     public static void main(String[] arguments) {

 80:         ColorSlide cs = new ColorSlide();

 81:     }

 82: }

 83:

 84: class ColorPanel extends JPanel {

 85:     Color background;

 86:

 87:     ColorPanel() {

 88:         background = Color.red;

 89:     }

 90:

 91:     public void paintComponent(Graphics comp) {

 92:         Graphics2D comp2D = (Graphics2D)comp;

 93:         comp2D.setColor(background);

 94:         comp2D.fillRect(0, 0, getSize().width, getSize().height);

 95:     }

 96:

 97:     void changeColor(Color newBackground) {

 98:         background = newBackground;

 99:     }

100: }

Compile and run the application. A frame will open that contains three sliders that represent the amount of red, green, and blue in a panel along the bottom edge of the frame.

Adjust the values of each slider to change the color that is displayed. Figure 16.3 shows the application being used to create North Texas Mean Green, a color that has a red value of 50, a green value of 150, and a blue value of 50. This shade inspires students and alumni of the University of North Texas, the football juggernaut of the Sun Belt Conference, to leap to our feet and make ferocious eagle-claw hand gestures that put fear in our rivals.

Perhaps it loses some of its verdant ferociousness in black-and-white.


Menus

If you're creating a program that uses a frame, you can jazz it up with a menu bar, a set of pull-down menus that is usually displayed below the title bar.

Menus in Java are created using three components: JMenuBar, JMenu, and JMenuItem.

A JMenuItem component is an item on a menu. It serves the same purpose as a button—click an item to make something happen.

A JMenu container holds JMenuItem components, lines that separate menu items, and other interface components, such as check boxes.

A JMenuBar container holds JMenu components, displaying their names.

These three work together more closely than members of the Osmond Family. For example, you could put an Exit button on a menu so users can exit the program.

This button could be put in a File menu, which is then placed in a menu bar, displaying the name File, along with other menu names below a frame's title bar.

A JMenuItem component can be set up using the same constructor methods as a JButton component: Call JMenuItem(String) to create an item with the text of the item as the argument.

The following statements create five menu items:

JMenuItem gambler1 = new JMenuItem("Hold 'Em");

JMenuItem gambler2 = new JMenuItem("Fold 'Em");

JMenuItem gambler3 = new JMenuItem("Walk Away");

JMenuItem gambler4 = new JMenuItem("Run");

JMenuItem gambler5 = new JMenuItem("Count Your Money");

Did you Know?

The gambler5 item should be disabled—call gambler5.setEnabled(false) after creating the item. You never count your money when you're sitting at the table. There'll be time enough for counting when the dealing's done.

A JMenu container holds menu items. To create one, call the JMenu(String) constructor with the menu's name as the only argument. The following statement creates a menu titled Gamble:

JMenu menu1 = new JMenu("Gamble");

After you have created a JMenu object, call its add(JMenuItem) method to add a menu item to it. Each new item will be placed at the end of the menu, so you should add items in order from top to bottom.

You also can add a text label: Call the add(String) method with the text as an argument.

If you would like to add something to a menu other than a JMenuItem or text, call a JMenu object's add(Component) method with a user interface component. The following statements create a check box and add it to a menu:

JMenu view = new JMenu("View");

JCheckBox wordWrap = new JCheckBox("Word Wrap");

view.add(wordWrap);

Menus also can contain lines that are used to visually group related items together. To add a line separator, call the addSeparator() method, which puts a line at the end of the menu.

Using the five menu items created earlier, the following statements create a menu and fill it with those items and two separators:

JMenu m1 = new JMenu("Gamble");

m1.add(gambler1);

m1.add(gambler2);

m1.addSeparator();

m1.add(gambler3);

m1.add(gambler4);

m1.addSeparator();

m1.add(gambler5);

After you have created all your menus and filled them with menu items, you're ready to add them to a frame by putting them in a JMenuBar. JMenuBar, another container, holds JMenu objects and displays each of their names, usually in a gray horizontal panel directly below an application's title bar.

To create a menu bar, call the JMenuBar() constructor method with no arguments. Call the bar's add(JMenu) method to add menus to the bar, beginning with the menu that should be displayed at the end of the bar. (The end is the rightmost position on a horizontal bar and the bottom position on a vertical bar.)

When the menu bar contains all of the menus it needs, add it to a frame by calling the frame's setJMenuBar(JMenuBar) method.

The following statement finishes off the ongoing example by creating a menu bar, adding a menu to it, and then placing the bar on a frame called kenny:

JMenuBar jmb = new JMenuBar();

jmb.add(m1);

kenny.setJMenuBar(jmb);

Figure 16.4 shows what this menu looks like on an otherwise empty frame.

Figure 16.4. A frame with a menu bar.

You already know how to handle events generated by these menu items, because JMenuItem objects function like buttons, and can generate action events when they are selected. Other components such as check boxes work the same way they do when placed in other containers.


Workshop: Using Image Icons and Toolbars

One of the easiest ways to improve the visual appeal of a graphical user interface is to use icons, or small images used to identify buttons, menu items, and other parts of an interface.

With many of the components in the Swing class library, you can label a component with an image instead of text by using the ImageIcon class in the javax.swing package.

You can create an ImageIcon from a file on your computer by calling the ImageIcon(String) constructor method. The argument to the method is either the name of the file or its location and name, as in these examples:

ImageIcon stopSign = new ImageIcon("stopsign.gif");

ImageIcon saveFile = new ImageIcon("images/savefile.gif");

Watch Out!

Make note of the / separator used in path names when creating an ImageIcon object. Although some operating systems use the \character to separate folders and file names, the ImageIcon constructor requires the / character.

The graphics file used to create the image icon must be in GIF or JPEG format. Most will be in GIF format, because it is well-suited to displaying small graphics with a limited number of colors.

The constructor method of ImageIcon will load the entire image from the file immediately—unlike other graphics-related classes you will work with during Hour 23, "Working with Graphics."

You can use image icons as labels and buttons by using the JLabel(ImageIcon) and JButton(ImageIcon) constructor methods, as in the following example:

ImageIcon siteLogo = new ImageIcon("siteLogo.gif");

JLabel logoLabel = new JLabel(siteLogo);

ImageIcon searchWeb = new ImageIcon("searchGraphic.gif");

JButton search = new JTextField(searchWeb);

Several components can have an icon and a text label. The following statement creates a button with both:

JButton refresh = new JButton("Refresh",

    "images/refreshIcon.gif");

Image icons often are used in toolbars, containers that group several components together into a row or column.

They also can be added to menus. Call the JMenuItem(Icon) to add an icon to a menu or JMenuItem(String, Icon) to add an icon and text.

Toolbars, which are created by using the JToolBar class in Swing, can be designed so that a user can move them from one part of a graphical user interface to another. This process is called docking, and these components are also called dockable toolbars.

You can create a toolbar with one of the following constructor methods:

  • JToolBar()— Create a toolbar that will line up components in a horizontal direction

  • JToolBar(int)— Create a toolbar that will line up components in the specified direction, which is either SwingConstants.HORIZONTAL or SwingConstants. VERTICAL

Components are added to a toolbar in the same way they are added to other containers—the add(Component) method is called with the component to be added.

For a toolbar to be dockable, it must be placed in a container that uses BorderLayout as its layout manager. This layout arranges a container into north, south, east, west, and center areas. When you are using a dockable toolbar, however, the container should only use two of these: the center and only one directional area.

The toolbar should be added to the directional area. The following statements create a vertical, dockable toolbar with three icon buttons:

BorderLayout border = new BorderLayout();

pane.setLayout(border);

JToolBar bar = new JToolBar(SwingConstants.VERTICAL);

ImageIcon play = new ImageIcon("play.gif");

JButton playButton = new JButton(play);

ImageIcon stop = new ImageIcon("stop.gif");

JButton stopButton = new JButton(stop);

ImageIcon pause = new ImageIcon("pause.gif");

JButton pauseButton = new JButton(pause);

bar.add(playButton);

bar.add(stopButton);

bar.add(pauseButton);

add(bar, BorderLayout.WEST);

The next project you will undertake during this hour is Tool, a Java application that includes image icons and a dockable toolbar around.

Open your text editor and enter Listing 16.3, saving the file as Tool.java.

Listing 16.3. The Full Text of Tool.java

 1: import java.awt.*;

 2: import java.awt.event.*;

 3: import javax.swing.*;

 4:

 5: public class Tool extends JFrame {

 6:     public Tool() {

 7:         super("Tool");

 8:         setSize(370, 200);

 9:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

10:

11:         // build toolbar buttons

12:         ImageIcon image1 = new ImageIcon("newfile.gif");

13:         JButton button1 = new JButton(image1);

14:         ImageIcon image2 = new ImageIcon("openfile.gif");

15:         JButton button2 = new JButton(image2);

16:         ImageIcon image3 = new ImageIcon("savefile.gif");

17:         JButton button3 = new JButton(image3);

18:

19:         // build toolbar

20:         JToolBar bar = new JToolBar();

21:         bar.add(button1);

22:         bar.add(button2);

23:         bar.add(button3);

24:

25:         // build text area

26:         JTextArea edit = new JTextArea(8, 40);

27:         JScrollPane scroll = new JScrollPane(edit);

28:

29:         // create frame

30:         BorderLayout border = new BorderLayout();

31:         setLayout(border);

32:         add("North", bar);

33:         add("Center", scroll);

34:         setVisible(true);

35:     }

36:

37:     public static void main(String[] arguments) {

38:         Tool frame = new Tool();

39:     }

40: }

The Tool application requires three graphics files that will be used to create the icons on the toolbar: newfile.gif, openfile.gif, and savefile.gif. You can find these files on the book's website at http://www.java24hours.com (open the Hour 16 page).

Figure 16.5 and Figure 16.6 show two different screenshots of this application as it runs. The toolbar has been moved from its original location (Figure 16.5) to another edge of the interface (Figure 16.6).

Figure 16.5. Using an application with a toolbar.

Figure 16.6. Docking a toolbar at a new location.

Compile the application and try it out by moving the toolbar around. You can move a toolbar by clicking its handle and dragging the toolbar to a different edge of the text area. When you release the toolbar, it will be placed along that edge and the text area will move over to make room for it.

By the Way

You also can drag a dockable toolbar off an interface entirely. This causes a new window to be opened that contains the toolbar.

Sun Microsystems offers a repository of icon graphics that you can use in your own programs. The three icons used in this hour's workshop are from that collection. To view the graphics, visit the web page http://java.sun.com/developer/techDocs/hi/repository.


Summary

This is the last of four hours devoted to Swing, the part of the Java language that supports windowing software.

Java offers extensive support for the graphical user interface features expected by users of Microsoft Windows and Apple Macintosh systems.

Although Swing is by far the largest part of the Java class library, most of the classes are used in similar ways. Once you know how to create a component, add a component to a container, apply a layout manager to a container, and respond to user input, you can make use of many new Swing classes as you explore the language.


Q&A

Q1:

Is there a reason to display scrollbars only when they are needed, as opposed to displaying them all the time?

A1:

Normally, the decision is based on how you want the interface to look. Some interface designers prefer to have the scrollbars visible at all times, while others make them visible only when the component needs them.

With early implementations of scroll panes in Java 2, scrollbars would disappear in certain instances and never reappear. Though this appears to have been resolved, making scrollbars visible at all times is a way to work around a problem like this.

Q2:

How can I find out about the rest of the Swing classes in the Java class library?

A2:

On Sun's official Java site, the full documentation for the Java class library is published at http://java.sun.com/j2se/1.5.0/docs/api. You can see the classes that are included in javax.swing, java.awt, and java.awt.event, the packages that were covered during the preceding four hours. All Swing classes and interfaces are documented, including their constructor methods, class variables, and instance variables. There are also links to some of Sun's official tutorials for Swing programmers.

Q3:

Did they charge admission or have reserved seating at the Colosseum?

A3:

Aside from the killing, the fan experience at the Roman Colosseum was similar to today's sporting events. There were 45,000 seats in the amphitheatre and room for up to 5,000 standing fans.

Tickets, which were heavily in demand, were marked with the entrance to use as well as the tier and row number of the seat. The emperor rated a luxury box, and senators and other high officials got the best seats.

Admission was free, because aspiring politicians bankrolled the events. The Colosseum, known officially as the Flavian Amphitheatre, opened in 80 A.D. Most of the biggest attractions involved people fighting each other or animals. Up to 5,000 animals were killed on Opening Day of the facility.


Quiz

No pane, no gain: Exercise some brain muscle by answering the following questions about scroll panes, image icons, and other Swing features.

Questions

1:

What graphics file formats are supported by the ImageIcon class?

  1. GIF

  2. GIF and JPEG

  3. GIF, PNG, and JPEG

2:

What does a JSlider object's getValueIsAdjusting() method accomplish?

  1. It determines whether the slider has been changed from its original value.

  2. It determines whether the slider is currently being changed in value.

  3. Not a lot; this method is a major disappointment to its parent superclass.

3:

The Swing library was named after a style of dance band jazz that was popularized in the 1930s and unexpectedly revived in the 1990s. Which of the following is not a real title of a song performed by a Swing musician?

  1. "Cement Mixer (Put-ti, Put-ti)"

  2. "Barney Google with the Goo Goo Googly Eyes"

  3. "Flat Foot Floogie (with the Floy Floy)"

Answers

A1: | b. PNG is supported with other Java classes that involve images, but graphics in this format aren't supported by ImageIcon.
A2: | b. The getValueIsAdjusting() method returns TRue while the slider is being moved and false otherwise.
A3: | b. "Barney Google," a hit song by Billy Rose in 1923, was too early for Swing. The other two songs are Swing hits by Slim Gaillard, whose gift for gibberish also was evident in the songs "Boot-Ta-La-Za," "Ra-Da-Da-Da," " Bingie-Bingie-Scootie," and "Vout Oreenie."


Activities

To see whether you have the swing of things, try the following activities:

  • Create a graphical user interface that includes a combo box in a scroll pane.

  • Add event-handling to the WriteMail application that displays the contents of the to, subject, and message components using System.out.println() when the Send button is clicked.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


    Part V: Creating Multimedia Programs

    HOUR 17 Creating Interactive Web Programs

    HOUR 18 Handling Errors in a Program

    HOUR 19 Creating a Threaded Program

    HOUR 20 Reading and Writing Files


Hour 17. Creating Interactive Web Programs

Now that Java has made the transition from a child prodigy to an established language, it is being used for all kinds of large-scale business software and other applications. How ever, for some people, the core appeal of the language remains a type of program that Java made possible: the applet.

Applets are programs designed to run as part of a World Wide Web page. When a Java applet is encountered on a page, it is downloaded to the user's computer and begins running.

During this hour you'll be introduced to applet programming and Java Web Start, a way to install and run Java software from within a web browser.

Programming applets with Java is much different from creating applications with Java. Because applets must be downloaded from a page each time they are run, they're smaller than most applications to reduce download time. Also, because applets run on the computer of the person using the applet, they have numerous security restrictions in place to prevent malicious or damaging code from being run.

The following topics will be covered:

  • Displaying information in an applet

  • Stopping and starting an applet

  • Putting an applet on a web page

  • Customizing an applet with parameters on a web page

  • Receiving parameters in an applet

  • Running applets with the Java Plug-in


Standard Applet Methods

The first step in the creation of an applet is to make it a subclass of JApplet, a class that's part of the Swing package, javax.swing. An applet is treated as a visual window inside a web page, so JApplet is part of Swing alongside clickable buttons, scrollbars, and other components of a program's user interface.

JApplet is a subclass of Applet, a class in the java.applet package. Being part of this hierarchy enables the applets you write to use all the behavior and attributes they need to be run as part of a web page. Before you begin writing any other statements in your applets, they will be able to interact with a web browser, load and unload themselves, redraw their window in response to changes in the browser window, and handle other necessary tasks.

In applications, programs begin running with the first statement inside the main() block statement and end with the last closing bracket (}) that closes out the block. There is no main() method in a Java applet, so there is no set starting place for the program. Instead, an applet has a group of standard methods that are handled in response to specific events as the applet runs.

The following are the events that could prompt one of the applet methods to be handled:

  • The program is loaded for the first time, which causes the applet's init() and start() methods to be called.

  • Something happens that requires the applet window to be redisplayed, which causes the applet's paint() method to be called.

  • The program is stopped by the browser, which calls the applet's stop() method.

  • The program restarts after a stop, which calls the start() method.

  • The program is unloaded as it finishes running, which calls the destroy() method.

The following is an example of a bare-bones applet:

public class Skeleton extends javax.swing.JApplet {

    // program will go here

}

Unlike applications, applet class files must be public because the JApplet class is also public. (If your applet uses other class files of your own creation, they do not have to be declared public.)

Your applet's class inherits all the methods that are handled automatically when needed: init(), paint(), start(), stop(), and destroy(). However, none of these methods do anything. If you want something to happen in an applet, you have to override these methods with new versions in your applet program.

Painting an Applet Window

The paint() method is used to display text, shapes, and graphics within the applet window. Whenever something needs to be displayed or redisplayed on the applet window, the paint() method handles the task. You also can force paint() to be handled with the following statement in any method of an applet:

repaint();

Aside from the use of repaint(), the main time the paint() method is handled is when something changes in the browser or the operating system running the browser. For example, if a user minimizes a web page containing an applet, the paint() method will be called to redisplay everything that was onscreen in the applet when the applet is later restored to full size.

Unlike the other methods you will be learning about during this hour, paint() takes an argument. The following is an example of a simple paint() method:

public void paint(Graphics screen) {

    Graphics2D screen2D = (Graphics2D)screen;

    // display statements go here

}

The argument sent to the paint() method is a Graphics object. The Graphics class of objects represents an environment in which something can be displayed, such as an applet window. As you did with Swing programs, you may cast this to a Graphics2D object to employ more sophisticated graphical features.

Later this hour, you'll learn about drawString(), a method for the display of text that's available in both the Graphics and Graphics2D classes.

If you are using a Graphics or Graphics2D object in your applet, you have to add the following import statements before the class statement at the beginning of the source file:

import java.awt.Graphics;

import java.awt.Graphics2D;

Did you Know?

If you are using several classes that are a part of the java.awt package of classes, you can use the statement import java.awt.* to make all of these classes available for use in your program.

Initializing an Applet

The init() method is handled once—and only once—when the applet is run. As a result, it's an ideal place to set up values for any objects and variables that are needed for the applet to run successfully. This method is also a good place to set up fonts, colors, and the screen's background color. Here's an example:

public void init() {

FlowLayout flo = new FlowLayout();

    setLayout(flo);

    JButton run = new JButton("Run");

    add(run);

}

If you are going to use a variable in other methods, it should not be created inside an init() method because it will only exist within the scope of that method.

For example, if you create an integer variable called displayRate inside the init() method and try to use it in the paint() method, you'll get an error when you attempt to compile the program. Create any variables you need to use throughout a class as object variables right after the class statement and before any methods.

Starting and Stopping an Applet

At any point when the applet program starts running, the start() method will be handled. When a program first begins, the init() method is followed by the start() method. After that, in many instances there will never be a cause for the start() method to be handled again. In order for start() to be handled a second time or more, the applet has to stop execution at some point.

The stop() method is called when an applet stops execution. This event can occur when a user leaves the web page containing the applet and continues to another page. It also can occur when the stop() method is called directly in a program.

Destroying an Applet

The destroy() method is an opposite of sorts to the init() method. It is handled just before an applet completely closes down and completes running.

This method is used when something has been changed during a program that should be restored to its original state. It's another method you'll use more often with animation than with other types of programs.


Putting an Applet on a Web Page

Applets are placed on a web page in the same way that anything unusual is put on a page: HTML markup tags describe the applet, which a web browser loads along with the other parts of the page. If you have used HTML to create a web page, you know that it's a way to combine formatted text, images, sound, and other elements together. HTML uses special commands called tags that are surrounded by < and > marks, including img for the display of images, p for the insertion of a paragraph mark, and <center> to center the text that follows until a </center> tag is reached.

The performance of some of these HTML tags can be affected by attributes that determine how they function. For example, src is an attribute of the img tag, and it provides the name of the image file that should be displayed. The following is an example of an img tag:

<IMG SRC="graduation.jpg">

One way to place applets on a web page is by using an applet tag and several attributes. The following is an example of the HTML required to put an applet on a page:

<applet code="StripYahtzee.class" codebase="javadir" height="300" width="400">

Sorry, no dice ... this requires a Java-enabled browser.

</applet>

The code attribute identifies the name of the applet's class file. If more than one class file is being used with an applet, code should refer to the main class file that is a subclass of the JApplet class.

If there is no code attribute, all files associated with the applet should be in the same folder as the web page that loads the program. codebase should contain a reference to the folder or subfolder where the applet and any related files can be found. In the preceding example, codebase indicates that the StripYahtzee applet can be found in the javadir subfolder.

The height and width attributes designate the exact size of the applet window on the web page. It must be big enough to handle the things you are displaying in your applet.

In between the opening <applet> tag and the closing </applet> tag, you can provide an alternate of some kind for web users whose browser software cannot run Java programs (less than two percent of all web users run browsers that fall into this group).

In the preceding example, the text "Sorry, no dice…this requires a Java-enabled browser" is displayed in place of the applet on a browser such as Lynx, which does not support Java. You can put instructions here on how to download a Java-enabled browser. You also can include hyperlinks and other HTML elements.

Another useful attribute, align, designates how an applet will be displayed in relation to the surrounding material on the page, including text and graphics. The value align="left" lines up the applet to the left of adjacent page elements and align="right" lines it up to the right.


A Sample Applet

This hour's first project is an applet that displays the string "Saluton mondo!", the traditional Esperanto greeting that is becoming more traditional by the hour. You'll take a look at how applets are structured by re-creating the Saluton application from Hour 2, "Writing Your First Program," as a program that can run on a web page.

Load your word processor and create a new file called SalutonApplet.java. Enter the text of Listing 17.1 into the file and save it when you're done.

Listing 17.1. The Full Text of SalutonApplet.java

 1: import java.awt.*;

 2:

 3: public class SalutonApplet extends javax.swing.JApplet {

 4:     String greeting;

 5:

 6:     public void init() {

 7:         greeting = "Saluton mondo!";

 8:     }

 9:

10:     public void paint(Graphics screen) {

11:         Graphics2D screen2D = (Graphics2D)screen;

12:         screen2D.drawString(greeting, 25, 50);

13:     }

14: }

This applet does not need to use the start(), stop(), or destroy() methods, so they are not included in the program. Compile the program with the javac compiler tool, if you're an JDK user, or another tool.

Drawing in An Applet Window

Text is displayed in an applet window by using the drawString() method of the Graphics2D class, which draws text in a graphical user interface component.

The drawString() method is similar in function to the System.out.println() method that displays information to the system's standard output device.

Before you can use the drawString() method, you must have a Graphics or Graphics2D object that represents the applet window.

The paint() method of all applets includes a Graphics object as its only argument, which can be cast to a Graphics2D object:

Graphics2D screen2D = (Graphics2D)screen;

When you have created a Graphics2D object like this, you can call its drawString() method to display text on the area represented by the object.

The following three arguments are sent to drawString():

  • The text to display, which can be several different strings and variables strung together with the + operator

  • The x position (in an (x,y) coordinate system) where the string should be displayed

  • The y position where the string should be displayed

The (x,y) coordinate system in an applet is used with several methods. It begins with the (0,0) point in the upper-left corner of the applet window. Figure 17.1 shows how the (x,y) coordinate system works in conjunction with the statement on Line 12 of SalutonApplet.java.

Figure 17.1. Drawing a string to an (x,y) position.

Testing the SalutonApplet Program

Although you have compiled the SalutonApplet program into a class file, you cannot run it using a Java interpreter such as java. If you do, you'll get an error message looking like this:

Exception in thread "main" java.lang.NoSuchMethodError: main

The error occurs because a Java interpreter runs applications by calling its main() method. Applets don't include this method. Instead, to run an applet, you need to create a web page that loads the applet. To create a web page, open up a new file on your word processor and call it SalutonApplet.html. Enter Listing 17.2 and then save the file.

Listing 17.2. The Full Text of SalutonApplet.html

 1: <html>

 2: <head>

 3: <title>Saluton Mondo!</title>

 4: </head>

 5: <body bgcolor="#000000" text="#FF00FF">

 6: <center>

 7: This a Java applet:<br>

 8: <applet code="SalutonApplet.class" height=150 width=300>

 9: You need a Java-enabled browser to see this.

10: </applet>

11: </body>

12: </html>

All applets you write can be tested with the appletviewer tool that comes with the Java Development Kit. You can see the output of the SalutonApplet applet by typing the following:

appletviewer SalutonApplet.html

One thing to note about appletviewer is that it only runs the applets that are included in a web page, and does not handle any of the other elements such as text and images.

Applets can also be loaded by web browsers, if they are equipped with the Java Plug-in. To attempt this at a command line, type the following command:

SalutonApplet.html

You can also choose File, Open from the browser's menu to find and open the page.

Figure 17.2 shows a screen capture of SalutonApplet loaded in Mozilla Firefox.

Figure 17.2. The SalutonApplet program running on a web page.

If you can't get this applet to run in Firefox or another web browser, the most likely reason is that the browser needs the Java Plug-in.


The Java Plug-in

Though popular web browsers began including their own Java interpreters with the first release of the language in the mid-'90s, these interpreters failed to keep current.

To make it possible for Java 2 applets to run in current browsers, Sun Microsystems offers the Java Plug-in, a substitute for a browser's built-in interpreter that supports the most up-to-date version of the language.

A plug-in is a program that works in conjunction with a web browser to expand its functionality. Plug-ins handle a type of data that the browser normally could not handle. Apple offers a plug-in to display QuickTime movies, Macromedia distributes a plug-in to run Flash animation files, and many other kinds of special content are supported in this manner.

If you installed the Java Development Kit, you were given a chance to install the Java Plug-in at the same time.

The Java Plug-in runs Java applets in place of the web browser's Java interpreter. Once the Java Plug-in is installed, all future Java 2 applets will run automatically if they specify that the Plug-in should be used to run them.

The plug-in is part of the Java Runtime Environment, which can be downloaded at no cost from Sun's Java site at the address http://java.com.


Sending Parameters from a Web Page

Now that you have had some experience writing computer programs, you might be feeling one of the strongest emotions of the programmer: compiler angst. Even though it takes no more than 15 seconds to compile most programs, that time can seem interminable when you're debugging a program. Write, save, compile, Aargh—an error! Write, save, compile, Aargh! Write, save, compile, Aargh!… As this vicious cycle repeats itself, it's easy to become world-weary as a program is compiled and recompiled.

One of the driving forces behind parameter use in Java applets is the fear and loathing of compilation. Parameters enable you to change elements of an applet without editing or recompiling anything. They also make the program more useful.

Parameters are stored as part of the web page that contains an applet. They are created using the HTML tag param and its two attributes: name and value. You can have more than one param tag with an applet, but all of them must be between the opening <applet> tag and the closing </applet> tag, which also support parameters). The following is an applet tag that includes several parameters:

<applet code="ScrollingHeadline.class" height="50" width="400">

<param name="headline1" value="Dewey defeats Truman">

<param name="headline2" value="Stix nix hix pix">

<param name="headline3" value="Man bites dog">

</applet>

This example could be used to send news headlines to an applet that scrolls them across the screen. Because news changes all the time, the only way to create a program of this kind is with parameters.

You use the name attribute to give the parameter a name. This attribute is comparable to giving a variable a name. The value attribute gives the named parameter a value.


Receiving Parameters in the Applet

You have to do something in your Java program to retrieve the parameters on the web page or they will be ignored. The getParameter() method of the JApplet class retrieves a parameter from a param tag on a web page. The parameter name, which is specified with the name attribute on the page, is used as an argument to getParameter(). The following is an example of getParameter() in action:

String display1 = getParameter("headline1");

The getParameter() method returns all parameters as strings, so you have to convert them to other types as needed. If you want to use a parameter as an integer, you could use statements such as the following:

int speed;

String speedParam = getParameter("speed");

if (speedParam != null) {

    speed = Integer.parseInt(speedParam);

}

This example sets the speed variable by using the speedParam string. You have to test for null strings before setting speed because the parseInt() method cannot work with a null string. When you try to retrieve a parameter with getParameter() that was not included on a web page with the param tag, it will be sent as null, which is the value of an empty string.


Workshop: Handling Parameters in an Applet

The next project you'll undertake has little practical value, except perhaps as a taunting device. The ShowWeight applet takes a person's weight and displays it under several different units. The applet takes two parameters: a weight in pounds, and the name of the person who weighs that amount. The weight is used to figure out the person's weight in ounces, kilograms, and metric tons, all of which are displayed.

Create a new file with your word processor and give it the name ShowWeight.java. Enter Listing 17.3 into the file. Then save and compile the file.

Listing 17.3. The Full Text of ShowWeight.java

 1: import java.awt.*;

 2:

 3: public class ShowWeight extends javax.swing.JApplet {

 4:     float lbs = (float)0;

 5:     float ozs;

 6:     float kgs;

 7:     float metricTons;

 8:     String name = "somebody";

 9:

10:     public void init() {

11:         String lbsValue = getParameter("weight");

12:         if (lbsValue != null) {

13:             Float lbsTemp = Float.valueOf(lbsValue);

14:             lbs = lbsTemp.floatValue();

15:         }

16:         String personValue = getParameter("person");

17:         if (personValue != null) {

18:             name = personValue;

19:         }

20:         ozs = (float)(lbs * 16);

21:         kgs = (float)(lbs / 2.204623);

22:         metricTons = (float)(lbs / 2204.623);

23:     }

24:

25:     public void paint(Graphics screen) {

26:         Graphics2D screen2D = (Graphics2D) screen;

27:         screen2D.drawString("Studying the weight of " + name, 5, 30);

28:         screen2D.drawString("In pounds: " + lbs, 55, 50);

29:         screen2D.drawString("In ounces: " + ozs, 55, 70);

30:         screen2D.drawString("In kilograms: " + kgs, 55, 90);

31:         screen2D.drawString("In metric tons: " + metricTons, 55, 110);

32:     }

The init() method is where the two parameters are loaded into the applet. Because they come from the web page as strings, they must be converted into the form you need: a floating-point number for the lbs variable, and a string for name.

Converting a string to a floating-point number requires two steps: converting the string to a Float object and then converting that object to a variable of the type float.

By the Way

As you learned with strings, objects and variables are treated differently in Java programs, and there are different things you can do with them. The reason there is a Float object and a float variable type is so you can use a floating-point number as either an object or a variable. The Float object class also has useful methods, such as valueOf() and floatValue(), that you can use to convert floating-point numbers into different types of variables.

Lines 20–22 are used to convert the lbs variable into different units of measure. Each of these statements has (float) in front of the conversion equation. This is used to cast the result of the equation into a floating-point number.

The paint() method of the applet uses the drawString() method of the Graphics2D class to display a line of text onscreen. The paint() method has three arguments: the text to display, and the x and y positions where the text should be shown.

Before you can test the ShowWeight applet, you need to create a web page that contains the applet. Open up a new file on your word processor and name it ShowWeight.html. Enter Listing 17.4 and save it when you're done.

Listing 17.4. The Full Text of ShowWeight.html

1: <applet code="ShowWeight.class" height="170" width="210">

2: <param name="person" value="Konishiki">

3: <param name="weight" value=605>

4: </applet>

Use a web browser equipped with the Java Plug-in to see the ShowWeight applet. This demonstration uses Konishiki as its example because the American-born sumo wrestling champion weighs in at more than 605 pounds, making him the largest of these immodest, bikini-wearing behemoths. You can substitute anyone whose weight is either exemplary or well-known. Figure 17.3 shows an example of output from the applet. As you can see, Konishiki's workout regimen doesn't include a lot of fat-free SnackWell's Devil's Food Cakes.

Figure 17.3. The ShowWeight applet loaded with Mozilla Firefox.

To make the applet display a different name along with a different value for the weight parameter, all you have to change is the ShowWeight.html file. The applet itself will continue to work correctly.


Java Web Start

One of the issues you must deal with as a Java programmer is how to make your software available to the people who will be using your work.

Applications require a Java interpreter, so one must either be included with the application, or users must install an interpreter themselves. The easiest solution is to require that users download and install the Java Runtime Environment from Sun's web site at http://java.com.

Regardless of how you deal with the requirement for an interpreter, you distribute an application like any other program, making it available on a CD, website, or some other means. A user must run an installation program to set it up, if one is available, or copy the files and folders manually.

Applets are easier to make available, because they can be run by web browsers.

There are several drawbacks to offering applets instead of applications, most importantly the default security policy for applets, which makes it impossible for them to read and write data on a user's computer, among other restrictions.

Java supports another way to make applications available to users: Java Web Start, a method of downloading and running applications by clicking links on web pages.

Java Web Start, which requires the Java Plug-in, offers a way to install and run applications as if they were applets. Here's how it works:

  • A programmer packages an application into a Java Archive file along with a file that uses the Java Network Launching Protocol (JNLP), part of Java Web Start.

  • The file is published on a web server along with a web page that links to that file.

  • A user loads the page with a browser and clicks the link.

  • If the user does not have the Java Runtime Environment, a dialog box opens asking whether it should be downloaded and installed.

  • The Java Runtime Environment installs and runs the program, opening new frames and other interface components like any other application. The program is saved in a cache, so it can be run again later without requiring installation.

To see it in action, visit Sun's Java Web Start site at http://java.sun.com/products/javawebstart/demos.html. The Web Start Demos page contains pictures of several Java applications, each with a Launch button you can use to run the application, as shown in Figure 17.4.

Figure 17.4. Presenting Web Start applications on a web page.

[View full size image]

Click the Launch button of one of the applications. If you don't have the Java Runtime Environment yet, a dialog box opens asking whether you would like to download and install it.

The runtime environment includes the Java Plug-in, a Java interpreter that adds support for the current version of the language to browsers such as Internet Explorer and Mozilla. The environment can also be used to run applications, whether or not they make use of Java Web Start.

When an application is run using Java Web Start, a title screen will be displayed on your computer briefly and the application's graphical user interface will appear.

Figure 17.5 shows one of the demo applications offered by Sun, a military strategy game in which three black dots gang up upon a red dot and attempt to keep it from moving into their territory.

Figure 17.5. Running a Java Web Start application.

As you can see in Figure 17.5, the application looks no different than any of the applications you created during the preceding 16 hours. Unlike applets, which are presented in conjunction with a web page, applications launched with Java Web Start run in their own windows, as if they were run from a command line.

Did you Know?

If you try out the dot game, be advised that the red dot is a lot tougher than he looks, even when outnumbered. I tried it out numerous times during the preparation of this hour of the book, and it took dozens of games over several editions before my black dots finally achieved victory.

One thing that's different about a Java Web Start application is the security that can be offered to users. When an application attempts to do some things such as reading and writing files, the user can be asked for permission.

For example, another one of the demo programs is a text editor. When you try to save a file with this application for the first time, the Security Advisory dialog box opens (see Figure 17.6).

Figure 17.6. Choosing an application's security privileges.

If the user does not permit something, the application will be unable to function fully. The kinds of things that would trigger a security dialog are the same things that are not allowed by default in applets: reading and writing files, loading network resources, and the like.

Once an application has been run by Java Web Start, it is stored in a cache, enabling you to run it again later without installation. The only exception is when a new version of the application has become available. In this circumstance, the new version will be downloaded and installed in place of the existing one automatically.


Using Java Web Start

Any Java application can be run using Java Web Start, as long as the web server that will offer the application is configured to work with the technology.

To prepare an application to use Java Web Start, you must save the application's files in a Java Archive (JAR) file, create a special Java Web Start file for the application, and upload the files to the web server.

The special file that must be created uses Java Network Launching Protocol (JNLP), an XML file format that specifies the application's main class file, its JAR archive, and other things about the program.

By the Way

XML, which stands for Extensible Markup Language, is a way of describing data that's similar in some ways to HTML, the language used to create web pages. You don't need to know anything about XML to create a JNLP file, because the format of JNLP files is relatively self-explanatory.

The next project you will undertake is to use Java Web Start to launch and run the LottoMadness application from Hour 15, "Responding to User Input." To get ready, put a copy of that project's files in your main Java programming folder. The files you need are LottoEvent.class and LottoMadness.class, though you might also want LottoEvent.java and LottoMadness.java, in case you decide to make any changes to the application.

The first thing you must do is package all of an application's class files into a Java Archive (JAR) file along with any other files it needs. If you are using the Software Development Kit, you can create the JAR file with the following command:

jar -cf LottoMadness.jar LottoEvent.class LottoMadness.class

A JAR file called LottoMadness.jar is created that holds both of the class files.

Next you should create an icon graphic for the application, which will be displayed when it is loaded and used as its icon in menus and desktops. The icon can be in either GIF or JPEG format, and should be 64 pixels wide and 64 pixels tall.

For this project, if you don't want to create a new icon, you can download lottobigicon.gif from the book's website. Go to http://www.java24hours.com and open the Hour 17 page. Right-click the lottobigicon.gif link and save the file to the same folder as your LottoMadness.jar file.

The final thing you must do is to create the JNLP file that describes the application. Listing 17.5 contains a JNLP file used to distribute the LottoMadness application. Open your word processor and enter the text of this listing, then save the file as LottoMadness.jnlp.

Listing 17.5. The Full Text of LottoMadness.jnlp

 1: <?xml version="1.0" encoding="utf-8"?>

 2: <!-- JNLP File for LottoMadness Application -->

 3: <jnlp

 4:   codebase="http://www.cadenhead.org/book/java24hours/java"

 5:   href="LottoMadness.jnlp">

 6:   <information>

 7:     <title>LottoMadness Application</title>

 8:     <vendor>Rogers Cadenhead</vendor>

 9:     <homepage href="http://www.java24hours.com"/>

10:     <icon href="lottobigicon.gif"/>

11:     <offline-allowed/>

12:   </information>

13:   <resources>

14:     <j2se version="1.5"/>

15:     <jar href="LottoMadness.jar"/>

16:   </resources>

17:   <application-desc main-class="LottoMadness"/>

18: </jnlp>

The structure of a JNLP file is similar to the HTML markup required to put a Java applet on a web page. Everything within < and > marks is a tag, and tags are placed around the information the tag describes. There's an opening tag before the information and a closing tag after it.

For example, Line 7 of Listing 17.5 contains the following text:

<title>LottoMadness Application</title>

In order from left to right, this line contains the opening tag <title>, the text LottoMadness Application, and the closing tag </title>. The text between the tags—LottoMadness Application— is the title of the application, which will be displayed when it is loaded and used in menus and shortcuts.

The difference between opening tags and closing tags is that closing tags begin with a slash (/) character and opening tags do not. In Line 8, <vendor> is the opening tag, </vendor> is the closing tag, and these tags surround the name of the vendor who created the application. Place your own name within these tags, taking care not to alter the <vendor> or </vendor> tags around it.

Some tags have an opening tag only, such as Line 11:

<offline-allowed/>

The <offline-allowed/> tag indicates that the application can be run even if the user is not connected to the Internet. If it was omitted from the JNLP file, the opposite would be true, and the user would be forced to go online before running this application.

In XML, all tags that do not have a closing tag end with /> instead of >.

Tags also can have attributes, which are another way to define information in an XML file. An attribute is a word inside a tag that is followed by an equals sign and some text within quotes.

For example, consider Line 9 of Listing 17.5:

<homepage href="http://www.java24hours.com"/>

This is the <homepage> tag, and it has one attribute, HRef. The text between the quote marks is used to set the value of this attribute to http://www.java24hours.com. This defines the home page of the application—the web page that users should visit if they want to read more information about the program and how it works.

The LottoMadness JNLP file defines a simple Java Web Start application that does not make use of any Java features that require special permission.

In addition to the tags that have already been described, Listing 17.5 defines other information required by Java Web Start.

Line 1 designates that the file uses XML and the UTF-8 character set. This same line can be used on any of the JNLP files you create for applications.

Line 2 is a comment. Like other comments in Java, it's placed in the file solely for the benefit of humans. Java Web Start will ignore it.

Lines 3–5 indicate where the JNLP file for this application can be found. The codebase attribute in Line 4 is the URL of the folder that contains the JNLP file. The HRef attribute in Line 5 is the name of the file. These lines indicate that the file is at the web address http://www.cadenhead.org/book/java24hours/java/LottoMadness.jnlp.

Lines 6 and 12 use the <information> and </information> tags to surround information about the application. Tags can contain other tags in XML: This tag contains <title>, <vendor>, <homepage>, <icon/>, and <offline-allowed/> tags.

Line 10 indicates the location of the program's icon, which uses the codebase attribute described previously. In this example, the file is at the web address http://www.cadenhead.org/book/java24hours/java/lottobigicon.gif.

Lines 13 and 16 use the <resources> and </resources> tags to surround information about resources used by the application.

Line 14 indicates the version of the Java interpreter that should run the application: 1.5, which sets up the application to use Java 2 version 5 (which has the internal version number 1.5)

Line 15 indicates the application's JAR file. This also uses codebase, so this file is in http://www.cadenhead.org/book/java24hours/java/LottoMadness.jar.

Line 17 indicates which class file should be run to start the application: LottoMadness. Note that the .class file extension is not specified—only the name of the class itself.

Line 18 ends the definition of this JNLP file. All JNLP files must be contained within an opening <jnlp> tag and a closing </jnlp> tag.

After you have created this file, change Line 4 of Listing 17.5 so that it refers to the folder on a web server where your application's JAR file, icon file, and JNLP file will be stored.

Upload all three of the files to this folder, then run your browser and load the JNLP file using its full web address. If your web server is configured to support Java Web Start, the application will be loaded and begin running, as in Figure 17.7.

Figure 17.7. Running LottoMadness using Java Web Start.

If your server does not support Java Web Start, which is more likely than not because it is a relatively new technology, you may see the text of your JNLP file loaded in a page and the application will not open.

A web server must be configured to recognize that JNLP files are a new type of data that should be run as an application, not delivered to the user as text in a browser window. On an Apache web server, the server administrator can support JNLP by adding the following line to the server's mime-types (or .mime-types) file:

application/x-java-jnlp-file JNLP

Watch Out!

If you can't get Java Web Start working on your server, you can test this project on the book's official site. Visit the web page http://www.java24hours.com, open the Hour 17 page, and click the LottoMadness.jnlp link.


Summary

Most of the hours in this book focus on applications, primarily because most Java programmers today don't do a lot of work designing applets for the World Wide Web.

Writing applets is a good way for beginners to develop their skills as Java programmers for the following reasons:

  • Applets are usually smaller in scope, making their creation a less daunting task.

  • You can find thousands of sample applets on the World Wide Web, including many with the source file available from which to learn.

  • You can make applets available to a global audience at low to no cost through the Web, exposing your work to more people who can offer comments and suggestions.


Q&A

Q1:

Is there a reason why the codebase attribute should be used in an applet tag?

A1:

If all Java programs are grouped into their own subfolder, as indicated by codebase, this structure might improve the way a website is organized, but there's no other reason why using codebase is better than omitting it. The choice is a matter of personal preference.

Q2:

What happens if the height and width specified for an applet don't leave enough room for the information that is displayed in the paint() method?

A2:

The information will be drawn off-screen, beyond the edges of the applet window, and won't be visible at any point while the applet runs. Choosing the right dimensions for an applet is largely a matter of trial-and-error until you find the right size for both the height and width attributes of the applet tag. You can't resize an applet window from within a Java program, so the only way to control its size is by using the height and width attributes. Fortu nately, you can change the web page's HTML without having to recompile the Java program.

Q3:

What is the Peter Principle?

A3:

The principle was an idea popularized in the book The Peter Principle: Why Things Always Go Wrong by Laurence Peter with Raymond Hull.

Peter, a Canadian-born author, psychologist and professor, put forth the following principle: In the workplace, every employee rises to his own level of incompetence.

If an employee does a good job, he is repeatedly promoted until he eventually reaches a level where he cannot do the work—and is no longer promoted.

I was promoted to write computer books in 1996 and have remained in the position for nine years.


Quiz

The following questions test your knowledge of applets.

Questions

1:

What type of argument is used with the paint() method?

  1. A Graphics object

  2. A Graphics2D object

  3. None

2:

Which method is handled right before an applet finishes running?

  1. decline()

  2. destroy()

  3. defenestrate()

3:

Why can't all variables needed in an applet be created inside the init() method?

  1. The scope of the variables would be limited to the method only.

  2. Federal legislation prohibits it.

  3. They can be created there without any problems.

Answers

A1: | a. The Graphics object keeps track of the behavior and attributes needed to display things on-screen in the applet window. You might create a Graphics2 object inside the method, but it isn't sent as an argument.
A2: | b.
A3: | a. Variables that are used in more than one method of a class should be created right after the class statement but before any methods begin.


Activities

You can apply your applet programming knowledge with the following activities:

  • Write an applet in which the text that is displayed moves each time the applet window is repainted.

  • Install the Java Plug-in with your preferred browser, if you're on a Windows or Solaris system, and try the sample applets provided from Sun's Java Plug-in page.

To see a Java program that implements the first activity, visit the book's website at http://www.java24hours.com.


Hour 18. Handling Errors in a Program

No subject in this book is less popular than the one you're about to tackle: errors.

Errors—the various bugs, blunders, typos, and other problems that stop a program from running successfully—are a natural part of the software development process. "Natural" is probably the kindest word that has ever been used to describe them—in my own Java programming, when I can't find the cause of an elusive error that keeps my program from working, I use words that would make a gangsta rapper blush.

Some errors are flagged by the compiler and prevent you from creating a class. Others are noted by the interpreter in response to a problem that keeps it from running successfully.

There are two kinds of problems you will encounter in Java:

  • Exceptions— Events that signal an unusual circumstance has taken place as a program runs

  • Errors— Events that signal the interpreter is having problems that may be unrelated to your program

During this hour, we'll explore exceptions as the following topics are discussed:

  • How to use methods that cause exceptions

  • How to respond to exceptions in your Java programs

  • How to create methods that ignore an exception, leaving it for another class to handle

  • How to create your own exceptions

You'll also learn how to keep errors out of your programs using a language feature called assertions.


Exceptions

Although you are just learning about them now, you have probably become well-acquainted with exceptions during the last 17 previous hours. These errors turn up when you write a Java program that compiles successfully but encounters a problem when it runs.

For example, a common programming mistake is to refer to an element of an array that doesn't exist, as in the following statements:

String[] greek = { "Alpha", "Beta", "Gamma" };

System.out.println(greek[3]);

In this example, the String array has three elements. Because the first element in an array is numbered 0 rather than 1, the first element is greek[0], the second is greek[1] and the third is greek[2]. The statement attempting to display the contents of greek[3] is erroneous, because that element does not exist.

The preceding statements will compile successfully, but when you run the program, the Java interpreter will halt with a message such as the following:

Exception in thread "main" java.lang.ArrayIndexOutBoundsException

        at SampleProgram.main(SampleProgram.java:4)

This message indicates that the application has generated an exception, which the interpreter noted by displaying an error message and stopping the program.

The error message includes a reference to a class called ArrayIndexOutOfBoundsException in the java.lang package. This class is an exception, an object that is created to make note of an exceptional circumstance that has taken place in a Java program.

When a Java class encounters an exception, it alerts users of the class to the error. In this example, the user of the class is the Java interpreter.

By the way

Two terms are used to describe this process: throw and catch. Classes and methods can throw exceptions to alert others that they have occurred. These exceptions can be caught by other classes, methods, or the Java interpreter.

All exceptions are subclasses of Exception, another class in the java.lang package. The ArrayIndexOutOfBoundsException does what you would expect—it lets you know you have used an array element outside the array's boundaries.

There are hundreds of exceptions in Java. Many of them indicate a problem that can be fixed with a change in your program, such as the array exception. These are comparable to compiler errors—once you correct the situation, you don't have to concern yourself with the exception any longer.

Other exceptions must be dealt with every time a program runs by using five new statements: try, catch, finally, throw, and throws.

Catching Exceptions in a try-catch Block

Up to this point, you have dealt with exceptions by fixing the problem that caused them. There are times you either can't deal with an exception in that manner or want to handle them within a Java class.

As an introduction to why this is useful, enter the short Java application in Listing 18.1 and save it as SumNumbers.java.

Listing 18.1. The Full Text of SumNumbers.java

1: public class SumNumbers {

2:     public static void main(String[] arguments) {

3:         float sum = 0;

4:         for (int i = 0; i < arguments.length; i++) {

5:             sum = sum + Float.parseFloat(arguments[i]);

6:         }

7:         System.out.println("Those numbers add up to " + sum);

8:     }

9: }

You can compile this application successfully. The SumNumbers application takes one or more numbers as command-line arguments, adds them up, and displays the total.

Because all command-line arguments are represented by strings in a Java application, the program must convert them into floating-point numbers before adding them together. The Float.parseFloat() class method in Line 5 takes care of this, adding the converted number to a variable named sum.

Run the application with the following command (or use another Java tool where you can specify the same seven numeric arguments):

java SumNumbers 8 6 7 5 3 0 9

The application will display the following output:

Those numbers add up to 38.0

Run the program several times with different numbers as arguments. It should handle all of them successfully, which might make you wonder what this has to do with exceptions.

To see the relevance, run the SumNumbers application with the following command:

java SumNumbers 1 3 5x

The third argument in this example contains a typo—there shouldn't be an x after the number 5. The SumNumbers application has no way to know this is a mistake, so it tries to add 5x to the other numbers, causing the following exception to be displayed:

Exception in thread "main" java.lang.NumberFormatException: 5x

        at java.lang.FloatingDecimal.readJavaFormatString(Unknown source)

        at java.lang.Float.parseFloat(Unknown source)

        at SumNumbers.main(SumNumbers:5)

This message is informative to the programmer developing the application, but it's not something you would want a user to see. Java programs can take care of their own exceptions by using a TRy-catch block.

This block statement takes the following form:

try {

    // statements that might cause the exception

} catch (Exception e) {

   // what to do when the exception occurs

}

A TRy-catch block should be used with any exception that you want a program to handle. The Exception object that appears in the catch statement should be one of two things:

  • The class of the exception that might occur

  • A superclass of several different kinds of exceptions that might occur

The TRy section of the TRy-catch block should contain the statement or statements that might throw an exception. In the SumNumbers application, the call to the Float.parseFloat() method in Line 5 will throw a NumberFormatException whenever it is used to convert a non-numeric string to a floating-point value.

To improve the SumNumbers application so that it never stops running with this kind of error, you can use a try-catch block that deals with this exception.

Open your text editor and create an application called NewSumNumbers.java from Listing 18.2.

Listing 18.2. The Full Text of NewSumNumbers.java

 1: public class NewSumNumbers {

 2:     public static void main(String[] arguments) {

 3:         float sum = 0;

 4:         for (int i = 0; i < arguments.length; i++) {

 5:             try {

 6:                 sum = sum + Float.parseFloat(arguments[i]);

 7:             } catch (NumberFormatException e) {

 8:                 System.out.println(arguments[i] + " is not a number.");

 9:             }

10:         }

11:        System.out.println("Those numbers add up to " + sum);

12:     }

13: }

After you save and compile the application, run it with a non-numeric command-line argument along with a few numbers, such as the following:

java NewSumNumbers 1 3 5x

Running it with these arguments produces the following output:

5x is not a number

Those numbers add up to 4.0

The try-catch block in Lines 5–9 deals with NumberFormatException errors that are thrown by the Float.parseFloat() method. These exceptions are caught within the NewSumNumbers class, which displays an error message for any argument that is not a number.

Because the exception is handled within the class, the Java interpreter does not display an error message when something like 5x is used as a command-line argument.

You can often deal with problems related to user input and other unexpected data by using try-catch blocks.

Watch Out!

You also can use TRy and catch to deal with errors that could be fixed by making some changes to your program, such as the ArrayIndexOutOfBoundsException problem that was described earlier this hour. This isn't recommended—the easiest solution is to change your program so the error never occurs.

Catching Several Different Exceptions

TRy-catch blocks can be used to handle several different kinds of exceptions, even if they are thrown by different statements.

Listing 18.3 contains an application called DivideNumbers that takes two integer arguments from the command-line and uses them in a division expression.

This application must be able to deal with two potential problems in user input:

  • Non-numeric arguments

  • Division by zero

Listing 18.3. The Full Text of DivideNumbers.java

 1: public class DivideNumbers {

 2:     public static void main(String[] arguments) {

 3:         if (arguments.length == 2) {

 4:             int result = 0;

 5:             try {

 6:                 result = Integer.parseInt(arguments[0]) /

 7:                     Integer.parseInt(arguments[1]);

 8:                 System.out.println(arguments[0] + " divided by " +

 9:                     arguments[1] + " equals " + result);

10:             } catch (NumberFormatException e) {

11:                 System.out.println("Both arguments must be numbers.");

12:             } catch (ArithmeticException e) {

13:                 System.out.println("You cannot divide by zero.");

14:             }

15:         }

16:     }

17: }

Compile the application and try it out with some integers, floating-point numbers, and non-numeric arguments.

The if statement in Line 3 checks to make sure that two arguments were sent to the application. If not, the program exits without displaying anything.

The DivideNumbers application performs integer division, so the result will be an integer. This isn't going to be as accurate as division using floating-point numbers—in integer division, 5 divided by 2 equals 2, not 2.5.

If you use a floating-point or non-numeric argument, a NumberFormatException will be thrown by Lines 6–7 and caught by Lines 10–11.

If you use an integer as the first argument and a zero as the second argument, a ArithmeticExpression will be thrown in Lines 6–7 and caught by Lines 12–13.

Handling Something After an Exception

When you are dealing with multiple exceptions by using try and catch, there are times when you want the program to do something at the end of the block whether an exception occurred or not.

You can handle this by using a try-catch-finally block, which takes the following form:

try {

    // statements that might cause the exception

} catch (Exception e) {

   // what to do when the exception occurs

} finally {

    // statements to execute no matter what

}

The statement or statements within the finally section of the block will be executed after everything else in the block, even if an exception occurs.

One place this is useful is in a program that reads data from a file on disk, which you will do in Hour 20, "Reading and Writing Files." There are several ways an exception can occur when you are accessing data—the file might not exist, a disk error could occur, and so on. If the statements to read the disk are in a try section and errors are handled in a catch section, you can close the file in the finally section. This makes sure that the file will be closed whether or not an exception was thrown as it was read.

Throwing Exceptions

When you call a method of another class, that class can control how the method is used by throwing exceptions.

As you make use of the classes in the Java class library, the compiler will often display a message such as the following:

NetReader.java:14: unreported exception java.net.MalformedURLException; must be

caught or declared to be thrown

Whenever you see an error stating that an exception "must be caught or declared to be thrown," it indicates that the method you are trying to use throws an exception.

Any class that calls these methods, such as an application that you write, must do one of the following things:

  • Handle the exception with a TRy-catch block.

  • Throw the exception.

  • Handle the exception with a TRy-catch block and then throw it.

Up to this point in the hour, you have seen how to handle exceptions. If you would like to throw an exception after handling it, you can use a tHRow statement followed by the exception object to throw.

The following statements handle a NumberFormatException error in a catch block and then throw the exception:

try {

    principal = Float.parseFloat(loanText) * 1.1F;

} catch (NumberFormatException e) {

    System.out.println(arguments[i] + " is not a number.");

    throw e;

}

When you throw an exception in this manner, it generally means that you have not done everything that needs to be done to take care of the exception.

An example of where this might be useful: Consider a hypothetical program called CreditCardChecker, an application that verifies credit card purchases. This application uses a class called CheckDatabase, which has the following job:

  1. Make a connection to the credit card lender's computer.

  2. Ask that computer whether the customer's credit card number is valid.

  3. Ask the computer whether the customer has enough credit to make the purchase.

As the CheckDatabase class is doing its job, what happens if the credit card lender's computer doesn't answer the phone at all? This kind of error is exactly the kind of thing that the TRy-catch block was designed for, and it is used within CheckDatabase to handle connection errors.

If the CheckDatabase class handles this error by itself, the CreditCardChecker application won't know that the exception took place at all. This isn't a good idea—the application should know when a connection cannot be made so it can report this to the person using the application.

One way to notify the CreditCardChecker application is for CheckDatabase to catch the exception in a catch block, and then throw it again with a throw statement. The exception will be thrown in CheckDatabase, which must then deal with it like any other exception.

Exception handling is a way that classes can communicate with each other in the event of an error or other unusual circumstance.

Ignoring Exceptions

The last technique that will be covered today is the laziest: how to ignore an exception completely.

A method in a class can ignore exceptions by using a throws clause as part of the method definition.

The following method throws a MalformedURLException, an error that can occur when you are working with World Wide Web addresses in a Java program:

public method loadURL(String address) throws MalformedURLException {

    URL page = new URL(address);

    loadWebPage(page);

}

The second statement in this example, URL page = new URL(address); creates a URL object, which represents an address on the Web. The constructor method of the URL class throws a MalformedURLException to indicate that an invalid address was used, so no object can be constructed. The following statement would cause one of these exceptions to be thrown:

URL source = new URL("http:www.java24hours.com");

The string http:www.java24hours.com is not a valid URL. It's missing some punctuation—two slash characters (//) after the colon.

Because the loadURL() method has been declared to throw MalformedURLException errors, it does not have to deal with them inside the method. The responsibility for handling this exception falls to any class that calls the loadURL() method.


Assertions

The assert keyword enables Java programmers to make use of assertions, a technique that's supposed to improve the reliability of software. An assertion is a Boolean true-or-false expression that represents something that should be true at a spot in the program. Here's an example:

assert speed > 55;

This statement asserts that the speed variable has a value greater than 55. It's a way for a programmer to say, "I expect speed to be greater than 55 at this position, and if it isn't, my program would be completely FUBAR."

By the way

FUBAR is an acronym popular among computer programmers that means "fouled up beyond all recognition" or "fouled up beyond all repair." A saltier version that uses a different F word is even more popular.

Assertions are a way to ensure that a program is running as expected.

The assert keyword must be followed by something that produces a Boolean value: an expression, a boolean, or a method that returns a boolean. Three examples:

assert pointX == 0;

assert endOfFileReached;

assert network.disconnected();

If the expression that follows the assert keyword is false, an AssertionError exception will be thrown. You can make these errors more meaningful by specifying an error message in an assert statement. Add a colon and text at the end, as in this example:

assert temperature > 2200 : "Core breach in Sector 12!";

If you're using the JDK interpreter, here's how it responds to an AssertionError exception:

Exception in thread "main" java.lang.AssertionError: Core breach in Sector 12!

    at Nuke.power(Nuke.java:1924)

Assertions are turned off by default in the JDK (and presumably other tools as well).

JDK users must use command-line arguments to turn on assertion support. To compile a class that contains assert statements, use the -source 1.5 option, as in the following example:

javac -source 1.5 Nuke.java

The -source 1.5 option causes the compiler to support assertions in the class file (or files) that it produces. An error will result if you try to compile a program that contains assert statements but do not use this option.

You also must enable assertions when running a Java class with the JDK interpreter. The easiest way to do this is to use the -ea argument, which enables assertions for all classes (except those that are part of the Java class library):

java -ea Nuke

To enable assertions only in one class, follow -ea with a colon and the name of the class, as in this example:

java -ea:Nuke Nuke

To enable assertions only in one package, follow -ea with a colon and the name of the package:

java -ea:com.prefect.power Nuke

Watch Out!

Because anyone can run a Java program with assertions turned off, you shouldn't depend too heavily on them. They're most useful when you run your own code and are testing its reliability.


Workshop: Throwing and Catching Exceptions

For this hour's workshop, you will create a class that uses exceptions to tell another class about an error that has taken place.

The classes in this workshop are HomePage, a class that represents a personal home page on the World Wide Web, and PageCatalog, an application that catalogs these pages.

Enter the text of Listing 18.4 in your text editor, saving it as HomePage.java when you're done.

Listing 18.4. The Full Text of HomePage.java

 1: import java.net.*;

 2:

 3: public class HomePage {

 4:     String owner;

 5:     URL address;

 6:     String category = "none";

 7:

 8:     public HomePage(String inOwner, String inAddress)

 9:         throws MalformedURLException {

10:

11:         owner = inOwner;

12:         address = new URL(inAddress);

13:     }

14:

15:     public HomePage(String inOwner, String inAddress, String inCategory)

16:         throws MalformedURLException {

17:

18:         this(inOwner, inAddress);

19:         category = inCategory;

20:     }

21: }

Save the file and compile it, producing a HomePage class you can use in other programs. This class represents personal web pages on the Web. It has three variables: address, a URL object representing the address of the page; owner, the person who owns the page; and category, a short comment describing the page's primary subject matter.

Like any class that creates URL objects, HomePage must either deal with MalformedURLException errors in a TRy-catch block or declare that it is ignoring these errors.

The class takes the latter course, as shown in Lines 8–9 and Lines 15–16. By using tHRows in the two constructor methods, HomePage removes the need to deal with MalformedURLException errors in any way.

To create an application that uses the HomePage class, return to your text editor and enter Listing 18.5. Save the file as PageCatalog.java.

Listing 18.5. The Full Text of PageCatalog.java

 1: import java.net.*;

 2:

 3: public class PageCatalog {

 4:     public static void main(String[] arguments) {

 5:         HomePage[] catalog = new HomePage[5];

 6:         try {

 7:             catalog[0] = new HomePage("Mark Evanier",

 8:                 "http://www.newsfromme.com", "comic books");

 9:             catalog[1] = new HomePage("Todd Smith",

10:                 "http://www.sharkbitten.com", "music");

11:             catalog[2] = new HomePage("Rogers Cadenhead",

12:                 "http://www.cadenhead.org/workbench", "programming");

13:             catalog[3] = new HomePage("Juan Cole",

14:                 "http://www.juancole.com", "politics");

15:             catalog[4] = new HomePage("Rafe Colburn",

16:                 "www.rc3.org");

17:             for (int i = 0; i < catalog.length; i++) {

18:                 System.out.println(catalog[i].owner + ": " +

19:                     catalog[i].address + " -- " +

20:                     catalog[i].category);

21:             }

22:         } catch (MalformedURLException e) {

23:             System.out.println("Error: " + e.getMessage());

24:         }

25:     }

26: }

When you run the compiled application, the following output will be displayed:

Error: no protocol: www.rc3.org

The PageCatalog application creates an array of HomePage objects and then displays the contents of the array. Each HomePage object is created using up to three arguments:

  • The name of the page's owner

  • The address of the page (as a String, not a URL)

  • The category of the page

The third argument is optional, and it is not used in Lines 15–16.

The constructor methods of the HomePage class throw MalformedURLException errors when they receive a string that cannot be converted into a valid URL object. These exceptions are handled in the PageCatalog application by using a try-catch block.

To correct the problem causing the "no protocol" error, edit Line 16 so that the string begins with the text "http://" like the other web addresses in lines 7–14.

Mark Evanier: http://www.newsfromme.com -- comic books

Todd Smith: http://www.sharkbitten.com -- music

Rogers Cadenhead: http://www.cadenhead.org/workbench -- programming

Juan Cole: http://www.juancole.com -- politics

Rafe Colburn: http://www.rc3.org -- none


Summary

Now that you have put Java's exception-handling techniques to use, I hope the subject of errors is a little more popular than it was at the beginning of the hour.

You can do a lot with these techniques:

  • Catch an exception and deal with it

  • Ignore an exception, leaving it for another class or the Java interpreter to take care of

  • Catch several different exceptions in the same TRy-catch block

  • Throw your own exception

Managing exceptions in your Java programs makes them more reliable, more versatile, and easier to use, because you don't display any cryptic error messages to people who are running your software.

Once you're comfortable handling errors, you can even use assertions to create more of them—as a safeguard against the times when your assumptions about a program are not correct.


Q&A

Q1:

Is it possible to create your own exceptions?

A1:

You can create your own exceptions easily by making them a subclass of an existing exception, such as Exception, the superclass of all exceptions. In a subclass of Exception, there are only two methods you might want to override: Exception() with no arguments and Exception() with a String as an argument. In the latter, the string should be a message describing the error that has occurred.

Q2:

Why doesn't this hour cover how to throw and catch errors in addition to exceptions?

A2:

Java divides problems into Errors and Exceptions because they differ in severity. Exceptions are less severe, so they are something that should be dealt with in your programs using try-catch or throws. Errors, on the other hand, are more serious and can't be dealt with adequately in a program.

Two examples of these errors are stack overflows and out-of-memory errors. These can cause the Java interpreter to crash, and there's no way you can fix them in your own program as the interpreter runs it.

Q3:

In the children's song "This Old Man," what does the old man play knick-knack on when he reaches the number 12?

A3:

The rhymes vary in the song, which originated in the North Country of England during the 18th century.

Some singers even vary the chorus, turning "knick-knack patty-whack" into "nick-nack cadillac."

The old man begins with "he plays two, he plays knick-knack on my shoe," then moves on to the following things: three, knee; four, door or floor; five, hive or drive; six, bricks or sticks; seven, heaven or oven; eight, gate or plate; nine, line or all the time; and ten, hen or now and then.

If he reaches 12, rhyming dictionaries offer only two decent possibilities for the old man: shelf or himself. Because the latter choice would give the song an R rating, it's safe to conclude that he plays knick-knack on my shelf with a knick-knack, paddy whack, give the dog a bone, then goes rolling home.


Quiz

Although this hour is literally filled with errors, see whether you can answer the following questions about them without making any errors of your own.

Questions

1:

How many exceptions can a single catch statement handle?

  1. Only one

  2. Several different exceptions

  3. This answer intentionally left blank.

2:

When will the statements inside a finally section be run?

  1. After a try-catch block that has ended with an exception

  2. After a TRy-catch block that has ended without an exception

  3. Both

3:

With all this talk about throwing and catching, what do the Texas Rangers need to do in the off-season?

  1. Get some more starting pitching

  2. Sign a left-handed power-hitting outfielder who can reach the short porch in right

  3. Bring in some new middle relievers

Answers

A1: | b. An Exception object in the catch statement can handle all exceptions of its own class and its superclasses.
A2: | c. The statement or statements in a finally section always are executed after the rest of a try-catch block, whether or not an exception has occurred.
A3: | a. Every answer is correct, but a. is more correct than the others, and will probably be correct for the next 30 years.


Activities

To see whether you are an exceptional Java programmer, try to make as few errors as possible in the following activities:

  • Modify the DivideNumbers application so that it throws any exceptions that it catches, and run the program to see what happens.

  • There's a try-catch block in the LottoEvent class you created in Hour 15, "Responding to User Input." Use this block as a guide to create your own Sleep class, which handles InterruptedException so other classes like LottoEvent don't need to deal with them.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


Hour 19. Creating a Threaded Program

A computer term that is used often to describe the hectic pace of daily life is multitasking, which means to do more than one thing at once—such as surfing the Web at your desk while participating in a conference call and doing butt crunch exercises to achieve more shapely shanks.

The term multitasking comes from the world of operating systems, where a multitasking computer is one that can run more than one program at a time.

One of the most sophisticated features of the Java language is the ability to write programs that can multitask using objects called threads.

During this hour, you'll learn how to make programs more sophisticated through the use of threads. The following topics will be covered:

  • Using an interface with a program

  • Creating threads

  • Starting, stopping, and pausing threads

  • Catching errors


Threads

In a Java program, each of the simultaneous tasks the computer handles is called a thread, and the overall process is called multithreading. Threading is useful in animation and many other programs.

Threads are a way to organize a program so that it does more than one thing at a time. Each task that must occur simultaneously is placed in its own thread, and this often is accomplished by implementing each task as a separate class.

Threads are represented by the THRead class and the Runnable interface, which are both part of the java.lang package of classes. Because they belong to this package, you don't have to use an import statement to make them available in your programs.

One of the simplest uses of the THRead class is to slow down how fast a program does something.

Slowing Down a Program

The THRead class has a sleep() method that can be called in any program that should stop running for a short period of time. You will often see this technique used in a program that features animation because it prevents images from being displayed faster than the Java interpreter can handle them.

To use the sleep() method, call Thread.sleep() with the number of milliseconds to pause, as in the following statement:

Thread.sleep(5000);

The preceding example will cause the Java interpreter to pause for five seconds before doing anything else. If for some reason the interpreter can't pause that long, an InterruptedException will be thrown by the sleep() method.

For this reason, you must deal with this exception in some manner when using the sleep() method. One way to do this is to place the Thread.sleep() statement inside a TRy-catch block:

try {

    Thread.sleep(5000);

} catch (InterruptedException e) {

    // wake up early

}

When you want a Java program to handle more than one thing at a time, you must organize the program into threads. Your program can have as many threads as needed, and they can all run simultaneously without affecting each other.

Creating a Thread

A Java class that can be run as a thread is often referred to as a threaded class. Although threads can be used to pause a program's execution for a few seconds, they are often used to the opposite reason: to speed up a program. If you put time-consuming tasks in their own threads, the rest of the program runs more quickly. This often is used to prevent a task from slowing down the responsiveness of a program's graphical user interface.

For example, if you have written a Swing application that loads stock market price data from disk and compiles statistics, the most time-consuming task is to load the data from disk. If threads are not used in the application, the program's interface may respond sluggishly as the data is being loaded. This can be extremely frustrating to a user, especially if the person has decided to close the application and return to more pressing matters, like a game of FreeCell.

There are two ways to place a task in its own thread:

  • Put the task in a class that implements the Runnable interface.

  • Put the task in a class that is a subclass of Thread.

To support the Runnable interface, the implements keyword is used when the class is created, as in this example:

public class LoadStocks implements Runnable {

    // body of the class

}

When a class implements an interface, it indicates that the class supports some kind of additional behavior in addition to its own methods.

Classes that implement the Runnable interface must include the run() method, which has the following structure:

public void run() {

   // body of the method

}

The run() method should take care of the task that the thread was created to accomplish. In the stock-analysis example, the run() method could contain statements to load data from disk and compile statistics based on that data.

When a threaded application is run, the statements in its run() method are not executed automatically. Threads can be started and stopped in Java, and a thread won't begin running until you do two things:

  • Create an object of the threaded class by calling the Thread constructor.

  • Start the thread by calling its start() method.

The THRead constructor takes a single argument—the object that contains the thread's run() method. Often, you will use the this keyword as the argument, which indicates that the current class includes the run() method.

Listing 19.1 contains a Java application that displays a sequence of prime numbers in a text area.

Listing 19.1. The Full Text of FindPrimes.java

 1: import java.awt.*;

 2: import javax.swing.*;

 3: import java.awt.event.*;

 4:

 5: class FindPrimes extends JFrame implements Runnable, ActionListener {

 6:     Thread go;

 7:     JLabel howManyLabel = new JLabel("Quantity: ");

 8:     JTextField howMany = new JTextField("400", 10);

 9:     JButton display = new JButton("Display primes");

10:     JTextArea primes = new JTextArea(8, 40);

11:

12:     FindPrimes() {

13:         super("Find Prime Numbers");

14:         setSize(400, 300);

15:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

16:         BorderLayout bord = new BorderLayout();

17:         setLayout(bord);

18:         display.addActionListener(this);

19:

20:         JPanel topPanel = new JPanel();

21:         topPanel.add(howManyLabel);

22:         topPanel.add(howMany);

23:         topPanel.add(display);

24:         add(topPanel, BorderLayout.NORTH);

25:

26:         primes.setLineWrap(true);

27:         JScrollPane textPane = new JScrollPane(primes);

28:         add(textPane, BorderLayout.CENTER);

29:

30:         setVisible(true);

31:     }

32:

33:     public void actionPerformed(ActionEvent evt) {

34:         display.setEnabled(false);

35:         if (go == null) {

36:             go = new Thread(this);

37:             go.start();

38:         }

39:     }

40:

41:     public void run() {

42:         int quantity = Integer.parseInt(howMany.getText());

43:         int numPrimes = 0;

44:         // candidate: the number that might be prime

45:         int candidate = 2;

46:         primes.append("First " + quantity + " primes:");

47:         while (numPrimes < quantity) {

48:             if (isPrime(candidate)) {

49:                 primes.append(candidate + " ");

50:                 numPrimes++;

51:             }

52:             candidate++;

53:         }

54:     }

55:

56:     public static boolean isPrime(int checkNumber) {

57:         double root = Math.sqrt(checkNumber);

58:         for (int i = 2; i <= root; i++) {

59:             if (checkNumber % i == 0) {

60:                 return false;

61:             }

62:         }

63:         return true;

64:     }

65:

66:     public static void main(String[] arguments) {

67:         FindPrimes fp = new FindPrimes();

68:     }

69: }

The FindPrimes application displays a text field, a Display Primes button, and a text area, as shown in Figure 19.1.

Figure 19.1. Running the FindPrimes application.

Most of the statements in the application are used to create the graphical user interface or display a sequence of prime numbers. The following statements are used to implement threads in this program:

  • Line 5: The Runnable interface is supported in the FindPrimes class.

  • Line 6: A THRead object is given a name (go), but isn't created yet.

  • Lines 35–38: If the go thread has a value of null, which indicates the thread hasn't been created yet, a new Thread object is created under the name go. The thread is started by calling the thread's start() method, which causes the run() method of the FindPrimes class to be executed.

  • Lines 41–54: The run() method looks for a sequence of prime numbers beginning with 2, displaying each one in the primes text area component by calling its append() method. The number of primes in the sequence is determined by the value in the howMany text field.


Working with Threads

You can start a thread by calling its start() method, which may lead you to believe that there's also a stop() method to bring it to a halt.

Although Java includes a stop() method in the THRead class, it has been deprecated. In Java, a deprecated element is a class, interface, method, or variable that has been replaced with something that works better. Anything that has been deprecated can still be used, but may be removed from the language entirely in a future version.

Watch Out!

It's a good idea to heed this deprecation warning. Sun Microsystems has deprecated the stop() method because it can cause problems for other threads running in the Java interpreter.

The next project you undertake will show how a thread can be stopped. The remainder of this hour covers an extended project describing the design of a threaded applet. The program you'll be writing will rotate through a list of website titles and the addresses used to visit them.

The title of each page and the web address will be displayed in a continuous cycle. Users will be able to visit the currently displayed site by clicking a button on the applet window. This program operates over a period of time, displaying information about each website in sequence. Because of this time element, threads are the best way to control the program.

Instead of entering this program into your word processor first and learning about it afterward, you'll get a chance to enter the full text of the Revolve applet at the end of the hour. Before then, each section of the program will be described.

The class Declaration

The first thing you need to do in this applet is to use import to make some classes available.

The java.awt group of classes is needed because you'll be using one of them, Graphics2D, to display text onscreen. The java.net group will be used when you work with the web addresses, and the java.applet group is needed when you tell the browser to load a new page. Finally, the java.awt.event group is needed to respond to mouse clicks so a user can visit one of the addresses shown, and the java.awt.swing package is needed because it is used to create the applet window and other user interface elements.

Use the following import statements:

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.net.*;

After you have used import to make some classes available, you're ready to begin the applet with the following statement:

public class Revolve extends JApplet

    implements Runnable, ActionListener {

This statement creates the Revolve class as a subclass of the JApplet class. It also indicates that two interfaces are supported by this class—Runnable and ActionListener. By implementing the Runnable class, you will be able to use a run() method in this applet to make a thread begin running. The ActionListener interface enables the applet to respond to actions the user takes with the mouse. Implementing it enables the actionPerformed() method to be called when a mouse button is clicked.

Setting Up Variables

The first thing to do in the Revolve class is create the variables and objects needed throughout the program. Create two arrays with six elements—an array of String objects called pageTitle and an array of URL objects called pageLink:

String[] pageTitle = new String[6];

URL[] pageLink = new URL[6];

The pageTitle array will store the titles of the six websites that will be displayed. The URL class of objects stores the value of a website address. URL has all the behavior and attributes needed to keep track of a web address and use it to load the page with a web browser. Both of these arrays are set up without any values at this point, so you'll have to provide them later.

The last three things to be created are a Color object named butterscotch, an integer variable called current and a Thread object called runner:

Color butterscotch = new Color(204, 204, 158);

int current = 0;

Thread runner;

Color objects represent colors you can use on fonts, user interface components, and other visual aspects of Swing. You'll find out how to use them during Hour 22, "Using Fonts and Color."

The current variable will be used to keep track of which site is being displayed so you can cycle through the sites. The Thread object runner represents the only thread this program runs. You will call methods of the runner object when you start, stop, and pause the operation of the applet.


Starting with init()

The init() method of an applet automatically is handled once when the applet first starts to run. In this example, this method is used to assign values to the two arrays created for this applet, pageTitle and pageLink. It also is used to create a clickable button that will appear on the applet. The method consists of the following statements:

public void init() {

    pageTitle[0] = "Sun's Java site";

    pageLink[0] = getURL("http://java.sun.com");

    pageTitle[1] = "Cafe au Lait";

    pageLink[1] = getURL("http://www.ibiblio.org/javafaq");

    pageTitle[2] = "JavaWorld";

    pageLink[2] = getURL("http://www.javaworld.com");

    pageTitle[3] = "Java 2 in 24 Hours";

    pageLink[3] = getURL("http://www.java24hours.com");

    pageTitle[4] = "Sams Publishing";

    pageLink[4] = getURL("http://www.samspublishing.com");

    pageTitle[5] = "Workbench";

    pageLink[5] = getURL("http://www.cadenhead.org/workbench");

    Button goButton = new Button("Go");

    goButton.addActionListener(this);

    FlowLayout flow = new FlowLayout();

    setLayout(flow);

    add(goButton);

}

Strings are assigned to the six elements of the pageTitle array, which stores the title of each web page. The elements of the pageLink array are assigned a value returned by the getURL() method, which you will be creating for this program.

The last seven statements of the init() method are used to create a button and place it on the applet window. The button has the name goButton and is labeled with the text Go.


Catching Errors as You Set Up URLs

When you set up a URL object, you must make sure that the text used to set up the address is in a valid format. http://java.sun.com and http:// www.samspublishing.com are valid, but something such as http:www.javaworld.com would not be because of the missing // marks.

The getURL() method takes a string of text as an argument. The string is checked to see whether it's a valid web address, and if it is, the method returns that valid address. If it's erroneous, the method sends back a null value. The following is the getURL() method:

URL getURL(String urlText) {

    URL pageURL = null;

    try {

        pageURL = new URL(getDocumentBase(), urlText);

    }

    catch (MalformedURLException m) { }

    return pageURL;

}

The first line of this method includes three things, in this order:

  • The type of object or variable that is returned by the method— a URL object in this case. If this is void, no information is returned by the method.

  • The name of the method— getURL.

  • The argument or arguments, if any, that this method takes— only one in this example, a String variable called urlText.

The TRy-catch block deals with any MalformedURLException errors that occur when URL objects are created.

If the string variable sent to the method is a valid web address, it will be sent back as a valid URL object. If not, null is returned. Because you were assigning values to six different URL objects in the pageURL array, the getURL() method makes this process easier to do.


Handling Screen Updates in the paint() Method

The paint() method of any applet is executed when the screen needs to be updated. This situation can be caused by the web browser or operating system outside of the applet obscuring part of an applet window or changing its dimensions in some way. The paint() method also can be called manually within an applet when the screen needs to be updated.

If you put a repaint(); statement in an applet, it forces the paint() method to be handled. This statement is a way you can tell the program that you have done something that requires a screen update. For example, if you are writing an animation program and you move an image from one place to another, you need to use repaint(); so the image is shown in its new location.

The Revolve applet has a short paint() method:

public void paint(Graphics screen) {

    Graphics2D screen2D = (Graphics2D) screen;

    screen2D.setColor(butterscotch);

    screen2D.fillRect(0, 0, getSize().width, getSize().height);

    screen2D.setColor(Color.black);

    screen2D.drawString(pageTitle[current], 5, 60);

    screen2D.drawString("" + pageLink[current], 5, 80);

}

The first statement in this method creates a screen2D object that represents the area of the applet window where things such as strings can be drawn. All drawing will be done by calling the methods of this object.

The setColor() method of Graphics2D selects the color that will be used for subsequent drawing. The color is set to butterscotch before a rectangle is drawn that fills the entire applet window. Next, the color is set to black and lines of text are displayed on the screen at the (x,y) positions of (5,60) and (5,80). The first line that is displayed is an element of the pageTitle array. The second line displayed is the address of the URL object, which is stored in the pageLink array. The current variable is used to determine which elements of these arrays to display.


Starting the Thread

One of the objects created for this program is a THRead object called runner. For a thread to get started, a place is needed where the thread is given a value and told to begin running. In this applet, the runner tHRead will start whenever the start() method is handled and stop whenever stop() is handled.

The start() method of an applet is handled at two different times: right after the init() method and every time the program is restarted after being stopped. An applet is stopped any time a user switches from the applet page to another web page. It starts again when a user returns to the original page. The following is the start() method of the Revolve applet:

public void start() {

    if (runner == null) {

        runner = new Thread(this);

        runner.start();

    }

}

This method does only one thing: If the runner thread is not already started, it creates a new runner thread and starts it. The runner object equals null when it has not been started yet, so you can test for this condition with the if statement.

The statement runner = new Thread(this); creates a new THRead object with one argument—the this statement. Using this makes the applet itself the program that will run in the runner thread.

The runner.start(); statement causes the thread to begin running. When a thread begins, the run() method of that thread is handled. Because the runner thread is the applet itself, the run() method of the applet is handled.

Running the Thread

The run() method is where the main work of a thread takes place. It is comparable to the main() block statement of a Java application. In the Revolve applet, the following represents the run() method:

public void run() {

    Thread thisThread = Thread.currentThread();

    while (runner == thisThread) {

        current++;

        if (current > 5) {

            current = 0;

        }

        repaint();

        try {

            Thread.sleep(10000);

        } catch (InterruptedException e) {

            // do nothing

        }

    }

}

The first thing that takes place in the run() method is the creation of a THRead object called thisThread. A class method of the THRead class, currentThread(), is used to set up the value for the thisThread object. The currentThread() method keeps track of the thread that's currently running.

All of the statements in this method are part of a while loop that compares the runner object to the thisThread object. Both of these objects are threads, and as long as they have the same value, the while loop will continue looping. There's no statement inside this loop that causes the runner and thisThread objects to have different values, so it will loop indefinitely unless something outside of the loop changes one of the THRead objects.

The run() method first uses the repaint(); statement to cause the paint() method to be handled. Next, the value of the current variable increases by one, and if current exceeds 5, it is set to 0 again. The current variable is used in the paint() method to determine which website information to display. Changing current causes a different site to be displayed the next time paint() is handled.

This method includes another try-catch statement that handles an error that might occur. The Thread.sleep(10000); statement causes a thread to pause for 10,000 milliseconds. This statement causes the thread to wait long enough for users to read the name of the website and its address. The catch statement takes care of any InterruptedException errors that might occur while the Thread.sleep() statement is being handled. These errors would occur if something interrupted the thread while it was trying to sleep().

Stopping the Thread

The stop() method is handled any time the applet is stopped because the applet's page is exited, and it is the best place to stop the running thread. The stop() method for the Revolve applet contains the following statements:

public void stop() {

    if (runner != null) {

        runner = null;

    }

}

The if statement tests whether the runner object is equal to null. If it is, there isn't an active thread that needs to be stopped. Otherwise, the statement sets runner equal to null.

Setting the runner object to a null value causes it to have a different value than the thisThread object. When this happens, the while loop inside the run() method will stop running.


Handling Mouse Clicks

The last thing to take care of in the Revolve applet is event-handling: Whenever a user clicks the Go button, the web browser should open the website that is listed. This is done with a method called actionPerformed(). The actionPerformed() method is called whenever the button is clicked.

The following is the actionPerformed() method of the Revolve applet:

public void actionPerformed(ActionEvent evt) {

    if (runner != null) {

        runner = null;

    }

    AppletContext browser = getAppletContext();

    if (pageLink[current] != null) {

        browser.showDocument(pageLink[current]);

    }

The first thing that happens in this method is that the runner tHRead is stopped in the same way it was stopped in the applet's stop() method. The next statement creates a new AppletContext object called browser.

An AppletContext object represents the environment in which the applet is being presented—in other words, the page it's located on and the web browser that loaded the page.

The showDocument() method of this object is called with a single argument: a URL object representing a World Wide Web address. If the page represented by pageLink[current] is a valid address, showDocument() is used to request that the browser load the page.


Workshop: Revolving Links

Now that all aspects of the Revolve applet have been described, you're ready to create the program and test it. Run your word processor and create a new file called Revolve.java. Enter the text of Listing 19.2 and save the file when you're done.

Listing 19.2. The Full Text of Revolve.java

 1: import java.applet.*;

 2: import java.awt.*;

 3: import java.awt.event.*;

 4: import javax.swing.*;

 5: import java.net.*;

 6:

 7: public class Revolve extends JApplet

 8:     implements Runnable, ActionListener {

 9:

10:     String[] pageTitle = new String[6];

11:     URL[] pageLink = new URL[6];

12:     Color butterscotch = new Color(255, 204, 158);

13:     int current = 0;

14:     Thread runner;

15:

16:     public void init() {

17:         pageTitle[0] = "Sun's Java site";

18:         pageLink[0] = getURL("http://java.sun.com");

19:         pageTitle[1] = "Cafe au Lait";

20:         pageLink[1] = getURL("http://www.ibiblio.org/javafaq");

21:         pageTitle[2] = "JavaWorld";

22:         pageLink[2] = getURL("http://www.javaworld.com");

23:         pageTitle[3] = "Java 2 in 24 Hours";

24:         pageLink[3] = getURL("http://www.java24hours.com");

25:         pageTitle[4] = "Sams Publishing";

26:         pageLink[4] = getURL("http://www.samspublishing.com");

27:         pageTitle[5] = "Workbench";

28:         pageLink[5] = getURL("http://www.cadenhead.org/workbench");

29:         Button goButton = new Button("Go");

30:         goButton.addActionListener(this);

31:         FlowLayout flow = new FlowLayout();

32:         setLayout(flow);

33:         add(goButton);

34:     }

35:

36:     URL getURL(String urlText) {

37:         URL pageURL = null;

38:         try {

39:             pageURL = new URL(getDocumentBase(), urlText);

40:         } catch (MalformedURLException m) { }

41:         return pageURL;

42:     }

43:

44:     public void paint(Graphics screen) {

45:         Graphics2D screen2D = (Graphics2D) screen;

46:         screen2D.setColor(butterscotch);

47:         screen2D.fillRect(0, 0, getSize().width, getSize().height);

48:         screen2D.setColor(Color.black);

49:         screen2D.drawString(pageTitle[current], 5, 60);

50:         screen2D.drawString("" + pageLink[current], 5, 80);

51:     }

52:

53:     public void start() {

54:         if (runner == null) {

55:             runner = new Thread(this);

56:             runner.start();

57:         }

58:     }

59:

60:     public void run() {

61:         Thread thisThread = Thread.currentThread();

62:         while (runner == thisThread) {

63:             current++;

64:             if (current > 5) {

65:                 current = 0;

66:             }

67:             repaint();

68:             try {

69:                 Thread.sleep(10000);

70:             } catch (InterruptedException e) {

71:                 // do nothing

72:             }

73:         }

74:     }

75:

76:     public void stop() {

77:         if (runner != null) {

78:             runner = null;

79:         }

80:     }

81:

82:     public void actionPerformed(ActionEvent evt) {

83:         if (runner != null) {

84:             runner = null;

85:         }

86:         AppletContext browser = getAppletContext();

87:         if (pageLink[current] != null) {

88:             browser.showDocument(pageLink[current]);

89:         }

90:     }

After you compile this program with the javac compiler tool, you need to create a web page on which to put the applet. Create a new file with your word processor and name it Revolve.html. Enter Listing 19.3 and save the file.

Listing 19.3. The Full Text of Revolve.html

1: <applet code="Revolve.class" width="300" height="100">

2: </applet>

When you're done, you can load this file in appletviewer to see how the different links are displayed. You won't be able to use the Go button to visit any of the links, however, because that isn't supported in appletviewer.

Figure 19.2 shows what the applet looks like in Mozilla Firefox.

Figure 19.2. Displaying revolving links in an applet window.

    Previous Section < Day Day Up > Next Section


Summary

Threads are a powerful concept that is implemented with a small number of classes and interfaces in Java. By supporting multithreading in your applications and applets, you make the programs more responsive and can often speed up how quickly they perform tasks.

Even if you learned nothing else from this hour, you now have a new 21st century term to describe your frenzied lifestyle. Use it in a few sentences to see if it grabs you:

  • Boy, I was really multithreading yesterday after we held up that string of liquor stores."

  • I multithreaded all through lunch, and it gave me gas."

  • Not tonight, dear, I'm multithreading."


Q&A

Q1:

Why isn't javax.swing.JApplet needed in the class statement of the Revolve applet?

A1:

It isn't needed because of the import statement that makes all the javax.awt.swing classes available to the program. The only purpose of import is to make it easier to refer to classes in a program. If you don't use it, you have to use full class references such as javax.swing.JApplet instead of simply JApplet. You could write all of your Java programs without using import, though it would make the source files more difficult to understand.

Q2:

If the Revolve applet only has one thread, what's the point of using threads at all?

A2:

Multithreading has benefits even it's really just one-threading. One of the main benefits is that you can start, stop, and pause a thread from within a program; you don't have the same kind of control without threads. Also, by making an applet a thread, even for a single-thread project, you make it easier to implement additional threads as needed later on.

Q3:

Are there any reasons not to leave a pair of empty brackets after a catch statement, which causes errors to be disregarded?

A3:

It depends on the type of error or exception being caught. In the Revolve applet, you know with both catch statements what the cause of an exception would be. Because of this knowledge, you can handle the error. In the getURL() method, the MalformedURLException would only be caused if the URL sent to the method is invalid.

Q4:

At what point did someone start the modern calendar by declaring, "Well, let's see, Jesus lived 125 years ago, so this is 126 A.D.?"

A4:

That happened in around 532 A.D. when the Scythian monk Dionysius Exiguus overhauled the calendar to stop paying homage to a Roman emperor who persecuted Christians.

In a table indicating when Easter should be celebrated, Exiguus counted years from the birth of Jesus rather than the reign of Emperor Diocletian.

His new system had no year 0, skipping from 1 B.C. (Before Christ) to 1 A.D. (Anno Domini). The concept of zero as a number wouldn't be adopted in Europe for another three centuries.

Some scholars believe that Jesus was born between 7 B.C. and 4 B.C., which throws a wrench into Exiguus' numbering.


Quiz

Set aside your threads (in the Java sense, not the nudity sense), and answer the following questions about multithreading in Java.

Questions

1:

What class must be implemented for a program to use threads?

  1. Runnable

  2. Thread

  3. Applet

2:

If an interface contains three different methods, how many of them must be included in a class that implements the interface?

  1. None of them.

  2. All of them.

  3. I know, but I'm not telling.

3:

You're admiring the work of another programmer who has created a program that handles four simultaneous tasks. What should you tell him?

  1. "That's not half as exciting as the Anna Kournikova screen saver I downloaded off the Web."

  2. "You're the wind beneath my wings."

  3. "Nice threads!"

Answers

A1: | a. Runnable must be used with the implements statement. THRead is used inside a multithreaded program, but it is not needed in the class statement that begins a program.
A2: | b. An interface is a guarantee that the class will include all of the interface's methods.
A3: | c. This compliment could be confusing if the programmer is well-dressed, but let's be honest—what are the chances of that?


Activities

If this long workshop hasn't left you feeling threadbare, expand your skills with the following activities:

  • If you are comfortable with HTML, create your own home page that includes the Revolve applet and six of your own favorite websites. Use the applet along with other graphics and text on the page.

  • Add a button to the FindPrimes application that can stop the thread while the sequence of prime numbers is still being calculated.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


Hour 20. Reading and Writing Files

There are numerous ways to represent data on a computer. You already have worked with one by creating objects—an object includes data in the form of variables and references to objects. It also includes methods that use the data to accomplish tasks.

To work with other kinds of data, such as files on your hard drive and documents on a web server, you can use the classes of the java.io package. The "io" part of its name stands for "input/output" and the classes are used to access a source of data, such as a hard drive, CD-ROM, or the computer's memory.

You can bring data into a program and send data out by using a communications system called streams, or objects that take information from one place to another.

During this hour, you will work with streams to do each of the following:

  • Read bytes from a file into a program

  • Create a new file on your computer

  • Save an array of bytes to a file

  • Make changes to the data stored in a file


Streams

To save data permanently within a Java program, or to retrieve that data later, you must use at least one stream.

A stream is an object that takes information from one source and sends it somewhere else. The name is inspired by water streams that take fish, boats, inner tube riders, and industrial pollutants from one place to another.

Streams connect a diverse variety of sources, including computer programs, hard drives, Internet servers, computer memory, and CD-ROMs. Because all these things use streams, once you learn how to work with one kind of data, you will be able to work with others in the same manner.

During this hour, you will use streams to read and write data stored in files on your computer.

There are two kinds of streams:

  • Input streams, which read data from a source

  • Output streams, which write data to a source

All input and output streams are made up of bytes, individual integers with values ranging from 0 to 255. You can use this format to represent data, such as executable programs, word-processing documents, and MP3 music files, but those are only a small sampling of what bytes can represent. A byte stream is used to read and write this kind of data.

By the Way

Java class files are stored as bytes in a form called bytecode. The Java interpreter runs bytecode, which doesn't actually have to be produced by the Java language. It can run compiled bytecode produced by other languages, including NetRexx and JPython. You also will hear the Java interpreter referred to as the "bytecode interpreter."

A more specialized way to work with data is in the form of characters—individual letters, numbers, punctuation, and the like. A character stream can be used when you are reading and writing a text source.

Whether you work with a stream of bytes, characters, or other kinds of information, the overall process is the same:

  • Create a stream object associated with the data.

  • Call methods of the stream to either put information in the stream or take information out of it.

  • Close the stream by calling the object's close() method.

Files

In Java, files are represented by the File class, which also is part of the java.io package. Files can be read from hard drives, floppy drives, CD-ROMs, and other storage devices.

A File object can represent files that already exist or files you want to create. To create a File object, use the name of the file as the constructor, as in this example:

File bookName = new File("address.dat");

This creates an object for a file named address.dat in the current folder. You also can include a path in the filename:

File bookName = new File("data\address.dat");

By the Way

This example works on a Windows system, which uses the backslash (\) character as a separator in path and filenames. Linux and other Unix-based systems use a forward slash (/) character instead. To write a Java program that refers to files in a way that works regardless of the operating system, use the class variable File.pathSeparator instead of a forward or backslash, as in this statement:

File bookName = new File("data" + File.pathSeparator

    + "address.dat");

Once you have a File object, you can call several useful methods on that object:

  • exists()— true if the file exists, false otherwise

  • getName()— The name of the file, as a String

  • length()— The size of the file, as a long value

  • createNewFile()— Creates a file of the same name, if one does not exist already

  • delete()— Deletes the file, if it exists

  • renameTo(File)— Renames the file, using the name of the File object specified as an argument

You also can use a File object to represent a folder on your system rather than a file. Specify the folder name in the File constructor, which can be absolute (such as "C:\MyDocuments\") or relative (such as "java\database").

Once you have an object representing a folder, you can call its listFiles() method to see what's inside the folder. This method returns an array of File objects representing every file and subfolder it contains.

Reading Data from a Stream

The first project of the hour is to read data from a file using an input stream. You can do this using the FileInputStream class, which represents input streams that will be read as bytes from a file.

You can create a file input stream by specifying a filename or a File object as the argument to the FileInputStream() constructor method.

The file must exist before the file input stream is created. If it doesn't, an IOException will be generated when you try to create the stream. Many of the methods associated with reading and writing files will generate this exception, so it's often convenient to put all statements involving the file in their own TRy-catch block, as in this example:

try {

    File cookie = new File("cookie.web");

    FileInputStream = new FileInputStream(cookie);

    System.out.println("Length of file: " + cookie.length());

} catch (IOException e) {

    System.out.println("Could not read file.");

}

File input streams read data in bytes. You can read a single byte by calling the stream's read() method without an argument. If no more bytes are available in the stream because you have reached the end of the file, a byte value of -1 will be returned.

When you read an input stream, it begins with the first byte in the stream—such as the first byte in a file. You can skip some bytes in a stream by calling its skip() method with one argument: an int representing the number of bytes to skip. The following statement skips the next 1024 bytes in a stream named scanData:

scanData.skip(1024);

If you want to read more than one byte at a time, do the following:

  • Create a byte array that is exactly the size of the number of bytes you want to read.

  • Call the stream's read() method with that array as an argument. The array will be filled with bytes read from the stream.

You will create an application that reads ID3 data from an MP3 audio file. Because MP3 is such a popular format for music files, 128 bytes are often added to the end of an ID3 file to hold information about the song, such as the title, artist, and album it is from.

The ReadID3 application reads an MP3 file using a file input stream, skipping everything but the last 128 bytes. The remaining bytes are examined to see whether they contain ID3 data. If they do, the first three bytes will be the numbers 84, 65, and 71.

By the Way

On the ASCII character set, which is included in the Unicode Standard character set supported by Java, those three numbers represent the capital letters "T," "A," and "G," respectively.

Open the editor you have been using, and enter the text of Listing 20.1. Save the file as ReadID3.java.

Listing 20.1. The Full Text of ReadID3.java

 1: import java.io.*;

 2:

 3: public class ReadID3 {

 4:     public static void main(String[] arguments) {

 5:         try {

 6:             File song = new File(arguments[0]);

 7:             FileInputStream file = new FileInputStream(song);

 8:             int size = (int)song.length();

 9:             file.skip(size - 128);

10:             byte[] last128 = new byte[128];

11:             file.read(last128);

12:             String id3 = new String(last128);

13:             String tag = id3.substring(0, 3);

14:             if (tag.equals("TAG")) {

15:                 System.out.println("Title: " + id3.substring(3, 32));

16:                 System.out.println("Artist: " + id3.substring(33, 62));

17:                 System.out.println("Album: " + id3.substring(63, 91));

18:                 System.out.println("Year: " + id3.substring(93, 97));

19:             } else {

20:                 System.out.println(arguments[0] + " does not contain"

21:                      + " ID3 info.");

22:             }

23:             file.close();

24:         } catch (Exception e) {

25:             System.out.println("Error -- " + e.toString());

26:         }

27:     }

28: }

When you compile this source file, a ReadID3 class file will be created. You can run this class as an application, specifying an MP3 file on your system as a command-line argument. For example:

java ReadID3 "Perfect Silence.mp3"

If you have the song Perfect Silence.mp3 on your system (and you really should), here's an example of what the ReadID3 application will display:

Title: Perfect Silence

Artist: Scapegoat Wax

Album: Swax

Year: 2002

Did you Know?

If you don't have Perfect Silence.mp3 on your computer (a big mistake, in my opinion), you can look for MP3 songs to examine using the Creative Commons that can be examined using Yahoo! Search at http://search.yahoo.com/cc.

Creative Commons is a set of copyright licenses that stipulate how a work such as a song or book can be distributed, edited, or republished. It's a great resource for finding music that's licensed for such use as playback in computer software.

The application reads the last 128 bytes from the MP3 in Lines 10–11 of Listing 20.1, storing them in a byte array. This array is used in Line 12 to create a String object that contains the characters represented by those bytes.

If the first three characters in the string are "TAG," the MP3 file being examined contains ID3 information in a format the application understands.

In Lines 15–18, the string's substring() method is called to display portions of the string. The characters to display are from the ID3 format, which always puts the artist, song, title, and year information in the same positions in the last 128 bytes of an MP3 file.

Some MP3 files either don't contain ID3 information at all or contain ID3 information in a different format than the application can read.

The file Perfect Silence.mp3 will contain readable ID3 information if you created it from a copy of the Swax CD that you purchased, because programs that create MP3 files from audio CDs read song information from a music industry database called CDDB.

After everything related to the ID3 information has been read from the MP3's file input stream, the stream is closed in Line 23. You should always close streams when you are finished with them to conserve resources in the Java interpreter.

By the Way

You may be tempted to find a copy of Perfect Silence.mp3 on a service such as AudioGalaxy, WinMX, or Gnutella, three of the most popular file-sharing services. I can understand this temptation perfectly where "Perfect Silence" is concerned. However, according to a recent report by the Recording Industry Association of America, anyone who downloads MP3 files for CDs you do not own will immediately burst into flame. For this reason, it's better just to buy the CD and make your own legal copy for personal use only. Swax is available at Sam Goody, Turtle's, Amazon.com and other leading retailers.

Buffered Input Streams

One of the ways to improve the performance of a program that reads input streams is to buffer the input. Buffering is the process of saving data in memory for use later when a program needs it. When a Java program needs data from a buffered input stream, it looks in the buffer first, which is faster than reading from a source such as a file.

To use a buffered input stream, you create an input stream such as a FileInputStream object, then use that object to create a buffered stream. Call the BufferedInputStream(InputStream) constructor with the input stream as the only argument. Data will be buffered as it is read from the input stream.

To read from a buffered stream, call its read() method with no arguments. An integer from 0 to 255 will be returned that represents the next byte of data in the stream. If no more bytes are available, -1 is returned instead.

As a demonstration of buffered streams, the next program you create will add a feature to Java that many programmers miss from other languages they have used: console input.

Console input is the ability to read characters from the console (also known as the command-line) while running an application.

The System class, which contains the out variable used in the System.out.print() and System.out.println() statements, has a class variable called in that represents an InputStream object. This object receives input from the keyboard and makes it available as a stream.

You can work with this input stream like any other. The following statement creates a buffered input stream associated with the System.in input stream:

BufferedInputStream bin = new BufferedInputStream(System.in);

The next project, the ReadConsole class, contains a class method you can use to receive console input in any of your Java applications. Enter the text of Listing 20.2 in your editor and save the file as ReadConsole.java.

Listing 20.2. The Full Text of ReadConsole.java

 1: import java.io.*;

 2:

 3: public class ReadConsole {

 4:     public static String readLine() {

 5:         StringBuffer response = new StringBuffer();

 6:         try {

 7:             BufferedInputStream bin = new

 8:                 BufferedInputStream(System.in);

 9:             int in = 0;

10:             char inChar;

11:             do {

12:                 in = bin.read();

13:                 inChar = (char) in;

14:                 if (in != -1) {

15:                     response.append(inChar);

16:                 }

17:             } while ((in != -1) & (inChar != '\n'));

18:             bin.close();

19:             return response.toString();

20:         } catch (IOException e) {

21:             System.out.println("Exception: " + e.getMessage());

22:             return null;

23:         }

24:     }

25:

26:     public static void main(String[] arguments) {

27:         System.out.print("You are standing at the end of the road ");

28:         System.out.print("before a small brick building. Around you ");

29:         System.out.print("is a forest. A small stream flows out of ");

30:         System.out.println("the building and down a gully.\n");

31:         System.out.print("> ");

32:         String input = ReadConsole.readLine();

33:         System.out.println("That's not a verb I recognize.");

34:     }

35: }

The ReadConsole class includes a main() method that demonstrates how it can be used. When you compile and run it as an application, the output should resemble the following:

You are standing at the end of the road before a small brick building.

Around you is a forest. A small stream flows out of the building and

down a gully.

> go north

That's not a verb I recognize.

The ReadConsole class contains one class method, readLine(), which receives characters from the console. When the Enter key is pressed, readLine() returns a String object that contains all the characters that were received.

If you save the ReadConsole class in a folder that is listed in your CLASSPATH environment variable, you can call ReadConsole.readLine() from any Java program that you write.

By the Way

The ReadConsole class is also the world's least satisfying text adventure game. You can't enter the building, wade in the stream, or even wander off. For a more full-featured version of this game, which is called Adventure, visit the Interactive Fiction archive at http://www.wurb.com/if/game/1.


Writing Data to a Stream

In the java.io package, the classes for working with streams come in matched sets. There are FileInputStream and FileOutputStreams classes for working with byte streams, FileReader and FileWriter classes for working with character streams, and many other sets for working with other kinds of stream data.

To begin reading data from a stream of bytes, you first create a File object that will be associated with an output stream. This file doesn't have to exist on your system.

You can create a FileOutputStream in two ways. If you want to append bytes onto an existing file, call the FileOutputStream() constructor method with two arguments: a File object representing the file and the boolean of TRue. The bytes you write to the stream will be tacked onto the end of the file.

If you want to write bytes into a new file, call the FileOutputStream() constructor method with a File object as its only object.

Once you have an output stream, you can call different write() methods to write bytes to it:

  • Call write() with a byte as its only argument to write that byte to the stream.

  • Call write() with a byte array as its only argument to write all of the array's bytes to the stream.

  • Specify three arguments to the write() method: a byte array, an integer representing the first element of the array to write to the stream, and the number of bytes to write.

The following statement creates a byte array with 10 bytes and writes the last five to an output stream:

File dat = new File("data.dat");

FileOutputStream datStream = new FileOutputStream(dat);

byte[] data = new { 5, 12, 4, 13, 3, 15, 2, 17, 1, 18 };

datStream.write(data, 5, 5);

After you have finished writing bytes to a stream, you close it by calling the stream's close() method.


Reading and Writing Configuration Properties

Java programs are more versatile when they can be configured using command-line arguments, as you have demonstrated in several applications created in preceding hours.

The java.util package includes a class, Properties, that enables configuration settings to be loaded from a file.

The file can be read like other file sources in Java:

  • Create a File object that represents the file

  • Create a FileInputStream object from that File object

  • Call load() to retrieve the properties from that input stream

A properties file has a set of property names followed by an equals sign ("=") and their values. Here's an example:

username=lepton

lastCommand=open database

windowSize=32

Each property has its own line, so this sets up properties named username, lastCommand, and windowSize with the values lepton, open database, and 32, respectively.

The following code loads a properties file called config.dat:

File configFile = new File("config.dat");

FileInputStream configStream = new FileInputStream(configFile);

Properties config = new Properties();

config.load(configStream);

Configuration settings, which are called properties, are stored as strings in the Properties object. Each property is identified by a key that's like an applet parameter. The getProperty() method retrieves a property using its key, as in this statement:

String username = config.getProperty("username");

Because properties are stored as strings, you must convert them in some manner to use a numerical value, as in this code:

String windowProp = config.getProperty("windowSize");

int windowSize = 24;

try {

    windowSize = Integer.parseInt(windowProp);

} catch (NumberFormatException exception) {

    // do nothing

}

Properties can be stored by calling the setProperty() method with two arguments—the key and value:

config.setProperty("username", "max");

The altered properties can be stored back to the file:

  • Create a File object that represents the file

  • Create a FileOutputStream object from that File object

  • Call store() to save the properties to that output stream


Workshop: Writing Bytes to an MP3 File

This hour's workshop uses Java's file-handling and property configuration capabilities to clean up web pages. The TagCleaner application transforms all HTML markup tags on pages to upper- or lowercase, making these formatting commands more readable.

Listing 20.3 contains an example web page, test.html, with markup tags capitalized in several different ways.

Listing 20.3. The Full Text of test.html

 1: <HTML>

 2: <Head>

 3: <TITLE>PALINDROME</TITLE>

 4: </head>

 5: <Body BGCOLOR="#FFFFFF">

 6: <div ALIGN="Center">

 7: <P>Dennis and Edna sinned.</P>

 8: </div>

 9: </Body>

10: </HTML>

The HTML markup tags in Listing 20.3 are enclosed within "<" and ">" characters. These tags are not displayed when the page displays in a browser; they dictate the format and positioning of elements on the page.

On the page, some tag names are written in all-caps, others have an initial capital letter, and some are lowercase. HTML is a language that's case insensitive, a programming term that means it doesn't matter how you capitalize something, as long as you spell it properly.

This page loads properly in browsers, but editing the HTML becomes more difficult because tags don't stand out as clearly.

In Listing 20.4, the HTML has been transformed consistently as uppercase.

Listing 20.4. The Full Text of test.html.clean

 1: <HTML>

 2: <HEAD>

 3: <TITLE>PALINDROME</TITLE>

 4: </HEAD>

 5: <BODY BGCOLOR="#FFFFFF">

 6: <DIV ALIGN="Center">

 7: <P>Dennis and Edna sinned.</P>

 8: </DIV>

 9: </BODY>

10: </HTML>

Tag names are hard to miss under the formatting in Listing 20.4.

The TagCleaner application takes configuration settings from a properties file that determines two aspects of the program's performance:

  • Whether to display tags in lowercase or uppercase

  • Whether to display output when the program runs

The properties file, TagCleaner.properties, is contained in Listing 20.5.

Listing 20.5. The Full Text of TagCleaner.properties

1: case=upper

2: hideOutput=false

With the properties file and a web page to use as input, you're ready to create and run the TagCleaner application. Enter the text of Listing 20.6 into an editor and save the file as TagCleaner.java when you're done.

Listing 20.6. The Full Text of TagCleaner.java

 1: import java.io.*;

 2: import java.util.*;

 3:

 4: public class TagCleaner {

 5:

 6:     public static void main(String[] arguments) {

 7:         if (arguments.length < 1) {

 8:             System.out.println("Usage: java TagCleaner filename");

 9:             System.exit(-1);

10:         }

11:         TagCleaner cleaner = new TagCleaner(arguments[0]);

12:     }

13:

14:     public TagCleaner(String filename) {

15:         try {

16:             // load configuration properties

17:             File propFile = new File("TagCleaner.properties");

18:             FileInputStream propStream = new FileInputStream(propFile);

19:             Properties props = new Properties();

20:             props.load(propStream);

21:             String caseProperty = props.getProperty("case");

22:             String hideOutput = props.getProperty("hideOutput");

23:             // set up file input and output

24:             File file = new File(filename);

25:             FileInputStream in = new FileInputStream(file);

26:             File clean = new File(filename + ".clean");

27:             FileOutputStream out = new FileOutputStream(clean);

28:             boolean eof = false;

29:             boolean inTag = false;

30:             boolean inQuote = false;

31:             if (hideOutput.equals("false")) {

32:                 System.out.print("Creating file ... ");

33:             }

34:             while (!eof) {

35:                 int input = in.read();

36:                 if (input == -1) {

37:                     eof = true;

38:                     continue;

39:                 }

40:                 // look for quote characters

41:                 if (input == '"') {

42:                     if (inQuote != true) {

43:                         inQuote = true;

44:                     } else {

45:                         inQuote = false;

46:                     }

47:                 }

48:                 // look for tag opening

49:                 if (input == '<') {

50:                     inTag = true;

51:                 }

52:                 // look for tag closing

53:                 if (input == '>') {

54:                     inTag = false;

55:                     inQuote = false;

56:                 }

57:                 if ((!inTag) | (inQuote)) {

58:                     out.write((char)input);

59:                 } else {

60:                     if (caseProperty.equals("lower")) {

61:                         out.write(Character.toLowerCase((char)input));

62:                     } else {

63:                         out.write(Character.toUpperCase((char)input));

64:                     }

65:                 }

66:             }

67:             in.close();

68:             out.close();

69:             if (hideOutput.equals("false")) {

70:                 System.out.println("done");

71:             }

72:         } catch (Exception e) {

73:             System.out.println("error\n\n" + e.toString());

74:         }

75:     }

76: }

When you're done, compile the file with your Java compiler. The application requires a web page to use as input. This page won't be altered by the application—instead, a transformed version of the page will be saved under a new filename.

Run the application with the name of the page as a command-line argument, as in the following JDK example:

java TagCleaner test.html

The TagCleaner program reads in the page. A file input stream associated with the page is created in Lines 24–25.

The page is read in the while loop contained in Lines 34–66. A boolean variable called eof is used as the condition of the loop. As long as it is equal to false, the loop will continue executing.

In Line 35, a single byte is read. If this byte is equal to -1, the end of the page has been reached, so eof is set to TRue in Lines 36–39, which will cause the loop to end.

The altered version of the page will be written to its own file, which is given the original file's name followed by ".clean" in Line 26. This file is associated with a file output stream in Line 27.

Data is written to the altered page in Lines 57–65.

The TagCleaner application decides whether to capitalize a character based on this rule: If the letter is contained with "<" and ">" tags, change its case, except when it also is contained within quote marks.

The Boolean variables inTag and inQuote keep track of whether the most recently read character from the page is contained within an HTML tag or quote marks.

By the Way

The reason for the exception: Quote marks surround attribute values inside HTML tags that might not be case insensitive. For example, consider this tag to display a graphic on a web page:

<IMG SRC="Mugshot.gif">

An IMG tag displays the file named in its SRC attribute. If you changed an SRC value from Mugshot.gif to mugshot.gif, it would stop displaying the graphics file.


Summary

During this hour, you worked with input streams and output streams that wrote bytes, the simplest way to represent data over a stream.

There are many more classes in the java.io package to work with streams in other ways. There's also a package of classes called java.net that enables you to read and write streams over an Internet connection.

Byte streams can be adapted to many uses, because you can easily convert bytes into other data types, such as integers, characters, and strings.

The first project of this hour, the ReadID3 application, read bytes from a stream and converted them into a string, because it was easier to read the ID3 data in this format from a song such as "Perfect Silence" by Scapegoat Wax off the album Swax.

Have I mentioned yet that you should buy the album?


Q&A

Q1:

Why do some of the byte stream methods in this hour use integers as arguments? Shouldn't they be using byte arguments?

A1:

There's a different between the bytes in a stream and the bytes represented by the byte class. A byte in Java has a value ranging from–128 to 127, while a byte in a stream has a value from 0 to 255. You often have to use int when working with bytes for this reason—it can hold the values 128 to 255, while byte cannot.

Q2:

Can you suggest any good books to expand into basic Java/database interactions with either Oracle or Microsoft SQL? Also, would this be done with JDBC?

A2:

Java software can access relational databases with either Java Database Connectivity (JDBC) or the JDBC-ODBC Bridge. The same techniques are required in either case—your Java class loads a database driver and uses it to connect to the database and make queries.

Sams Teach Yourself Java 2 in 21 Days, Fourth Edition (ISBN 0-672-32628-0), a more advanced book I coauthored with Laura Lemay, devotes a chapter to JDBC and JDBC-ODBC. Sample chapters and more information can be found on the web at http://www.java21days.com.

Since you mentioned Oracle, you ought to take a look at Oracle and Java Development by Bulusu Lakshman (ISBN 0-672-32117-3), also offered by Sams Publishing.

Q3:

What kind of bird are colly birds or calling birds, the fourth present given away in the "12 Days of Christmas"?

A3:

A colly bird is another name for a blackbird. Colly is an 18th century term that means to be dirtied with soot or coal dust.

By the end of the carol, the true love has given the singer 364 gifts, including 36 colly birds. That always seemed a bit excessive to me, like he was feeling guilty about something.


Quiz

To see whether you took a big enough byte from the tree of knowledge during this hour, answer the following questions about input and output streams in Java.

Questions

1:

Which of the following techniques can be used to convert an array of bytes into a string?

  1. Call the array's toString() method.

  2. Convert each byte to a character, and then assign each one to an element in a String array.

  3. Call the String() constructor method with the array as an argument.

2:

What kind of stream is used to read from a file in a Java program?

  1. An input stream

  2. An output stream

  3. Either

3:

What method of the File class can be used to determine the size of a file?

  1. getSize()

  2. read()

  3. length()

Answers

A1: | c. You can deal with each byte individually, as suggested in answer b., but you can easily create strings from other data types.
A2: | a. An input stream is created from a File object or by providing a filename to the input stream's constructor method.
A3: | c. This method returns a long representing the number of bytes in the stream.


Activities

To experience the refreshing feeling of wading through another stream, test the waters with the following activities:

  • Write an application that reads the ID3 tags of all MP3 files in a folder and renames the files using the artist, song, and album information (when it is provided).

  • Write a program that reads a Java source file and writes it back without any changes under a new name.

  • Buy a copy of the album Swax by Scapegoat Wax.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


    Part VI: Creating Multimedia Programs

    HOUR 21 Reading and Writing XML Data

    HOUR 22 Using Fonts and Color

    HOUR 23 Working with Graphics

    HOUR 24 Creating Animation


Hour 21. Reading and Writing XML Data

The rise to prominence of Java in the mid-'90s coincided with another dramatic change in the development of computer software: the introduction of Extensible Markup Language (XML).

XML, a format for organizing and storing data so that it can be read by any program, has become ginormous, to borrow my kids' favorite adjective, which means "gigantically enormous."

Thanks to XML, data can be read and written independently of the software used to create it. This is a welcome change from the bad old days, when every program seemed to have its own proprietary and idiosyncratic format.

XML data can be read with a parser, a program that recognizes the format and can extract portions of the data as needed.

During this hour, you will read and write XML data using the XML Object Model (XOM), a Java class library that can accomplish each of the following tasks:

  • Reading XML from a file

  • Extracting XML elements

  • Collecting a set of child elements

  • Reading attribute values for an XML element

  • Writing an XML file


Creating an XML File

Before exploring XOM, you should learn some things about XML and how it stores data. XML data turns up in countless places—it can be stored to a file, transmitted over an Internet network, and held in a program's memory.

As XML became popular, Sun Microsystems took note of its usefulness by supporting the format. Several classes in the Java 2 class library can read and write XML, including the Properties class in the java.util package, which was covered in the previous hour, "Reading and Writing Files."

A Properties object can be stored as XML rather than in the name=value format covered in the preceding hour.

After the object has been filled with configuration properties, its storeToXML() method saves it to an XML file. This method takes two arguments:

  • A FileOutputStream over which the file should be saved

  • A comment, which can be the empty string "" if the data requires no comment

This hour's first project is a simple application, PropertyFileCreator, that stores configuration properties in XML format. Fire up your favorite programming editor and enter the text of Listing 21.1, saving the result as PropertyFileCreator.java.

Listing 21.1. The Full Text of PropertyFileCreator.java

 1: import java.io.*;

 2: import java.util.*;

 3:

 4: public class PropertyFileCreator {

 5:     public PropertyFileCreator() {

 6:         Properties prop = new Properties();

 7:         prop.setProperty("username", "rcade");

 8:         prop.setProperty("browser", "Mozilla Firefox");

 9:         prop.setProperty("showEmail", "no");

10:         try {

11:             File propFile = new File("properties.xml");

12:             FileOutputStream propStream = new FileOutputStream(propFile);

13:             Date now = new Date();

14:             prop.storeToXML(propStream, "Created on " + now);

15:         } catch (IOException exception) {

16:             System.out.println("Error: " + exception.getMessage());

17:         }

18:     }

19:

20:     public static void main(String[] arguments) {

21:         PropertyFileCreator pfc = new PropertyFileCreator();

22:     }

23: }

Compile the application, which creates a properties file with three settings: the username "rcade", browser "Mozilla Firefox", and showEmail "no".

If the properties had been saved in the other format, it would look like this:

#Created on Sun Jul 10 21:18:33 EDT 2005

# Sun Jul 10 21:18:33 EDT 2005

showEmail=no

browser=Mozilla Firefox

username=rcade

When you run the application, it creates the XML file properties.xml, which is presented in Listing 21.2.

Listing 21.2. The Full Text of properties.xml

 1: <?xml version="1.0" encoding="UTF-8"?>

 2: <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">

 3: <properties>

 4: <comment>Created on Sun Jul 10 21:18:33 EDT 2005</comment>

 5: <entry key="showEmail">no</entry>

 6: <entry key="browser">Mozilla Firefox</entry>

 7: <entry key="username">rcade</entry>

 8: </properties>

XML organizes data in a self-documenting manner, making it possible to understand a great deal about the data simply by looking at it.

As you glance over Listing 21.2, you can tell pretty quickly how it stored the configuration properties. The ?xml and !DOCTYPE tags may be tough to follow, but the rest of the file should be simple to grok.

By the way

The term grok, which means to understand something confidently enough to brag about it, was borrowed from Robert Heinlein's science fiction novel Stranger in a Strange Land, where it was a Martian word that meant "to be one with."

With terms like grok and instances and ternary operators, you're learning a second language as you learn Java, which will be a real help as you work further with fellow programmers. I call it Jargonese.

Data in an XML file is surrounded by tags that look a lot like HTML, the markup language employed on the World Wide Web.

Start tags begin with a "<" character followed by the name of an element and a ">" character, such as <properties> on Line 3 of Listing 21.2.

End tags begin with "<" followed by the same element name and the "/>" characters, such as </properties> on Line 8.

Everything nested within a start tag and end tag is considered to be the element's value.

XML data must have a single root element that encloses all of its data. In Listing 21.2, the root is the properties element defined in Lines 3–18.

An element may contain text, a child element, or multiple child elements. The properties element holds four children: a comment element and three enTRy elements.

Here's the comment element:

<comment>Created on Sun Jul 10 21:18:33 EDT 2005</comment>

This element has the value of the text it encloses: "Created on Sun Jul 10 21:18:33 EDT 2005."

An XML element also can have one or more attributes, which are defined inside its start tag as name="value" pairs. Attributes must be separated by spaces. They provide supplemental information about the element.

Each enTRy element has an attribute and a value:

<entry key="showEmail">no</entry>

This element has the value "no" and a key attribute with the value "showEmail".

One kind of XML element isn't present in Listing 21.2—an element defined entirely as a single tag. These elements begin with the "<" character, followed by the element name and the "/>" characters.

For instance, this element could be present as a child of the properties element:

<inactive/>

Although XML has been described as a format and compared to HTML, it's not actually a language itself. Instead, XML describes how to create data formats specific to the tasks you want to accomplish with a computer program. XML formats are called dialects.

The XML dialect created by Java's Properties class is an example of this. Sun has developed this format for the representation of software configuration settings.

Data that follows the rules of XML formatting is described as well-formed. Software that reads or writes XML must accept well-formed data.

Data also can follow a more meticulous standard called validity. A valid XML file contains the right elements in the right places, requiring some means of defining what the valid elements are.


Reading an XML File

As you have discovered during the first 20 hours, 13 minutes, and 52 seconds of this book, there's a wealth of Java code that's already written for you.

This code simplifies your job greatly. Within the Java 2 class library, you can adopt Swing classes for graphical user interface programming, the java.io classes for file access, java.awt.event to take user input, and take on other classes to do as little actual coding of your own as absolutely necessary.

A vital skill to develop in your Java programming is to learn where to look for Java classes and packages you can employ in your own projects. Reusing a well-developed class library is considerably simpler than coding your own classes from scratch.

Sun Microsystems isn't the only developer producing terrific Java classes, which you'll see during the remainder of this hour by using the XML Object Model (XOM), a class library developed by the computer programmer and book author Elliotte Rusty Harold.

Harold, an expert in both the Java language and XML, grew frustrated with how existing XML libraries worked. (You may be sensing a theme here—Java itself was developed by James Gosling as an expression of his frustration with another language.)

Harold created his own class library that represents XML data as a tree holding each element as a node.

The library can be downloaded from the website http://www.cafeconleche.org/XOM. After downloading and installing the library, you can use it in Java programs by adding the file xom-1.0.jar to your Classpath environment variable.

Watch Out!

XOM has been made available at no cost under an open source license, the GNU Lesser General Public License (LGPL). You can distribute the XOM library without modification with Java applications that rely on it.

You also can make changes to the classes in the library, but you must make these changes available under the LGPL. The full details of the license can be viewed on the Web at http://www.cafeconleche.org/XOM/license.xhtml.

XOM has classes to read and write XML data, saving it to files and other destinations.

The next program that you create is the PropertyFileReader application, which reads the property.xml file that employs Sun's properties XML dialect.

The core classes of the XOM library are in the nu.xom package, made available in your programs with an import statement:

import nu.xom.*;

The Builder class can load and parse XML data in any dialect, as long as it's well-formed.

Here's the code to create a builder and load the properties file with it:

File propFile = new File("properties.xml");

Builder builder = new Builder();

Document doc = builder.build(propFile);

When the builder loads XML data, it makes it available as a Document object, which holds an entire XML document.

The document's root element can be retrieved with its getrootElement() method:

Element root = doc.getRootElement();

The Element class represents a single element. Each element has several methods that can be used to examine its contents:

  • The getFirstChildElement() method grabs the first child matching a specified name.

  • The get() method reads an element matching a specified index, numbered in order from 0 up.

  • The getChildElements() method grabs all of its child elements

  • The getValue() method reads its text

  • The getAttribute() method retrieves one of its attributes

The following statements retrieve the comment element and its value:

Element commentElement = root.FirstChildElement("comment");

comment = commentElement.getValue();

This approach doesn't work when several elements share the same name, as the entry element does.

For those, you can retrieve all of the elements and loop through them with a for loop:

Elements entries = root.getChildElements("entry");

for (int current = 0; current < entries.size(); current++) {

    Element entry = entries.get(current);

}

An element's attribute can be accessed with the getAttribute() method, which takes the attribute's name as an argument:

Attrbute key = entry.getAttribute("key");

Once you have the attribute, its getValue() method reveals the matching value:

String keyValue = key.getValue();

Put all of this together by entering the text of Listing 21.3, saving the code in the source file PropertyFileReader.java.

Listing 21.3. The Full Text of PropertyFileReader.java

 1: import java.io.*;

 2: import nu.xom.*;

 3:

 4: public class PropertyFileReader {

 5:     String comment;

 6:     String username;

 7:     String browser;

 8:     boolean showEmail;

 9:

10:     public PropertyFileReader() throws ParsingException, IOException {

11:         // get the XML document

12:         File propFile = new File("properties.xml");

13:         Builder builder = new Builder();

14:         Document doc = builder.build(propFile);

15:         // get the root element, <properties>

16:         Element root = doc.getRootElement();

17:         // get the <comment> element and store it in a variable

18:         Element commentElement = root.getFirstChildElement("comment");

19:         comment = commentElement.getValue();

20:         // get the <entry> elements

21:         Elements entries = root.getChildElements("entry");

22:         for (int current = 0; current < entries.size(); current++) {

23:             // get current <entry>

24:             Element entry = entries.get(current);

25:             // get entry's key attribute

26:             Attribute key = entry.getAttribute("key");

27:             String keyValue = key.getValue();

28:             // store attribute value in the proper variable

29:             if (keyValue.equals("username")) {

30:                 username = entry.getValue();

31:             }

32:             if (keyValue.equals("browser")) {

33:                 browser = entry.getValue();

34:             }

35:             if (keyValue.equals("showEmail")) {

36:                 String emailValue = entry.getValue();

37:                 if (emailValue.equals("yes")) {

38:                     showEmail = true;

39:                 } else {

40:                     showEmail = false;

41:                 }

42:             }

43:         }

44:     }

45:

46:     public void showProperties() {

47:         System.out.println("\nProperties\n");

48:         System.out.println("Comment: " + comment);

49:         System.out.println("Username: " + username);

50:         System.out.println("Browser: " + browser);

51:         System.out.println("Show Email: " + showEmail);

52:     }

53:

54:     public static void main(String[] arguments) {

55:         try {

56:             PropertyFileReader reader = new PropertyFileReader();

57:             reader.showProperties();

58:         } catch (Exception exception) {

59:             System.out.println("Error: " + exception.getMessage());

60:         }

61:     }

62: }

Compile and run the PropertyFileReader application, which requires no command-line arguments. The program produces the following output, adjusted for the date and time that it was run:

Properties

Comment: Created on Sun Jul 10 21:18:33 EDT 2005

Username: rcade

Browser: Mozilla Firefox

Show Email: false

Watch Out!

You may encounter an error, depending on whether Sun has fixed a problem with the document type declaration file http://java.sun.com/dtd/properties.dtd, which is referenced in Line 2 of Listing 21.2. To resolve the problem, delete this line and save the file.


Workshop: Reading RSS Syndication Feeds

There are hundreds of XML dialects out there representing data in a platform- independent, software-independent manner. One of the most popular is RSS, a format for sharing headlines and links from online news sites, weblogs, and other sources of information.

RSS makes web content available in XML form, perfect for reading in software, in web-accessible files called feeds. There are RSS readers called news aggregators that have been adopted by several million information junkies to track all of their favorite websites. There also are web applications that collect and share RSS items.

The hard-working Builder class in the nu.xom package can load XML over the Internet from any URL:

String rssUrl = "http://search.csmonitor.com/rss/top.rss";

Builder builder = new Builder();

Document doc = builder.build(rssUrl);

This hour's workshop employs this technique to read an RSS 2.0 file, presenting the 15 most recent items.

Open your editor and enter the text of Listing 21.4. Save the result as Aggregator.java.

Listing 21.4. The Full Text of Aggregator.java

 1: import java.io.*;

 2: import nu.xom.*;

 3:

 4: public class Aggregator {

 5:     public String[] title = new String[15];

 6:     public String[] link = new String[15];

 7:     public int count = 0;

 8:

 9:     public Aggregator(String rssUrl) {

10:         try {

11:             // retrieve the XML document

12:             Builder builder = new Builder();

13:             Document doc = builder.build(rssUrl);

14:             // retrieve the document's root element

15:             Element root = doc.getRootElement();

16:             // retrieve the root's channel element

17:             Element channel = root.getFirstChildElement("channel");

18:             // retrieve the item elements in the channel

19:             if (channel != null) {

20:                 Elements items = channel.getChildElements("item");

21:                 for (int current = 0; current < items.size(); current++) {

22:                     if (count > 15) {

23:                         break;

24:                     }

25:                     // retrieve the current item

26:                     Element item = items.get(current);

27:                     Element titleElement = item.getFirstChildElement("title");

28:                     Element linkElement = item.getFirstChildElement("link");

29:                     title[current] = titleElement.getValue();

30:                     link[current] = linkElement.getValue();

31:                     count++;

32:                 }

33:             }

34:         } catch (ParsingException exception) {

35:             System.out.println("XML error: " + exception.getMessage());

36:             exception.printStackTrace();

37:         } catch (IOException ioException) {

38:             System.out.println("IO error: " + ioException.getMessage());

39:             ioException.printStackTrace();

40:         }

41:     }

42:

43:     public void listItems() {

44:         for (int i = 0; i < 15; i++) {

45:             if (title[i] != null) {

46:                 System.out.println("\n" + title[i]);

47:                 System.out.println(link[i]);

48:                 i++;

49:             }

50:         }

51:     }

52:

53:     public static void main(String[] arguments) {

54:         if (arguments.length > 0) {

55:             Aggregator aggie = new Aggregator(arguments[0]);

56:             aggie.listItems();

57:         } else {

58:             System.out.println("Usage: java Aggregator rssUrl");

59:         }

60:     }

61: }

After you compile the application successfully, it can be run with any RSS 2.0 feed. Here's a command to try it with the Top Stories feed from the Christian Science Monitor newspaper:

java Aggregator http://search.csmonitor.com/rss/top.rss

Sample output from the feed follows:

As Britain copes, a massive hunt for London bombers

http://www.csmonitor.com/2005/0711/p07s01-woeu.html

The new Al Qaeda: local franchises

http://www.csmonitor.com/2005/0711/p01s01-woeu.html

Tough job: Can anyone govern California?

http://www.csmonitor.com/2005/0711/p02s01-uspo.html

By the way

You can find out more about the RSS 2.0 XML dialect from the RSS Advisory Board website at http://blogs.law.harvard.edu/tech. The author of this book is a member of the board, which offers guidance on the format and a directory of software that can be used to read RSS feeds.

There also are two other formats with similar functionality and appeal: RSS 1.0 and Atom.


Summary

The Java language liberates software from dependence on a particular operating system. The program you write with the language on a Windows XP box creates class files that can be run on a Linux server or a Mac OS X computer.

Extensible Markup Language, better known as XML, achieves a similar liberation for the data produced by software. If XML data follows the simple rules required to make it well-formed, you can read it with any software that parses XML. You don't need to keep the originating program around just to ensure there's always a way to access it.

The XML Object Model (XOM) library makes it easy to read and write XML data.

When you can grok both Java and XML, you can declare your independence from two of the major obstacles faced by computer programmers for decades—obsolete data and obsolete operating systems.


Q&A

Q1:

What's the purpose of the DOCTYPE statement in the XML file produced by the PropertyFileCreator application?

A1:

That's a reference to a document type definition (DTD), a file that defines the rules XML data must follow to be considered valid in its dialect.

If you load the web page referred to in that statement, http://java.sun.com/dtd/properties.dtd, you'll find references to each of the elements and attributes contained in the XML file produced by the Java 2 library's Properties class.

Although Sun provides this DTD, Java's official documentation indicates that it shouldn't be relied upon when evaluating property configuration data. Parsers are supposed to ignore it.

Q2:

An XML file I want to load in a Java program makes use of indentation. How can I strip this out before reading it?

A2:

You don't need to strip out indentation and other whitespace. These characters are insignificant in XML, so the Builder class will ignore them when parsing an XML document.

The nu.xom package includes a Serializer class that can set the indentation for XML data, formatting it uniformly when writing the data to a file.

Q3:

Why is junk e-mail called spam?

A3:

Spam, which today describes a wide variety of undesirable junk messages cluttering the Internet, was named after a famous Monty Python's Flying Circus skit.

In the skit, a restaurant works Spam luncheon meat into each of its menu choices. Dishes include egg and Spam; bacon and Spam; bacon, sausage, and Spam; and lobster thermidor aux crevettes with a mornay sauce garnished with truffle pate' brandy and a fried egg on top of Spam.

As for the food, the Hormel Company chose the name by combining the words "spices" and "ham."


Quiz

To see whether you took a big enough byte from the tree of knowledge during this hour, answer the following questions about input and output streams in Java.

Questions

1:

Which of the following terms should not be used to complement XML data that is properly formatted?

  1. This data is well-formed.

  2. This data is valid.

  3. This data is dy-no-mite!

2:

What method reads all of the elements that are enclosed within a parent element?

  1. get()

  2. getChildElements()

  3. getFirstChildElement()

3:

What method of the Elements class can be used to determine the number of elements that it contains?

  1. count()

  2. length()

  3. size()

Answers

A1: | c. Well-formed data has properly structured start and end tags, a single root element containing all child elements, and an ?XML declaration at the top. Valid data follows the rules of a particular XML dialect. "Dy-no-mite!" is the catchphrase of the comedian Jimmie "J.J." Walker.
A2: | b. The getChildElements() method returns an Elements object holding all of the elements.
A3: | c. Just like vectors, Elements uses a size() method that provides a count of the items it holds.


Activities

To extend your knowledge of Extensible Markup Language, parse the following activities:

  • Add the configuration settings password and visits to the properties.xml file, giving each of them values, then revise the PropertyFileReader application to display them.

  • Write a program that displays the data contained in shortChanges.xml, an XML document of weblog information available at http://www.weblogs.com/shortChanges.xml.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


Hour 22. Using Fonts and Color

There's no limit to the lengths that people will go to look good, as evidenced by the popularity of botulin toxin injections in the foreheads of beauty seekers. In extremely minute amounts, the poison paralyzes muscles for months, making it impossible for them to wrinkle, dimple, or furrow.

Java programs don't need one of the most deadly substances on Earth to look good. You can dress up the appearance of a graphical application with the Font and Color classes. No self-respecting program would be seen in public without them. You'll learn about these classes during this hour as the following topics are covered:

  • Using fonts in your programs

  • Setting a font's style and size

  • Displaying colors

  • Using the color constants

  • Setting up the background color

  • Using sRGB values to choose colors

  • Using HSB values to choose colors

  • Creating special text effects using colors


Using the Font Class

Colors and fonts are represented in Java by the Color and Font classes, which both belong to the java.awt package. With these classes, you can present text in several different fonts and sizes, and change the colors of text, graphics, and other elements.

One of the principles of object-oriented programming is to make an object work for itself, and the Font and Color objects follow this rule. They store all the information that's needed to display a font or change a color, and they can handle other related tasks that are required.

There are three things you need to know about a font to display it:

  • The typeface of the font: Either a descriptive name (Dialog, DialogInput, Monospaced, SanSerif, or Serif) or an actual font name (such as Arial, Courier New, or Times New Roman)

  • The style of the font: bold, italic, or plain

  • The size of the font, in points

Before you can display text in a certain typeface, style, and point size, you need to create a Font object that holds this information. The following statement creates a 12-point serif italic Font object:

Font currentFont = new Font("Serif", Font.ITALIC, 12);

When selecting a typeface, it's better to choose one of the descriptive names: Serif, SanSerif, and Monospaced. This enables the system running the program to designate one of its own fonts that fits the description.

You can, however, refer to specific fonts, which only will be used if they are installed on the computer of the person running your program.

You choose the style of the font by using one or more constant variables. Specifying the style as Font.PLAIN makes it non-bold and non-italic, Font.BOLD makes it bold, and Font.ITALIC makes it italic. To combine bold and italic, use Font.BOLD+Font.ITALIC, as in the following code:

Font headlineFont = new Font("Courier New", Font.BOLD + Font.ITALIC, 72);

The last argument specifies the point size of the font.

There are several ways to make use of fonts in a Java program:

  • On a graphical user interface, you can call a component's setFont(Font) method, which designates the font as the one that will be used on all subsequent text that is displayed until the font is changed.

  • On a container such as a panel, you can override the paintComponent(Graphics) method and work with the Graphics object to set and display fonts.

  • On an applet window, you can override the paint(Graphics) method as you did on Hour 17, "Creating Interactive Web Programs."

Displaying fonts nicely requires Java's support for anti-aliasing, a graphical technique that draws lines more smoothly. Without the technique, some lines appear jagged, especially in diagonal directions and curves.

In anti-aliased graphics, the color of pixels at the edges of a line are altered in color, making the lines cleaner and less blocky in appearance.

A Swing graphical interface component only employs anti-aliasing when explicitly requested by using a rendering hint.

A Graphics2 object has a setRenderingHint() method that accomplishes this task. The method takes two arguments:

  • The key of the rendering hint

  • The value to associate with that key

These values are instance variables in the RenderingHints class of java.awt.

To activate anti-aliasing, call setRenderingHint() with two arguments:

comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

    RenderingHints.VALUE_ANTIALIAS_ON);

The first project you undertake during this hour draws text on a panel under a graphic. This class draws fonts by overriding a panel's paintComponent() method. Open your word processor and create a new file called Player.java, entering the text of Listing 22.1 in the file.

Listing 22.1. The Full Text of Player.java

 1: import java.awt.*;

 2: import javax.swing.*;

 3:

 4: public class Player extends JFrame {

 5:     public Player() {

 6:         super("Player");

 7:         setSize(294, 396);

 8:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 9:         PlayerPanel fp = new PlayerPanel();

10:         add(fp);

11:         setVisible(true);

12:     }

13:

14:     public static void main(String[] arguments) {

15:         Player frame = new Player();

16:     }

17: }

18:

19: class PlayerPanel extends JPanel {

20:     public PlayerPanel() {

21:         ImageIcon player = new ImageIcon("johnny-evers-1913.jpg");

22:         JLabel playerLabel = new JLabel(player);

23:         add(playerLabel);

24:     }

25:

26:     public void paintComponent(Graphics comp) {

27:         super.paintComponent(comp);

28:         Graphics2D comp2D = (Graphics2D)comp;

29:         comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

30:             RenderingHints.VALUE_ANTIALIAS_ON);

31:         int width = getSize().width;

32:         int height = getSize().height;

33:         Font currentFont = new Font("Dialog", Font.BOLD, 18);

34:         comp2D.setFont(currentFont);

35:         comp2D.drawString("JOHNNY EVERS", width - 155, height - 50);

36:         currentFont = new Font("Dialog", Font.ITALIC, 12);

37:         comp2D.setFont(currentFont);

38:         comp2D.drawString("second baseman", width - 155, height - 30);

39:         currentFont = new Font("Dialog", Font.PLAIN, 12);

40:         comp2D.setFont(currentFont);

41:         comp2D.drawString("CHICAGO CUBS", width - 155, height - 10);

42:     }

After you compile the file with javac or another compiler, you'll need the graphic of Hall of Fame second baseman Johnny Evers. Visit the book's official website at http://www.java24hours.com, then open the Hour 22 page. Right-click the link to johnny-evers-1913.jpg and store it in the same folder as Player.java.

When that's done, run the application. The program should resemble Figure 22.1.

Figure 22.1. Running the Player application.

The Player application is a frame that contains a panel where several strings will be drawn using different font objects. All of the work involving fonts takes place in the PlayerPanel class, which is defined in Lines 19–42.

The paintComponent(Graphics) method of a container functions the same as the paint(Graphics) method in an applet. This method is called automatically whenever the container needs to be redrawn.

The first thing that takes place in the method is the call to super. paintComponent(), which calls the method in the superclass to make sure that everything is set up correctly before you begin drawing in the panel.

Next, to make use of Java2D, the Graphics object is used to create a Graphics2D object called comp2D in Line 28. All subsequent font and drawing methods will be called on this object, such as the call to set up anti-aliasing in Lines 29–30.

A Font object is created in Line 33 that represents a Dialog, bold 18-point font. The setFont() method of comp2D is called to make this the current font.

Next, the drawString(String) method of comp2D is called with the text of a string to display. The same thing happens with different fonts and strings in Lines 36–41.

The Player application uses the width and height of the panel to determine where the text should be drawn. The first text, the name Johnny Evers, is displayed 155 pixels to the left of the right edge and 50 pixels above the bottom edge. If you resize the application window, the text moves accordingly.


Using the Color Class

The simplest way to display a color in a Java program is to use one of the constant variables from the Color class. You can refer to the following constants: black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white, and yellow.

In a panel or applet window, you can set the background color of the component using these constants. The following is an example:

setBackground(Color.orange);

When you want to display text of a certain color or draw other graphics in different colors, you have to use a method that sets up the current color. You can do this from within the paintComponent() method of a container by using a setColor() method, as in the following:

public void paintComponent(Graphics comp) {

    Graphics2D comp2D = (Graphics2D)comp;

    comp2D.setColor(Color.orange);

    comp2D.drawString("Go, Buccaneers!", 5, 50);

}

Unlike the setBackground() method, which can be called directly on a container such as a panel or applet, the setColor() method must be used on an object that can handle a color change. The preceding example shows the setColor() method of the comp2D object being used to change the current color of the container window.


Other Ways to Choose Colors

To use a color not included in the 13 constant variables, you must specify the color's sRGB or HSB values. sRGB, which stands for Standard Red Green Blue, defines a color by the amount of red, green, and blue that is present in the color. Each value ranges from 0, which means there is none of that color, to 255, which means the maximum amount of that color is present. Most graphics editing and drawing programs will identify a color's sRGB values.

If you know a color's sRGB values, you can use it to create a Color object. For example, an sRGB value for dark red is 235 red, 50 green, and 50 blue, and an sRGB value for light orange is 230 red, 220 green, and 0 blue. The following is an example of a panel that displays light orange text on a dark red background:

import java.awt.*;

import javax.swing.*;

public class GoBucs extends JPanel {

    Color lightOrange = new Color(230, 220, 0);

    Color darkRed = new Color(235, 50, 50);

    public void paintComponent(Graphics comp) {

        Graphics2D comp2D = (Graphics2D)comp;

        comp2D.setColor(darkRed);

        comp2D.fillRect(0, 0, 200, 100);

        comp2D.setColor(lightOrange);

        comp2D.drawString("Go, Buccaneers!", 5, 50);

    }

}

This example calls the fillRect() method of Graphics2D to draw a filled-in rectangle using the current color. You will learn more about this method on Hour 23.

By the Way

Light orange on a dark red background isn't any more attractive on a Java program than it was on the National Football League's Tampa Bay Buccaneers, the reason the team now wears brass-and-pewter uniforms.

Using sRGB values enables you to select from more than 16.5 million possible combinations, though most computer monitors only can offer a close approximation for most of them. For guidance on whether burnt-semidark-midnightblue goes well with medium-faded-baby-green, purchase a copy of the upcoming Sams Teach Yourself Color Sense While Waiting in Line at This Bookstore.

Another way to select a color in a Java program is the HSB system, which stands for Hue Saturation Brightness. Each of these values is represented by a floating-point number that ranges from 0.0 to 1.0. The HSB system isn't as commonly supported in graphics software, so you won't be using it as often in your programs as you use sRGB values. However, one thing HSB values are convenient for is changing a color's brightness without changing anything else about the color. You'll see an example of this use and an example of using HSB values to choose a color in this hour's workshop.


Workshop: Displaying a Danger Message

You can use Java to present news headlines and other information in different ways. One special effect you might see on a web page or graphical user interface is text that fades to black. You also might see the reverse—text that brightens from black to white. This hour's workshop uses the Font and Color classes to create text that cycles in brightness from dark to bright. The text looks like an alert about impending danger, so the panel will be called Danger.

To make the class more useful, the text of the warning will be set as an argument to a constructor. The text that will be used in this example warns of a "Core Breach in Sector 12," but you can substitute other threatening text of similar length.

By the Way

If you're at a secure place in your life right now and can't think of any warning message fraught with impending doom, feel free to choose one of the following:

  • "Mother-in-law wants to visit"

  • "Boss approaching"

  • "We have no bananas"

  • "Karaoke contest in 10 minutes"

Create a new file in your word processor called Danger.java. Each section of the class will be described as you enter it. Begin with the following statements:

import java.awt.*;

import javax.swing.*;

public class Danger extends JPanel implements Runnable {

    String text = "No text has been specified";

    float hue = (float) 0.5;

    float saturation = (float) 0.8;

    float brightness = (float) 0.0;

    Font textFont = new Font("Dialog", Font.BOLD, 20);

    int textX;

    Thread runner;

The program begins like most Swing projects you create, by importing packages such as java.awt and javax.swing. The class statement defines Danger as a subclass of the JPanel class. It also uses the implements keyword to indicate that Danger implements the Runnable interface, which is required for all classes that function as threads.

The next several lines define variables and objects that will be used in the class. The string variable text is created with a default value, and it will be used to store the text that should be displayed onscreen. Three floating-point variables are used to store values for a color using its Hue Saturation Brightness ratings. The (float) portion of each line converts the value that follows it into a floating-point number. This conversion must be done because the hue, saturation, and brightness variables must be of type float.

The text of the panel will be displayed in 20-point Dialog bold. To do this, you need to create a Font object to store that font's values. The Font object, called textFont, is created for this purpose. Finally, the integer variable textX will be used when you're centering text from left-to-right on the panel, and a Thread object called runner is created to hold the thread that will run the Danger class.

After inserting a blank line, continue entering the Danger class by entering the constructor method of the class:

public Danger(String warning) {

    text = warning;

    FontMetrics fm = getFontMetrics(textFont);

    textX = 200 - fm.stringWidth(text) / 2;

    runner = new Thread(this);

    runner.start();

}

The constructor is called when objects of this class are created, and then it is never handled again. It's a good place to set up some things that weren't set up as instance or class variables. The first thing that happens is that the contents of warning, the string sent to the constructor, are copied to the text instance variable.

The FontMetrics class measures how wide a line of text will appear when it is displayed. Using the stringWidth() method of FontMetrics, you can place text at a different place in a container depending on how wide it is. The textX variable stores the horizontal position where the text should be displayed.

The last thing that happens in the constructor is the creation of a new THRead object and a call to its start() method, which causes the thread to begin running. The thread is associated with the Danger class because this was used as an argument to the Thread() constructor.

Now continue by entering the paintComponent() method of your class, which is called whenever the Danger panel needs to be updated. After leaving a blank line after the constructor method, enter the following:

public void paintComponent(Graphics comp) {

    Graphics2D comp2D = (Graphics2D) comp;

    comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

        RenderingHints.VALUE_ANTIALIAS_ON);

    comp2D.setColor(Color.black);

    comp2D.fillRect(0, 0, 400, 200);

    Color textColor = Color.getHSBColor(hue, saturation,

        brightness);

    comp2D.setColor(textColor);

    comp2D.setFont(textFont);

    comp2D.drawString(text, textX, 30);

}

The paintComponent() method takes a Graphics object called comp as an argument, and then uses this object to cast a Graphics2D object called comp2D. The comp2D object holds all the information needed to display something onscreen, and it has several methods you'll use.

The Color object called textColor is created using the HSB variables to select the color. The textColor object then becomes the current display color using the setColor() method of screen.

Using the drawString() method of screen2D, the variable text is displayed at the (x,y) position of textX and 30. The color of the text is the current display color.

The paintComponent() method handles most of the display work that takes place during the Danger application. All you have left to add is a method called pause(). Enter a blank line at the end of your program, and then continue with the following statements:

void pause(int duration) {

    try {

        Thread.sleep(duration);

    } catch (InterruptedException e) { }

}

The pause() method, which takes an argument called duration, pauses the thread by calling the Thread.sleep() method with an argument specifying the number of milliseconds to pause. When you are displaying changing graphics or text, you might need pauses of some kind to prevent things from changing too quickly. This pause() method shows one way to create these pauses.

To finish off the Danger class, you need to add a run() method that controls the threaded animation of the text. Add the following statements:

public void run() {

    Thread thisThread = Thread.currentThread();

    while (runner == thisThread) {

        pause(75);

        brightness += 0.05;

        if (brightness > 1) {

            brightness = (float) 0.0;

            pause(75);

        }

        repaint();

    }

}

The run() method begins with the same two statements used in other threaded programs. A THRead object is created that holds the currently running thread, and it is compared to the runner object in a while loop.

This while loop is what causes the animation of the text to take place. The pause(75) statement causes the animation to pause 75 milliseconds between each update of the panel. Without a pause of some kind, the text would flash different colors as quickly as a Java interpreter could handle it.

You have to change the value of the brightness variable for the text to change in brightness. The program increases the variable .05 (a 5% change), and if the variable has reached the maximum brightness of 1.0, it is reset to 0.0. Whenever brightness must be reset to 0.0, the program calls the pause() method.

The last thing that takes place in the run() method's while loop is a call to the repaint() statement. You use this statement any time you need to redraw the container because something has changed. Because the brightness variable changes each time through the while loop, you know there's a need to redisplay the text after every pause. The repaint() statement is a request for Java to call the paintComponent() method.

Save the Danger.java file, which should resemble Listing 22.2. The only difference might be in the way you have indented methods and other statements. That does not have to be changed for the program to run, but indentation and other spacing can make a program easier to understand.

Listing 22.2. The Full Text of Danger.java

 1: import java.awt.*;

 2: import javax.swing.*;

 3:

 4: public class Danger extends JPanel implements Runnable {

 5:     String text = "No text has been specified";

 6:     float hue = (float) 0.5;

 7:     float saturation = (float) 0.8;

 8:     float brightness = (float) 0.0;

 9:     Font textFont = new Font("Dialog", Font.BOLD, 20);

10:     int textX;

11:     Thread runner;

12:

13:     public Danger(String warning) {

14:         text = warning;

15:         FontMetrics fm = getFontMetrics(textFont);

16:         textX = 200 - fm.stringWidth(text) / 2;

17:         runner = new Thread(this);

18:         runner.start();

19:    }

20:

21:    public void paintComponent(Graphics comp) {

22:         Graphics2D comp2D = (Graphics2D) comp;

23:         comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

24:             RenderingHints.VALUE_ANTIALIAS_ON);

25:         comp2D.setColor(Color.black);

26:         comp2D.fillRect(0, 0, 400, 200);

27:         Color textColor = Color.getHSBColor(hue, saturation,

28:             brightness);

29:         comp2D.setColor(textColor);

30:         comp2D.setFont(textFont);

31:         comp2D.drawString(text, textX, 30);

32:     }

33:

34:     void pause(int duration) {

35:         try {

36:             Thread.sleep(duration);

37:         } catch (InterruptedException e) {

38:             // do nothing

39:         }

40:     }

41:

42:     public void run() {

43:         Thread thisThread = Thread.currentThread();

44:         while (runner == thisThread) {

45:             pause(75);

46:             brightness += 0.05;

47:             if (brightness > 1) {

48:                 brightness = (float) 0.0;

49:                 pause(75);

50:             }

51:             repaint();

52:         }

53:     }

After compiling the file with the javac compiler tool, you need to create an application or applet that contains the Danger panel. Create a new file with your word processor called DangerFrame.java, and enter the text of Listing 22.3 into the file.

Listing 22.3. The Full Text of DangerFrame.java

 1: import java.awt.*;

 2: import javax.swing.*;

 3:

 4: public class DangerFrame extends JFrame {

 5:     public DangerFrame () {

 6:         super("Warning!");

 7:         setSize(400, 70);

 8:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 9:         Danger gb = new Danger("Core Breach in Sector 12");

10:         add(gb);

11:         setVisible(true);

12:     }

13:

14:     public static void main(String[] arguments) {

15:         DangerFrame frame = new DangerFrame();

16:     }

17: }

You can change the value in Line 9 to any other menacing sounding text, as long as it is similar in size to Core Breach in Sector 12. Compile and run the file to see the Danger panel in a frame (Figure 22.2).

Figure 22.2. Displaying the Danger panel in an application.

    Previous Section < Day Day Up > Next Section


Summary

Now that you can use Font and Color objects in your programs to change the color scheme, you can no longer feign ignorance when it comes to designing an attractive program. By using fonts and color instead of sticking to the familiar black text on a light gray background, you can draw more attention to elements of your programs and make them more compelling for users.

By combining these features, you're now one step closer to writing programs that look MAH-ve-lous.


Q&A

Q1:

Is there a limit to the point size that can be used for text?

A1:

The limiting factor is the height and width of your component. Point sizes typically range from 9-point text for small lines that are readable to 48-point text for large headlines. Choosing the right size depends on the font typeface as well as the size, so it's largely a matter of trial and error.

Q2:

What happens if a color defined in a Java program can't be displayed on the monitor of someone displaying the program? For example, if my monitor is set to display only 256 colors, what will occur if I choose one of the 16.5 million colors that isn't in those 256?

A2:

When a monitor can't display a color selected with a setColor() or setBackground() method, it shows the closest existing color as a substitute. An example of this kind of substitution is the Danger application, which runs differently depending on the number of colors that can be shown as the text cycles from black to light blue to white.

Q3:

What causes brain freeze, the splitting headache you get when you drink something cold?

A3:

That condition, known medically as "ice cream headache," is caused by the soft palate at the back of your mouth dropping from a warm temperature to a cold one very quickly.

The temperature in the forehead briefly drops a few degrees during the headache, a condition similar to what happens in a migraine. Brain freeze is much less likely to happen on a cold day.

As I tell my kids, the best way to make one go away as quickly as possible is to close your mouth and breathe through your nose, warming up your forehead.


Quiz

Test whether your font and color skills are MAH-ve-lous by answering the following questions.

Questions

1:

Which one of the following is not a constant used to select a color?

  1. Color.cyan

  2. Color.teal

  3. Color.magenta

2:

When you change the color of something and redraw it on a container, what must you do to make it visible?

  1. Use the drawColor() method.

  2. Use the repaint() statement.

  3. Do nothing.

3:

What do the initials HSB stand for?

  1. Hue, Saturation, Brightness

  2. Hue, Shadows, Balance

  3. Lucy in the Sky with Diamonds

Answers

A1: | b. The primary color of the Jacksonville Jaguars, teal, has gone unrepresented in Color.
A2: | b. The call to repaint() causes the paintComponent() method to be called manually.
A3: | a. If c. were the right answer, you could use colors that would only be visible years later during flashbacks.


Activities

To further explore the spectrum of possibilities when using fonts and color in your programs, do the following activities:

  • Create a version of the Danger application with animation speed set by a slider.

  • Add a way to specify the background of the Danger application by sending an argument for the sRGB values of the desired background color.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


Hour 23. Working with Graphics

Graphics can be represented on a computer in several ways. One is to store the image using a file format that approximates what the graphic looks like. For example, if you took a photo of the Californian sasquatch swimming in your pool and scanned it into your computer, you could save it as a JPEG file. The JPEG format is ideal for storing photographic images in reasonably small file sizes.

You also can represent graphics as a series of drawing instructions used to create the image. These are called "vector graphics," and they are becoming popular on the World Wide Web in the form of Macromedia Flash programs. These graphics don't look like photographic images, but they are much smaller in file size and can be redrawn easily at different sizes, making them ideal for animation. If you created a cartoon about the sasquatch, you could save it in a vector format.

Java supports vector graphics through Java2D, the same classes that were used to draw text in different ways in Hour 22, "Using Fonts and Color." You'll get a chance to draw shapes of different colors in a program—everything from rectangles to ovals to lines.

The following subjects will be covered:

  • The drawing methods of the Graphics2D class

  • Drawing lines

  • Drawing rectangles and rounded rectangles

  • Drawing polygons

  • Drawing ellipses

  • Drawing with different colors

  • Drawing filled and unfilled shapes


Using Graphics

This isn't meant as a knock to those of us who enjoy displaying arrays, incrementing variables, or using a constructor method, but let's face it—many subjects in a programming language such as Java tend to be dry.

It's hard to impress your non-programming acquaintances with the way your if-else statement determines which method to use in a mathematical application. When you're on a first date, you won't get far with the anecdote that illustrates how a switch-case block statement handles a variety of circumstances correctly. Nobody ever made a movie about the ternary operator.

Graphics programming is the exception to the rule. When you write a program that does something interesting with graphics, you can have fun with a programming language and impress relatives, friends, and prospective employers at the same time.

Drawing things such as lines and polygons is as easy in a Java program as displaying text. All you need are Graphics and Graphics2D objects to define the drawing surface and objects that represent the things to draw.

The Graphics class stores information required to display something onscreen. The most common use of the class is as an object that represents the area where something can be drawn in a container such as a panel or an applet window.

In a container such as a JPanel component, a Graphics object is sent to the paintComponent() method as an argument:

public void paintComponent(Graphics comp) {

    // ...

}

The same thing happens in the paint() method of an applet:

public void paint(Graphics comp) {

    // ...

}

Both of these methods are called automatically whenever the container must be redrawn. For instance, if you have a Java frame open as an application is running and cover it up with another window, the frame's paintComponent() method will be called when the other window is closed.

Inside these paint methods, you should begin by calling the same method in the superclass, as in the following example:

public void paintComponent(Graphics comp) {

    super.paintComponent(comp);

}

Next, the Graphics object argument can be used to create a Graphics2D object, as in the following statement:

Graphics2D comp2D = (Graphics2D) comp;

Once you have a Graphics2D object, you draw by calling its methods. This Graphics2D object, which is called comp2D in this hour's projects, has methods used to draw text with a command such as the following:

comp2D.drawString("Draw, pardner!", 15, 40);

This statement causes the text Draw, pardner! to be displayed at the (x,y) coordinates of (15,40).

All of the shape- and line-drawing methods work using the same (x,y) coordinate system as text. The (0,0) coordinate is at the upper-left corner of the container. The x values go up as you head to the right, and y values go up as you head downward. You can determine the maximum (x,y) value you can use in an applet with the following statements:

int maxXValue = getSize().width;

int maxYValue = getSize().height;


Drawing Lines and Shapes

Figure 23.1 shows a Java application that illustrates the different things you'll be learning to draw during this hour: lines, rectangles, ellipses, and polygons.

Figure 23.1. Displaying a sign using Java2D graphics.

With the exception of lines, all of the shapes you can draw can be filled or unfilled. A filled shape is drawn with the current color completely filling the space taken up by the shape. Unfilled shapes just draw a border with the current color.

Before you create an application to draw this sign, we'll describe each of the drawing methods. The comp2D object will be used as the Graphics2D object throughout this section.

By the Way

The sign shown in Figure 23.1 is the international symbol that means "Use of Compressed Air Prohibited," another one of the freedoms being stripped from us today like smoking in restaurants, downloading MP3s, and ripping the tags off furniture.

Drawing Lines

A 2D drawing operation in Java requires two steps:

  • An object is created that represents the shape that is being drawn.

  • A method of a Graphics2D object is called to actually draw that shape.

The objects that define shapes all are part of the java.awt.geom package of classes. There are two classes that can be used to create lines: Line2D.Float and Line2D.Double. These classes differ only in the way they are created: One is created using floating-point numbers to specify the beginning (x,y) point and ending (x,y) point of the line, and the other uses double values.

The following statement creates a line from the point (40,200) to the point (70,130):

Line2D.Float ln = new Line2D.Float(40F, 200F, 70F, 130F);

Each of the arguments to the Line2D.Float constructor is a number followed by an F, which indicates that the number is a floating-point value. This is necessary when creating a Line2D.Float object.

By the Way

Line2D.Float may look unusual because it includes a . character as part of the name. Normally, you would expect this to mean that Line2D.Float refers to a variable called Float in the Line2D class. Float actually refers to an inner class that is defined inside the Line2D class. The capital letter that begins the name Float is an indicator that it's something other than a variable, because class and object variable names are either all lowercase or all uppercase. Line2D.Float is treated like any other class. The only difference is the . in the name.

After you create a drawing object of any kind, whether it's a line, ellipse, rectangle, or another shape, it is drawn by calling a method of the Graphics2D class. The draw() method draws the shape as an outline and the fill() method draws it as a filled shape.

The following statement will draw the ln object created in the previous example:

comp2D.draw(ln);

Drawing Rectangles

Rectangles can be filled or unfilled, and they can have rounded corners or square ones. They can be created using the Rectangle2D.Float class and specifying the following four arguments:

  • The x coordinate at the upper left of the rectangle

  • The y coordinate at upper left

  • The width of the rectangle

  • The height

The following statement draws an unfilled rectangle with square corners:

Rectangle2D.Float rr = new

    Rectangle2D.Float(245F, 65F, 20F, 10F);

This statement creates a rectangle with its upper-left corner at the (x,y) coordinate of (245,65). The width of the rectangle is 20 and the height is 10. These dimensions are expressed in pixels, the same unit of measure used for coordinates. To draw this rectangle as an outline, the following statement could be used:

comp2D.draw(rr);

If you want to make the rectangle filled in, use the fill() method instead of draw(), as in this statement:

comp.fill(rr);

You can create rectangles with rounded corners instead of square ones by using the RoundRectangle2D.Float class. The constructor to this class starts with the same four arguments as the Rectangle2D.Float class, and adds the following two arguments:

  • A number of pixels in the x direction away from the corner of the rectangle

  • A number of pixels in the y direction away from the corner

These distances are used to determine where the rounding of the rectangle's corner should begin.

The following statement creates a rounded rectangle:

RoundRectangle2D.Float ro = new RoundRectangle.Float(

    10F, 10F,

    100F, 80F,

    15F, 15F);

This rectangle has its upper-left corner at the (10,10) coordinate. The last two arguments to drawRoundRect() specify that the corner should begin rounding 15 pixels away from the corner at (10,10) as well as the other three corners.

As with other rectangle methods, the third and fourth arguments specify how wide and tall the rectangle should be. In this case, it should be 100 pixels wide and 80 pixels tall.

After the rounded rectangle is created, it is drawn using the draw() and fill() methods of a Graphics2D object.

Drawing Ellipses and Circles

Ellipses and circles can both be created with the same class: Ellipse2D.Float. This class takes four arguments: the (x,y) coordinates of the ellipse and its width and height.

The (x,y) coordinates do not indicate a point at the center of the ellipse or circle, as you might expect. Instead, the (x,y) coordinates, width, and height describe an invisible rectangle that the ellipse fits into. The (x,y) coordinate is the upper-left corner of this rectangle. If it has the same width and height, the ellipse is a circle.

The following statement creates a circle at (245,45) with a height and width of 5 each:

Ellipse2D.Float cir = new Ellipse2D.Float(

    245F, 45F, 5F, 5F);

Drawing this object requires a call to draw(cir) or fill(cir).

Drawing Arcs

Another circular shape you can draw in Java is an arc, a partial ellipse or circle. Arcs are created using the Arc2D.Float class, which has a constructor method with many of the same arguments. You draw the arc by specifying an ellipse, the portion of the ellipse that should be visible (in degrees), and the place the arc should begin on the ellipse.

To create an arc, specify the following integer arguments to the constructor:

  • The x coordinate of the invisible rectangle that the ellipse fits into

  • The y coordinate of the rectangle

  • The width of the rectangle

  • The height of the rectangle

  • The point on the ellipse where the arc should begin (in degrees from 0 to 359)

  • The size of the arc, also in degrees

  • The type of arc it is

The arc's starting point and size range from 0 to 359 degrees in a counterclockwise direction, beginning with 0 degrees at the 3 o'clock position, as shown in Figure 23.2.

Figure 23.2. How arcs are defined in degrees.

The type of arc is specified by using one of three class variables from the Arc2D.Float class: PIE if the arc should be drawn as a slice of a pie graph, CLOSED if the endpoints of the arc should be connected with a straight line, and OPEN if the endpoints should not be connected.

The following statement draws an open arc at (100,50) that is 120 degrees long, begins at the 30-degree mark, and has a height and width of 75 each:

Arc2D.Float smile = new Arc2D.Float(100F, 50F, 75F, 75F,

    30F, 120F, Arc2D.Float.OPEN);

You will work more with arcs later in this hour's workshop.

Drawing Polygons

Polygons are the most complicated shape to create because they have a varying number of points. The first step in creating a polygon is to create a GeneralPath object that will hold it. This object starts off without any points in the polygon being defined:

GeneralPath polly = new GeneralPath();

Once this object is created, its moveTo() method is used to define the first point in the polygon. For a closed polygon, such as an octagon, this can be any of the points. You can also define open polygons, and, in this case, your first point should be one of the end points of the polygon.

The moveTo() method takes two arguments: an x and a y coordinate. This (x,y) coordinate defines the point on the polygon. The following statement is an example:

polly.moveTo(100F, 20F);

After you have established the initial point in this manner, each successive point is added with the lineTo() method. This method also takes an x coordinate and y coordinate as arguments, as in the following statement:

polly.lineTo(80F, 45F);

You can call lineTo() as often as needed to create the sides of the polygon. When you have added the last point, you can close off the polygon by calling the closePath() method with no arguments:

polly.closePath();

If you don't call closePath(), the polygon will be open.

When you have finished creating the shape, it can be drawn with the draw() and fill() methods like any other drawn object.

Drawing Lines of Different Widths

If you tried out all of the drawing operations you have learned about up to this point, you would see that they draw lines that are one pixel wide.

You can change the size of the line by using the BasicStroke class, part of the java.awt package. Objects of this class represent the width of the "drawing pen," and you can create one by calling the BasicStroke(int) constructor, as in the following example:

BasicStroke pen = new BasicStroke(12);

The integer specified in the constructor represents the width of the pen in pixels. Using BasicStroke objects is similar to working with fonts and colors. To draw with a pen you have created, call the setStroke() method of the Graphics2D class with the pen as an argument. The following example creates a 3-pixel wide stroke and assigns it to a Graphics2D object called comp2D:

BasicStroke brush = new BasicStroke(3);

comp2D.setStroke(brush);

Everything you draw will use the pen until you select a different one.

Creating the Sign

To put all of these shapes together, load your word processor and create a new file called Sign.java. Enter Listing 23.1 into the file and save it when you're done.

Listing 23.1. The Full Text of Sign.java

 1: import java.awt.*;

 2: import javax.swing.*;

 3: import java.awt.geom.*;

 4:

 5: public class Sign extends JFrame {

 6:     public Sign() {

 7:         super("Use of Compressed Air Prohibited");

 8:         setSize(410, 435);

 9:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

10:         SignPanel sp = new SignPanel();

11:         add(sp);

12:         setVisible(true);

13:     }

14:

15:     public static void main(String[] arguments) {

16:         Sign sign = new Sign();

17:     }

18: }

19:

20: class SignPanel extends JPanel {

21:     public void paintComponent(Graphics comp) {

22:         super.paintComponent(comp);

23:         Graphics2D comp2D = (Graphics2D) comp;

24:         comp2D.setColor(Color.white);

25:         comp2D.fillRect(0, 0, 400, 400);

26:

27:         // draw sign

28:         comp2D.setColor(Color.red);

29:         Ellipse2D.Float sign1 = new Ellipse2D.Float(0F, 0F, 400F, 400F);

30:         comp2D.fill(sign1);

31:         comp2D.setColor(Color.white);

32:         Ellipse2D.Float sign2 = new Ellipse2D.Float(55F, 55F, 290F, 290F);

33:         comp2D.fill(sign2);

34:

35:         // draw man

36:         comp2D.setColor(Color.black);

37:         Ellipse2D.Float head = new Ellipse2D.Float(160F, 96F, 32F, 32F);

38:         comp2D.fill(head);

39:         GeneralPath body = new GeneralPath();

40:         body.moveTo(159F, 162F);

41:         body.lineTo(119F, 303F);

42:         body.lineTo(139F, 303F);

43:         body.lineTo(168F, 231F);

44:         body.lineTo(190F, 303F);

45:         body.lineTo(213F, 303F);

46:         body.lineTo(189F, 205F);

47:         body.lineTo(203F, 162F);

48:         body.lineTo(247F, 151F);

49:         body.lineTo(236F, 115F);

50:         body.lineTo(222F, 118F);

51:         body.lineTo(231F, 140F);

52:         body.lineTo(141F, 140F);

53:         body.lineTo(101F, 190F);

54:         body.lineTo(112F, 197F);

55:         body.lineTo(144F, 162F);

56:         body.closePath();

57:         comp2D.fill(body);

58:

59:         // draw can

60:         comp2D.setColor(Color.black);

61:         comp2D.fillRect(251, 191, 33, 118);

62:         comp2D.fillRect(262, 160, 13, 31);

63:         GeneralPath nozzle = new GeneralPath();

64:         nozzle.moveTo(252F, 176F);

65:         nozzle.lineTo(262F, 160F);

66:         nozzle.lineTo(262F, 176F);

67:         nozzle.closePath();

68:         comp2D.fill(nozzle);

69:

70:         // draw lines

71:         comp2D.setColor(Color.black);

72:         BasicStroke pen = new BasicStroke(2F);

73:         comp2D.setStroke(pen);

74:         Line2D.Float ln1 = new Line2D.Float(203F, 121F, 255F, 102F);

75:         comp2D.draw(ln1);

76:         Line2D.Float ln2 = new Line2D.Float(255F, 102F, 272F, 116F);

77:         comp2D.draw(ln2);

78:         Line2D.Float ln3 = new Line2D.Float(272F, 134F, 252F, 158F);

79:         comp2D.draw(ln3);

80:

81:         // finish sign

82:         comp2D.setColor(Color.red);

83:         GeneralPath sign3 = new GeneralPath();

84:         sign3.moveTo(110F, 78F);

85:         sign3.lineTo(321F, 289F);

86:         sign3.lineTo(290F, 317F);

87:         sign3.lineTo(81F, 107F);

88:         sign3.closePath();

89:         comp2D.fill(sign3);

90:     }

91: }

After compiling the program successfully, run it at the command line. The end result was displayed in Figure 23.1.


Workshop: Baking a Pie Graph

To draw this hour to a close, you will create PiePanel, a graphical user interface component that displays a pie graph. This component will be a subclass of JPanel, a simple Swing container that's useful as a place to draw something.

One way to begin creating a class is to define the way objects of the class will be created. Programs that use the PiePanel class must undertake the following steps:

  • Create a PiePanel object by using the constructor method PiePanel(int). The integer specified as an argument is the number of slices the pie graph will contain.

  • Call the object's addSlice(Color, float) method to give a slice the designated color and value.

The value of each slice in PiePanel is the quantity represented by that slice.

For example, Table 23.1 displays data about the status of student loan repayments in the U.S. from the start of the program in 1959 through November 1997, according to Congressional testimony by David A. Longanecker of the Office of Postsecondary Education.

Table 23.1. U.S. Student Loan Repayments

Amount repaid by students

$101 billion

Amount loaned to students still in school

$68 billion

Amount loaned to students making payments

$91 billion

Amount loaned to students who defaulted

$25 billion

You could use PiePanel to represent this data in a pie graph with the following statements:

PiePanel loans = new PiePanel(4);

loans.addSlice(Color.green, 101F);

loans.addSlice(Color.yellow, 68F);

loans.addSlice(Color.blue, 91F);

loans.addSlice(Color.red, 25F);

Figure 23.3 shows the result in an applet that contains one component: a PiePanel created with the student loan data.

Figure 23.3. Displaying student loan data on a pie graph.

[View full size image]

When a PiePanel object is created, the number of slices is specified in the constructor. You need to know three more things to be able to draw each slice:

  • The color of the slice, represented by a Color object

  • The value represented by each slice

  • The total value represented by all slices

A new helper class, PieSlice, will be used to represent each slice in the pie graph:

class PieSlice {

    Color color = Color.lightGray;

    float size = 0;

    PieSlice(Color pColor, float pSize) {

        color = pColor;

        size = pSize;

    }

}

Each slice is constructed by calling PieSlice(Color, float). The combined value of all slices will be stored as a private instance variable of the PiePanel class, totalSize. There also will be instance variables for the panel's background color (background) and a counter used to keep track of slices (current):

private int current = 0;

private float totalSize = 0;

private Color background;

Now that you have a PieSlice class to work with, you can create an array of PieSlice objects with another instance variable:

private PieSlice[] slice;

When a PiePanel object is created, none of the slices have been assigned a color or size. The only things that must be done in the constructor are defining the size of the slice array and saving the background color of the panel:

public PiePanel(int sliceCount) {

    slice = new PieSlice[sliceCount];

    background = getBackground();

}

The addSlice(Color, float) method is used to add a slice of the pie to the panel:

public void addSlice(Color sColor, float sSize) {

    if (current <= slice.length) {

        slice[current] = new PieSlice(sColor, sSize);

        totalSize += sSize;

        current++;

    }

}

The current instance variable is used to put each slice into its own element of the slice array. The length variable of an array contains the number of elements the array has been defined to hold, so as long as current is not larger than slice.length, you can continue adding slices to the panel.

The PiePanel class handles all graphical operations in its paintComponent(Graphics) method, as you might expect. The trickiest thing about this task is drawing the arcs that represent each slice of the pie.

This is handled in the following statements:

float start = 0;

for (int i = 0; i < slice.length; i++) {

    float extent = slice[i].size * 360F / totalSize;

    comp2D.setColor(slice[i].color);

    Arc2D.Float drawSlice = new Arc2D.Float(

        xInset, yInset, width, height, start, extent,

        Arc2D.Float.PIE);

    start += extent;

    comp2D.fill(drawSlice);

}

The start variable keeps track of where to start drawing an arc, and extent keeps track of the size of an arc. If you know the total size of all pie slices and the size of a specific slice, you can figure out extent by multiplying the arc's size by 360 and dividing that by the total of all slices.

All of the arcs are drawn in a for loop: After each arc's extent is calculated, the arc is created and then extent is added to start. This causes each slice to begin right next to the last one. A call to the Graphics2D method fill() draws the arc.

To bring all of this together, load your word processor and create a new file called PiePanel.java. Enter the full text of Listing 23.2, and then save and compile the file when you're done.

Listing 23.2. The Full Text of PiePanel.java

 1: import java.awt.*;

 2: import javax.swing.*;

 3: import java.awt.geom.*;

 4:

 5: public class PiePanel extends JPanel {

 6:     private PieSlice[] slice;

 7:     private int current = 0;

 8:     private float totalSize = 0;

 9:     private Color background;

10:

11:     public PiePanel(int sliceCount) {

12:         slice = new PieSlice[sliceCount];

13:         background = getBackground();

14:     }

15:

16:     public void addSlice(Color sColor, float sSize) {

17:         if (current <= slice.length) {

18:             slice[current] = new PieSlice(sColor, sSize);

19:             totalSize += sSize;

20:             current++;

21:         }

22:     }

23:

24:     public void paintComponent(Graphics comp) {

25:         super.paintComponent(comp);

26:         Graphics2D comp2D = (Graphics2D) comp;

27:         int width = getSize().width - 10;

28:         int height = getSize().height - 15;

29:         int xInset = 5;

30:         int yInset = 5;

31:         if (width < 5) {

32:             xInset = width;

33:         }

34:         if (height < 5) {

35:             yInset = height;

36:         }

37:         comp2D.setColor(background);

38:         comp2D.fillRect(0, 0, getSize().width, getSize().height);

39:         comp2D.setColor(Color.lightGray);

40:         Ellipse2D.Float pie = new Ellipse2D.Float(

41:             xInset, yInset, width, height);

42:         comp2D.fill(pie);

43:         float start = 0;

44:         for (int i = 0; i < slice.length; i++) {

45:             float extent = slice[i].size * 360F / totalSize;

46:             comp2D.setColor(slice[i].color);

47:             Arc2D.Float drawSlice = new Arc2D.Float(

48:                 xInset, yInset, width, height, start, extent,

49:                 Arc2D.Float.PIE);

50:             start += extent;

51:             comp2D.fill(drawSlice);

52:         }

53:     }

54: }

55:

56: class PieSlice {

57:     Color color = Color.lightGray;

58:     float size = 0;

59:

60:     PieSlice(Color pColor, float pSize) {

61:         color = pColor;

62:         size = pSize;

63:     }

64: }

After you save and compile the file, you will have a PiePanel class that can be added as a component to any Java program's graphical user interface. You can't run the class directly, so to test PiePanel, you need to create a class that uses it.

Listing 23.3 contains an applet that uses these panels, PieApplet.

Listing 23.3. The Full Text of PieApplet.java

 1: import java.awt.*;

 2: import javax.swing.*;

 3:

 4: public class PieApplet extends JApplet {

 5:     Color uneasyBeingGreen = new Color(0xCC, 0xCC, 0x99);

 6:     Color zuzusPetals = new Color(0xCC, 0x66, 0xFF);

 7:     Color zootSuit = new Color(0x66, 0x66, 0x99);

 8:     Color sweetHomeAvocado = new Color(0x66, 0x99, 0x66);

 9:     Color shrinkingViolet = new Color(0x66, 0x66, 0x99);

10:     Color miamiNice = new Color(0x33, 0xFF, 0xFF);

11:     Color inBetweenGreen = new Color(0x00, 0x99, 0x66);

12:     Color norwegianBlue = new Color(0x33, 0xCC, 0xCC);

13:     Color purpleRain = new Color(0x66, 0x33, 0x99);

14:     Color freckle = new Color (0x99, 0x66, 0x33);

15:

16:     public void init() {

17:         PiePanel pie = new PiePanel(10);

18:         pie.addSlice(uneasyBeingGreen, 1306);

19:         pie.addSlice(zuzusPetals, 1080);

20:         pie.addSlice(zootSuit, 296);

21:         pie.addSlice(sweetHomeAvocado, 242);

22:         pie.addSlice(shrinkingViolet, 186);

23:         pie.addSlice(miamiNice, 162);

24:         pie.addSlice(inBetweenGreen, 144);

25:         pie.addSlice(norwegianBlue, 143);

26:         pie.addSlice(purpleRain, 129);

27:         pie.addSlice(freckle, 127);

28:         add(pie);

29:     }

30: }

After compiling this applet, create a simple web page that contains it by entering Listing 23.4 and saving it as PieApplet.html.

Listing 23.4. The Full Text of PieApplet.html

1: <applet code="PieApplet.class" width="300" height="200">

2: </applet>

The PieApplet applet displays a pie graph showing the population of the 10 most populated countries (in millions), using figures from a June 2005 U.S. Census International Data Base report. In order, they are China (1.306 billion), India (1.080 billion), the United States (296 million), Indonesia (242 million), Brazil (186 million), Pakistan (162 million), Bangladesh (144 million), Russia (143 million), Nigeria (129 million), and Japan (127 million).

Because Java only has a few colors defined in the Color class, 10 new ones were created for use here and given descriptive names. The colors are expressed as hexadecimal values—in Java, hexadecimal numbers are preceded by 0x—but they could also have been specified as decimal values in each Color() constructor.

Figure 23.4 shows what this applet should look like in a browser such as Internet Explorer.

Figure 23.4. Displaying population figures in a pie graph.

When you are viewing the PieApplet program, resize the applet window—the pie graph will be redrawn with dimensions that match the new size. This occurs because the (x,y), height, and width variables of the arcs use variables that are based on the size of the PiePanel. When the applet window is resized, Java resizes the panel also. These variables are defined in Lines 26–33 of Listing 23.2 by calling the component's getSize() method, which returns a Dimension object that has height and width instance variables describing how big the component is.

By the Way

The names and hexadecimal values for the colors are from Hexadecimal Hues, a site devoted to assigning off-the-wall names to all the colors that can be used on the World Wide Web. To see more, visit the page http://tools.firmlist.com/hexagonalhues.

You can find the current U.S. Census world population figures by visiting the web page http://www.census.gov/cgi-bin/ipc/idbrank.pl. If this page is unavailable, you can find similar information at the main Census page (http://www.census.gov) or the Population Research Bureau (http://www.prb.org).


Summary

Drawing something using the polygons and other shapes available with Java might seem like more trouble than it's worth, especially when you can load image files such as .GIF files and .JPG files, as you'll see in the next hour. However, graphics depicted with polygons have two advantages over graphics that are loaded from image files:

  • Speed—Even a small graphic, such as an icon, would take longer to load and display than a series of polygons.

  • Scaling—You can change the size of an entire image that uses polygons simply by changing the values to create it. For example, you could add a function to the Sign class that multiplies all (x,y) points in each shape by two before they are created, and it would result in an image twice as large. Polygon images scale much more quickly than image files and produce better results.

There are many instances where it makes more sense to use graphics files in your programs, and you will be trying some of them in the next hour.


Q&A

Q1:

How can I draw arcs that go clockwise rather than counterclockwise?

A1:

You can accomplish this by specifying the size of the arc as a negative number. The arc will begin at the same point, but go in the opposite direction in an elliptical path. For example, the following statement draws an open arc at (35,20) that is 90 degrees long, begins at the 0 degree mark, goes clockwise, and has a height of 20 and a width of 15:

Arc2D.Float smile = new Arc2D.Float(35F, 20F, 15F, 20F,

    0F, -90F, Arc2D.Float.OPEN);

Q2:

Ellipses and circles don't have corners. What are the (x,y) coordinates specified with the Ellipses.Float constructor method?

A2:

The (x,y) coordinates represent the smallest x value and smallest y value of the oval or circle. If you drew an invisible rectangle around it, the upper-left corner of the rectangle would be the x and y coordinates used as arguments to the method.

Q3:

What kind of plant grows on Chia Pets?

A3:

Salvia hispanica, a mint plant native to central Mexico that was a major food crop for the Aztecs and had uses for cleansing, wound dressing, and body painting.

The plant isn't as dinky as you might think. The grooved clay surface of a Chia animal offers insufficient nutrients and no space for roots to grow.

Joseph Enterprises, the makers of the Chia Pet, has a World Wide Web site at http://www.chiapet.com.


Quiz

Test whether your Java graphics skills are taking shape by answering the following questions.

Questions

1:

What method is used to change the current color before you draw something in a program?

  1. shiftColor()

  2. setColor()

  3. Could you repeat the question?

2:

If you want to use the height and width of a component to determine how big something should be drawn, what can you use?

  1. A ruler and a friend who's good at math

  2. getHeight() and getWidth()

  3. getSize().height and getSize().width

3:

What societal problem did this hour's first example program call attention to?

  1. Overpopulation

  2. Defaulted student loans

  3. People who compress air in places with signs that clearly indicate it is prohibited, especially restaurants

Answers

A1: | b. You can use the setBackground() method to set the background color of an applet, and you can use the setColor() method of the Graphics class to select the current color.
A2: | c.
A3: | c. Though overpopulation is a pretty big deal, too.


Activities

To draw upon your vast storehouse of graphical skills, do the following activities:

  • Create a version of the PieApplet class that takes color values and pie slice values as parameters instead of including them in the source code of the applet.

  • Create a version of Sign that changes in shape to fit the available space in the panel (just like the PiePanel component does).

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


Hour 24. Creating Animation

Whether you are reading this book in 24 one-hour sessions or a day-long-bring-me-more-coffee-can't-feel-my-hand-are-you-going-to-finish-that-doughnut marathon, you deserve something for making it this far.

Unfortunately, Sams Publishing declined my request to buy you a pony, so the best I can offer as a reward is the most entertaining subject in the book: animation.

At this point, you have learned how to use text, fonts, color, lines, and polygons in your Java programs. For the last hour on Java's multimedia capabilities, and the last hour of the book, you will learn how to display image files in GIF and JPEG formats in your programs and present them in animated sequences. The following topics will be covered:

  • Using Image objects to hold image files

  • Putting a series of images into an array

  • Cycling through an image array to produce animation

  • Using the drawImage() command

  • Establishing rules for the movement of an image


Animating a Sequence of Images

Computer animation at its most basic consists of drawing an image at a specific place, moving the location of the image, and telling the computer to redraw the image at its new location. Many animations on web pages are a series of image files, usually GIF files that are displayed in the same place in a certain order. You can do this to simulate motion or to create some other effect.

The first program you will be writing today uses a series of image files to create an animated picture of the Anastasia Island Lighthouse in St. Augustine, Florida. Several details about the animation will be customizable with parameters, so you can replace any images of your own for those provided for this example.

Create a new file in your word processor called Animate.java. Enter Listing 24.1 into the file, and remember to save the file when you're done entering the text.

Listing 24.1. The Full Text of Animate.java

 1: import java.awt.*;

 2:

 3: public class Animate extends javax.swing.JApplet

 4:     implements Runnable {

 5:

 6:     Image[] picture = new Image[6];

 7:     int totalPictures = 0;

 8:     int current = 0;

 9:     Thread runner;

10:     int pause = 500;

11:

12:     public void init() {

13:         for (int i = 0; i < 6; i++) {

14:             String imageText = null;

15:             imageText = getParameter("image"+i);

16:             if (imageText != null) {

17:                 totalPictures++;

18:                 picture[i] = getImage(getCodeBase(), imageText);

19:             } else {

20:                 break;

21:             }

22:         }

23:         String pauseText = null;

24:         pauseText = getParameter("pause");

25:         if (pauseText != null) {

26:             pause = Integer.parseInt(pauseText);

27:         }

28:     }

29:

30:     public void paint(Graphics screen) {

31:         super.paint(screen);

32:         Graphics2D screen2D = (Graphics2D) screen;

33:         if (picture[current] != null) {

34:             screen2D.drawImage(picture[current], 0, 0, this);

35:         }

36:     }

37:

38:     public void start() {

39:         if (runner == null) {

40:             runner = new Thread(this);

41:             runner.start();

42:         }

43:     }

44:

45:     public void run() {

46:         Thread thisThread = Thread.currentThread();

47:         while (runner == thisThread) {

48:             repaint();

49:             current++;

50:             if (current >= totalPictures) {

51:                 current = 0;

52:             }

53:             try {

54:                 Thread.sleep(pause);

55:             } catch (InterruptedException e) {

56:                 // do nothing

57:             }

58:         }

59:     }

60:

61:     public void stop() {

62:         if (runner != null) {

63:             runner = null;

64:         }

65:     }

66: }

Because animation is usually a process that continues over a period of time, the portion of the program that manipulates and animates images should be designed to run in its own thread. This becomes especially important in a Swing program that must be able to respond to user input while an animation is taking place. Without threads, animation often takes up so much of the Java interpreter's time that the rest of a program's graphical user interface is sluggish to respond.

The Animate program uses the same threaded applet structure that you used during Hour 19, "Creating a Threaded Program." Threads also are useful in animation programming because they give you the ability to control the timing of the animation. The THRead.sleep() method is an effective way to determine how long each image should be displayed before the next image is shown.

The Animate applet retrieves images as parameters on a web page. The parameters should have names starting at image0 and ending at the last image of the animation, such as image3 in this hour's example. The maximum number of images that can be displayed by this applet is six, but you could raise this number by making changes to Lines 6 and 13.

The totalPicture integer variable determines how many different images will be displayed in an animation. If less than six image files have been specified by parameters, the Animate applet will determine this during the init() method when imageText equals null after Line 15.

The speed of the animation is specified by a "pause" parameter. Because all parameters from a web page are received as strings, the Integer.parseInt() method is needed to convert the text into an integer. The pause variable keeps track of the number of milliseconds to pause after displaying each image in an animation.

Loading and Displaying Images

As with most threaded programs, the run() method contains the main part of the program. A while (runner == thisThread) statement in Line 47 causes Lines 48–57 to loop until something causes these two Thread objects to have different values.

The first thing that happens in the while loop is a call to the applet's repaint() method. This statement requests that the applet's paint() method be called so that the screen can be updated. Use repaint() any time you know something has changed and the display needs to be changed to bring it up to date. In this case, every time the Animate loop goes around once, a different image should be shown.

By the Way

In Java, you can never be sure that calling repaint() will result in the component or applet window being repainted. The interpreter will ignore calls to repaint() if it can't process them as quickly as they are being called, or if some other task takes up most of its time.

The paint() method in Lines 30–36 contains the following statements:

Graphics2D screen2D = (Graphics2D) screen;

if (picture[current] != null)

    screen2D.drawImage(picture[current], 0, 0, this);

First, a Graphics2D object is cast so that it can be used when drawing to the applet window. Next, an if statement determines whether the Image object stored in picture[current] has a null value. When it does not equal null, this indicates that an image is ready to be displayed. The drawImage() method of the screen2D object displays the current Image object at the (x,y) position specified.

By the Way

The paint() method of this applet does not call the paint() method of its superclass, unlike some of the other graphical programs in the book, because it makes the animated sequence look terrible. The applet's paint() method clears the window each time it is called, which is okay when you're drawing a graphical user interface or some other graphics that don't change. However, clearing it again and again in a short time causes an animation to flicker.

The this statement sent as the fourth argument to drawImage() enables the program to use a class called ImageObserver. This class tracks when an image is being loaded and when it is finished. The JApplet class contains behavior that works behind the scenes to take care of this process, so all you have to do is specify this as an argument to drawImage() and some other methods related to image display. The rest is taken care of for you.

An Image object must be created and loaded with a valid image before you can use the drawImage() method. The way to load an image in an applet is to use the getImage() method. This method takes two arguments: the web address or folder that contains the image file and the filename of the image.

The first argument is taken care of with the getCodeBase() method, which is part of the JApplet class. This method returns the location of the applet itself, so if you put your images in the same folder as the applet's class file, you can use getCodeBase(). The second argument should be a GIF file or JPEG file to load. In the following example, a turtlePicture object is created and an image file called Mertle.gif is loaded into it:

Image turtlePicture = getImage(getCodeBase(), "Mertle.gif");

By the Way

As you look over the source code to the Animate applet, you might wonder why the test for a null value in Line 33 is necessary. This check is required because the paint() method may be called before an image file has been fully loaded into a picture[] element. Calling getImage() begins the process of loading an image. To prevent a slowdown, the Java interpreter continues to run the rest of the program while images are being loaded.

Storing a Group of Related Images

In the Animate applet, images are loaded into an array of Image objects called pictures. The pictures array is set up to handle six elements in Line 6 of the program, so you can have Image objects ranging from picture[0] to picture[5]. The following statement in the applet's paint() method displays the current image:

screen.drawImage(picture[current], 0, 0, this);

The current variable is used in the applet to keep track of which image to display in the paint() method. It has an initial value of 0, so the first image to be displayed is the one stored in picture[0]. After each call to the repaint() statement in Line 48 of the run() method, the current variable is incremented by one in Line 49.

The totalPictures variable is an integer that keeps track of how many images should be displayed. It is set when images are loaded from parameters off the web page. When current equals totalPictures, it is set back to 0. As a result, current cycles through each image of the animation, and then begins again at the first image.


Sending Parameters to the Applet

Because the Animate applet relies on parameters to specify the image files it should display, you need to create a web page containing these filenames before you can test the program. After saving and compiling the Animate.java file, open up a new file in your word processor and call it Animate.html. Enter Listing 24.2 into that file and save it when you're done.

Listing 24.2. The Full Text of Animate.html

1: <applet code="Animate.class" width="215" height="298">

2: <param name="image0" value="lh0.gif">

3: <param name="image1" value="lh1.gif">

4: <param name="image2" value="lh2.gif">

5: <param name="image3" value="lh3.gif">

6: <param name="pause" value="800">

7: </applet>

This file specifies four image files: lh0.gif, lh1.gif, lh2.gif, and lh3.gif. These files are listed as the values for the parameters image0 through image3. You can find the files used in this example on the Hour 24 page of the book's website at http://www.java24hours.com.

You also can specify any of your own GIF or JPEG files, if desired. Whichever files you choose should be placed in the same folder as the Animate.class and Animate.html files. With the pause parameter, you can specify how long the program should pause after each image is displayed.

By the Way

You might be wondering why the files and the parameters are given names that start numbering with 0 instead of 1. This is done because the first element of an array in a Java program is numbered 0. Putting an image0 called lh0.gif into pictures[0] makes it easier to know where these images are being stored.

Once the files have been put in the right place, you're ready to try out the Animate applet. Type the following command to open the page in your web browser and view the applet:

Animate.html

Figure 24.1 shows one of the four images being displayed as the applet runs.

Figure 24.1. Animating GIF files in an applet.

Although this is a simple animation program, hundreds of applets on the web use similar functionality to present a series of image files as an animation. Presenting a sequence of image files through Java is similar to the animated GIF files that are becoming more commonplace on web pages. Although Java applets are often slower to load than these GIF files, they can provide more control of the animation and allow for more complicated effects.


Workshop: Follow the Bouncing Ball

This hour's workshop is an animation that definitely couldn't be replicated with an animated GIF file or any other non-programming alternative. You'll write a program that bounces a tennis ball around the screen in lazy arcs, bouncing off the sides of the panel that contains the animation. Though a few laws of physics will be broken along the way, you'll learn one way to move an image file around the screen.

Create a new file in your word processor called BouncePanel.java, and enter the text of Listing 24.3 into it. Save and compile the file when you're done.

Listing 24.3. The Full Text of BouncePanel.java

 1: import java.awt.*;

 2: import javax.swing.*;

 3: import java.util.*;

 4:

 5: public class BouncePanel extends JPanel implements Runnable {

 6:     Image ball, court;

 7:     float current = 0F;

 8:     Thread runner;

 9:     int xPosition = 10;

10:     int xMove = 1;

11:     int yPosition = -1;

12:     int ballHeight = 185;

13:     int ballWidth = 190;

14:     int height;

15:

16:     public BouncePanel() {

17:         super();

18:         Toolkit kit = Toolkit.getDefaultToolkit();

19:         ball = kit.getImage("tennis.gif");

20:         court = kit.getImage("court.jpg");

21:         runner = new Thread(this);

22:         runner.start();

23:     }

24:

25:     public void paintComponent(Graphics comp) {

26:         Graphics2D comp2D = (Graphics2D) comp;

27:         height = getSize().height - ballHeight;

28:         if (yPosition == -1) {

29:             yPosition = height - 20;

30:         }

31:         if ((court != null) && (ball != null)) {

32:             comp2D.drawImage(court, 0, 0, this);

33:             comp2D.drawImage(ball,

34:                (int) xPosition,

35:                (int) yPosition,

36:                this);

37:         }

38:     }

39:

40:     public void run() {

41:         Thread thisThread = Thread.currentThread();

42:         while (runner == thisThread) {

43:             current += (float) 0.1;

44:             if (current > 3) {

45:                 current = (float) 0;

46:             }

47:             xPosition += xMove;

48:             if (xPosition > (getSize().width - ballWidth)) {

49:                 xMove *= -1;

50:             }

51:             if (xPosition < 1) {

52:                 xMove *= -1;

53:             }

54:             double bounce = Math.sin(current) * height;

55:             yPosition = (int) (height - bounce);

56:             repaint();

57:             try {

58:                 Thread.sleep(100);

59:             } catch (InterruptedException e) {

60:                 // do nothing

61:             }

62:         }

63:     }

64: }

Before you dive into the discussion of what's taking place in this class, you should see what it does. You need to create a program and add the BouncePanel component to the program's graphical user interface.

Create a new file in your word processor called Bounce.java and enter Listing 24.4 into it.

Listing 24.4. The Full Text of Bounce.java

 1: import java.awt.*;

 2: import javax.swing.*;

 3:

 4: public class Bounce extends JFrame {

 5:     public Bounce() {

 6:         super("Tennis");

 7:         setSize(550, 450);

 8:         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 9:         BouncePanel boing = new BouncePanel();

10:         add(boing);

11:         setVisible(true);

12:     }

13:

14:     public static void main(String[] arguments) {

15:         Bounce frame = new Bounce();

16:     }

17: }

After saving this file, you need to get a copy of the tennis.gif and court.gif files and put them in the same folder as Bounce.class and BouncePanel.class. This file is available from the same place as the lighthouse image files: the book's website at http://www.java24hours.com.

Once you have copied the graphics files into the right place, run the Bounce application by typing this command:

java Bounce

Figure 24.2 shows the application running after both graphics have fully loaded.

Figure 24.2. Moving graphics files in an animation.

This application displays the animation on the BouncePanel component: a GIF file of a tennis ball bounces back and forth in front of a GIF file depicting a net. When the ball hits a point at the bottom edge of the frame, it rebounds upward close to the top edge. When the ball hits the right or left edge, it bounces in the opposite direction.

The animated sequence in the BouncePanel class illustrates how to animate an image file using Java. It consists of the following steps:

1. | Draw the ball at its current location.
2. | Move the ball according to the rules that have been established for how the ball should move.
3. | Check whether the rules need to be changed based on the ball's new location.
4. | Repeat.

Drawing the Image

The BouncePanel class is threaded, so all its image-manipulation code is placed in a run() method that will be called when the thread is started.

The paintComponent() method is where the court is drawn, followed by the ball at its current location.

By the Way

If you display the tennis.gif file in a graphics viewer or editing program, you will see that it has a dark gray background around the ball. This background does not show up in the animated sequence because the tennis.gif file has been saved with that dark gray color designated as a transparent color. Java 2 supports transparency in graphics files, making it much easier to animate one image atop another.

The Image object called ball is loaded with the tennis.gif image in the init() method. Several variables are used in the class to keep track of the ball's location and its current rate of movement:

  • xPosition This variable is the x coordinate where the ball should be drawn. This coordinate begins as 10.

  • xMove This variable is the amount the ball should move along the x axis after every screen update. This amount starts out as 1, but it will change to -1 when the ball hits the right edge of the applet window. It changes back and forth from -1 to 1 every time it hits an edge, and this change is handled by Lines 48–53.

  • yPosition This variable is the y coordinate where the ball should be drawn. This coordinate is initially set to -1, which is a signal to the paint() method that the yPosition needs to be set up before the ball can be drawn for the first time. The yPosition value varies from a point near the bottom of the applet window to the top edge.

  • current This floating point number starts at 0 and increases by 0.1 each time the ball is redrawn. When it reaches 3, it is set back to 0 again. The current variable is used with a mathematical sine function to determine how high the ball bounces. Sine waves are a good way to approximate the movements of a bouncing ball, and the Math.sin() method enables a sine value to be used in conjunction with animation. The tennis ball is traveling half a sine wave each time it goes from the ground to the top of the window and back.

The movement rules that you establish for an animated program will vary depending on what you're trying to show. The Bounce application uses the Math.sin() method to create the slow arcs traveled by the ball.


Summary

The purpose of Sams Teach Yourself Programmigng with Java in 24 Hours, Fourth Edition is to help you become comfortable with the concepts of programming and confident in your ability to write your own applications and applets. Java has an approach that is somewhat difficult to master. (Feel free to scratch out the word "somewhat" in the previous sentence if it's a gross misstatement of the truth.)

As you build experience in Java, you're building experience that grows increasingly relevant, because concepts such as object-oriented programming, virtual machines, and secure environments are on the leading edge of software development.

If you haven't already, you should read the appendices to find out about this book's website, additional Java books from Sams Publishing, and other useful information.

At the conclusion of this hour, you can explore Java in several different places. Programmers are discussing the language on the weblogs at http://weblogs.java.net. Hundreds of Java User Groups meet regularly, according to the list published at Sun's Java site (http://developers.sun.com/jugs). Numerous Java job openings are displayed in the database of employment World Wide Web sites such as http://www.careerbuilder.com. There's also a website for this book at http://www.java24hours.com where you can send email to the author and read answers to reader questions, clarifications to the book, and (gulp) corrections.

Of course, my favorite way for you to continue building your skills as a Java programmer is to read Sams TeachYourself Java 2 in 21 Days, Fourth Edition. I coauthored the book with Laura Lemay, and it expands on the subjects covered here and introduces new ones, such as JDBC, Java servlets, and network programming.

My apologies for this brazen attempt to hawk another book…if I sell enough copies, my name is entered into a drawing with other top Sams authors to win special prizes.

My heart's set on the Limited Edition U2 iPod or the three-day, two-night vacation to Indianapolis.

—Rogers Cadenhead


Q&A

Q1:

Does a threaded animation program have to use Thread.sleep() to pause, or can you omit it to produce the fastest possible animation?

A1:

You have to put some kind of pause in place in an animation program, or the program will crash or behave erratically. Without pauses, Java won't be able to keep up with constant repaint() requests and may be unable to respond to mouse-clicks on its interface and other user input. Part of the process of animation design in Java is finding the right display speed that all environments can handle.

Q2:

What happens if you draw something, such as an image, to coordinates that aren't within the window?

A2:

Methods that draw something to a coordinate will continue to draw it even if none of it is visible within the area shown by the applet window or application frame. This is a good way to have something move into view, because the portion of the image that falls into the visible area will be displayed.

Q3:

After completing this book, will I be able to pass the programmer certification test?

A3:

Every programming language has features great for expert-level coders that send beginners fleeing in terror.

In Java, a good example is the ternary operator introduced in Hour 7, "Using Conditional Tests to Make Decisions," which uses a true-false boolean expression to produce one of two values. A Java programmer can avoid learning about the ternary operator entirely, because the same effect can be achieved with a simple if-else block statement.

Certification test writers love ternary operators and other obscure but powerful aspects of the language. For this reason, you'll need more prep before taking one of these tests.

Shameless plug ahead: Each chapter of Sams Teach Yourself Java 2 in 21 Days, Fourth Edition, the book I coauthored with Laura Lemay, ends with a certification practice question.

Q4:

Why is a man who dates a bunch of different women called a "lothario"?

A4:

Lothario is a character in The Fair Penitent, a play written in 1703 by Nicholas Rowe. In the play, Lothario seduces Calista, the daughter of a lord. This is discovered on the day of her wedding to Lord Altamont, which leads to a duel, street riot, and a really bad day for everyone involved.

The character was known as the "gay Lothario" for several centuries, taking an expression used in Rowe's play. He would be more accurately described today as the straight Lothario.


Quiz

Animate yourself as much as you can muster and answer the following questions to test your skills.

Questions

1:

Where is the (0,0) coordinate on a container?

  1. In an off-screen double-buffering area

  2. The exact center of the window

  3. The upper-left corner of the applet window

2:

What thing did you not learn during this hour?

  1. How to load images in an application

  2. How to make sure an image is not displayed until it loads

  3. Why the tennis ball is bouncing off thin air instead of the ground in the BouncePanel application.

3:

In a threaded animation applet, where should you handle most of the movement of an image?

  1. The run() method

  2. The init() method

  3. The paint() method

Answers

A1: | c. The x value increases as you head to the right, and the y value increases as you head downward.
A2: | c. Would you believe clear-air turbulence?
A3: | a. Some movement might be handled by statements in the paint() method, but most of it will take place in run() or a method called from within run().


Activities

Before you're stranded and the subject of graphics is abandoned, picture yourself doing the following activities:

  • Create an application that contains a BouncePanel component and a slider or text field in which the animation speed can be changed from 100 to another value.

  • Create a version of the Animate project that runs as an application instead of an applet.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


Part VII: Bonus...

    Part VII: Bonus…

    HOUR 25 Creating Web Services with XML-RPC


Hour 25. Creating Web Services with XML-RPC

Every day, thousands of computer programs join millions of people on the Web, gathering and exchanging information over HTTP, the protocol that drives the World Wide Web.

As humankind is reading the news, playing online games of Texas Hold 'em poker, and searching Google for the latest celebrity wardrobe malfunctions, our programs are diligently putting the Web to work, calling methods of other programs and receiving data in return.

These exchanges take place over the Internet, enabling two programs to work together as if they were both running on the same computer.

Programs that can do this are called web services, and during the 25th hour of the day, you'll learn how to code them in Java using the Apache XML-RPC class library.

By the way

As you might have noticed, there only have been 24 hours in a day since the ancient Babylonians set up the timekeeping scheme more than 1,000 years ago. Web services are such an important facet of programming we've suspended the laws of time and space to bring you this additional hour.

During this hour, you'll learn about the following aspects of web services programming and XML-RPC:

  • Exchanging information over HTTP with XML-RPC

  • Creating classes whose methods can be called with XML-RPC

  • Running an XML-RPC server

  • Calling a method with an XML-RPC client

  • Receiving a response from the method call


Working with Apache XML-RPC

There are a lot of different ways for two computer programs to communicate with each other over the Internet or another network. The simplest of all may be XML-RPC, which is short for XML Remote Procedure Call, a protocol developed in 1998 by Dave Winer of UserLand Software and Microsoft to foster web services.

Client/server implementations of XML-RPC are now available for most operating systems and programming languages in wide use. Winer publishes a directory of them on the Web at http://www.xmlrpc.com.

XML-RPC works by transmitting XML over HTTP, the same protocol that's used by web browsers and web servers. XML was covered in Hour 21, "Reading and Writing XML Data," and you'll get more practice with the XML Object Model (XOM) class library as it's employed during this hour.

The XML-RPC protocol makes it possible to call methods and receive data in return in a language- and operating system–independent manner.

The process isn't directly analogous to Java—you don't create an object and call a method, because XML-RPC is simpler than Java and supports different data types. XML-RPC also does not support objects.

Behind the scenes, XML-RPC supports its own distinct data types, but you don't need to know any of that when using Apache XML-RPC, a class library offered by the developers of the Apache web server and Tomcat Java servlet container.

Apache XML-RPC can be downloaded from http://ws.apache.org/xmlrpc, a site that includes Javadoc documentation and additional support. The software is released under an open source license, so you must familiarize yourself with its terms before deciding whether to adopt it on a project.

Though version 2.0 of Apache XML-RPC was released in spring 2005, this hour's Java classes have been written for version 1.2, a stable release that has been available for more than a year. You may be able to compile and run these classes with the most current 2.0 release by the time this chapter sees print.

To install Apache XML-RPC, download the software as a ZIP archive (Windows), or in TAR.GZ format on other operating systems. Two files must be stored in a directory that's in the Classpath of the Java interpreter and compiler. For version 1.2, these files are xmlrpc-1.2-b1.jar and xmlrpc-1.2-b1-applet.jar.

The programs that you create during this hour will function as an XML-RPC client and XML-RPC server to enhance the capabilities of the LottoMadness application from Hour 15, "Responding to User Input."

LottoMadness will gain the ability to save the results of the drawings that it performs, sending results to a central server where they are saved as an XML file.

This requires two programs—a client that makes an XML-RPC method call and a server that takes the call.


Creating an XML-RPC Handler

Any Java class can take XML-RPC method calls, as long as it has public methods with return types and arguments that correspond properly with XML-RPC data types.

These classes are called XML-RPC handlers, because a server gives them the job of handling an incoming request.

Every public method of the class can be called over XML-RPC, as it is implemented by Apache XML-RPC, so you must keep this in mind when declaring methods.

The LottoCounter class in Listing 25.1 can handle XML-RPC calls. This class receives lottery results, storing them in an XML file named lotto.log.

This class and the rest of the hour's projects require XOM, the class library introduced in Hour 21. Download the library from the website http://www.cafeconleche.org/XOM, then add the file xom-1.0.jar to your Classpath environment variable (or the Classpath for this project).

Enter the text of the class and save it as LottoCounter.java. This program doesn't introduce any functionality that's new to this hour, putting to use the XML capabilities of the XOM class library.

Listing 25.1. The Full Text of LottoCounter.java

 1: import java.io.*;

 2: import java.util.*;

 3: import nu.xom.*;

 4:

 5: public class LottoCounter {

 6:     Document document;

 7:     Element root;

 8:     File logFile;

 9:

10:     public LottoCounter() throws IOException, ParsingException {

11:         Builder builder = new Builder();

12:         logFile = new File("lotto.log");

13:         if (!logFile.exists()) {

14:             // create a new XML document

15:             root = new Element("log");

16:             document = new Document(root);

17:             writeDocument();

18:         }

19:         // load the XML document from a file

20:         document = builder.build(logFile);

21:         root = document.getRootElement();

22:     }

23:

24:     public boolean sendResult(int plays, int win3, int win4, int win5, int win6)

25:         throws IOException, ParsingException {

26:

27:         // create the result element

28:         Element result = new Element("result");

29:

30:         // create subelements for each value

31:         Element playElement = new Element("plays");

32:         playElement.appendChild("" + plays);

33:         Element win3Element = new Element("win3");

34:         win3Element.appendChild("" + win3);

35:         Element win4Element = new Element("win4");

36:         win4Element.appendChild("" + win4);

37:         Element win5Element = new Element("win5");

38:         win5Element.appendChild("" + win5);

39:         Element win6Element = new Element("win6");

40:         win6Element.appendChild("" + win6);

41:         Element dateElement = new Element("date");

42:         Date now = new Date();

43:         dateElement.appendChild(now.toString());

44:

45:         // add subelements to result

46:         result.appendChild(playElement);

47:         result.appendChild(win3Element);

48:         result.appendChild(win4Element);

49:         result.appendChild(win5Element);

50:         result.appendChild(win6Element);

51:         result.appendChild(dateElement);

52:

53:         // add the result to the root

54:         root.appendChild(result);

55:

56:         // save the document

57:         writeDocument();

58:         return true;

59:    }

60:

61:    // write the document to a file

62:    private void writeDocument() throws IOException {

63:         FileOutputStream fileStream = new FileOutputStream(logFile);

64:         Serializer writer = new Serializer(fileStream);

65:         writer.setIndent(2);

66:         writer.write(document);

67:     }

68: }

This class, which can't be run directly because it lacks a main() method, has one public method called sendResult(). This method can be called to submit lottery results: the total number of drawings and the number of times that three, four, five or all six numbers matched the user's picks.

Though the constructor also is public, it cannot be called over XML-RPC.

Here's code that could test this class, submitting some results entered as command-line arguments:

public static void main(String[] arguments) {

    try {

        int plays = Integer.parseInt(arguments[0]);

        int win3 = Integer.parseInt(arguments[1]);

        int win4 = Integer.parseInt(arguments[2]);

        int win5 = Integer.parseInt(arguments[3]);

        int win6 = Integer.parseInt(arguments[4]);

        LottoCounter counter = new LottoCounter();

        counter.send(plays, win3, win4, win5, win6);

    } catch (Exception exception) {

        System.out.println("Error: " + exception.getMessage());

        exception.printStackTrace();

    }

}

Don't add this to the class—you'll be testing it in a matter of minutes over XML-RPC.

When this class receives lottery results, it assembles an XML file named lotto.log like the one in Listing 25.2. LottoCounter will create this file if it doesn't exist when the program first runs.

Listing 25.2. The Full Text of lotto.log

 1: <?xml version="1.0" encoding="UTF-8"?>

 2: <log>

 3:   <result>

 4:     <plays>3482</plays>

 5:     <win3>57</win3>

 6:     <win4>3</win4>

 7:     <win5>0</win5>

 8:     <win6>0</win6>

 9:     <date>Wed Jul 13 15:41:43 EDT 2005</date>

10:   </result>

11:   <result>

12:     <plays>779</plays>

13:     <win3>12</win3>

14:     <win4>0</win4>

15:     <win5>0</win5>

16:     <win6>0</win6>

17:     <date>Wed Jul 13 15:45:08 EDT 2005</date>

18:   </result>

19: </log>

This XML document has the root-level element log, which contains a result element for each submitted lottery run. The last submission in Listing 25.2 was from a user who conducted 779 lottery drawings, winning 3-out-of-6 12 times.

By the way

If I were to play the Florida Lotto that many times with that much success, I would have won from $12 to $18 after spending $770 on tickets. I'm beginning to think that "Win the Lottery" is not a fiscally sound retirement plan.


Creating an XML-RPC Server

Now that you have a Java class that will handle XML-RPC requests, you're ready to develop a server that waits for these requests to arrive, dispatching them to the handler.

The LottoServer class drives a simple web server that looks for these requests.

Apache XML-RPC has two core packages: org.apache.xmlrpc for applications and org.apache.xmlrpc for applications.

The WebServer class in org.apache.xmlrpc functions as a bare-bones XML-RPC server that listens on a specified TCP/IP Internet port:

int port = 4404;

server = new WebServer(port);

The choice of port number 4404 is arbitrary; any port from 1,024 through 49,151 could be chosen.

By the way

The Internet Assigned Numbers Authority, a group that decrees how ports below 1,024 are used, offers a directory of port numbers and the software using them on the Web: http://www.iana.org/assignments/port-numbers.

The server's addHandler() method designates a class that will handle XML-RPC requests:

LottoCounter counter = new LottoCounter();

server.addHandler("lotto", counter);

The method's arguments are an identifier that gives the handler a name and an object. The LottoCounter object counter has been assigned the name "lotto", so the public methods of that object may be called over XML-RPC.

There's one such method, sendRequest(), which will be called over XML-RPC as lotto.sendRequest. No parentheses should follow the method name—they are omitted in XML-RPC.

An XML-RPC server can add as many handlers as desired, which don't need to belong to the same class.

The server can be launched by calling its start() method:

server.start();

Enter the text of Listing 25.3 and save the file under the name LottoServer.java.

Listing 25.3. The Full Text of LottoServer.java

 1: import java.io.*;

 2: import nu.xom.*;

 3: import org.apache.xmlrpc.*;

 4:

 5: public class LottoServer {

 6:     int port = 4404;

 7:     WebServer server;

 8:

 9:     public LottoServer() throws IOException, ParsingException {

10:         // create the server

11:         System.out.println("Creating server on port " + port);

12:         server = new WebServer(port);

13:

14:         // register the request handler

15:         LottoCounter counter = new LottoCounter();

16:         server.addHandler("lotto", counter);

17:     }

18:

19:     public void start() {

20:         // start the server

21:         System.out.println("Now accepting requests");

22:         server.start();

23:     }

24:

25:     public static void main(String[] arguments) {

26:         try {

27:             LottoServer lotto = new LottoServer();

28:             lotto.start();

29:         } catch (Exception exception) {

30:             System.out.println("Error: " + exception.getMessage());

31:         }

32:     }

33: }

Compile and run the application, which requires no command-line arguments:

java LottoServer

The following output indicates the server's running and ready to receive requests:

Creating server on port 4404

Now accepting requests

On a Windows system, you must leave this running and open a second command-line window to create the XML-RPC client. On Linux, you can start the server in the background by putting an "&" character after the command:

java LottoServer &

When running the application in the background, to stop it later on, you must use the ps command to find its process ID, then the kill command to bring it to a halt.

Here's an example for the Bash shell on Linux:

ps auxw | grep LottoServer

rcade    10424  0.0  1.3 269764 14320 pts/0  S    Jul13   0:00 /usr/java/jdk1.5.0/bin/java

   LottoServer

kill -9 10424


Creating an XML-RPC Client

An XML-RPC server can be called over the Internet, over a network, or within a single computer. Any web server that has a URL, a unique web address, can be accessed with the protocol.

The LottoClient class will extend XML-RPC functionality to LottoMadness, the lottery-testing application created in Hour 15.

A client can be implemented with either the XmlRpcClient class in the org.apache.xmlrpc.applet package (for applets) or the SimpleXmlRpcClient class in org.apache.xmlrpc.applet (for other classes).

The reason to split them in this manner is security. Applets run a restricted environment that prohibits some capabilities of the Java language, such as making network connections to any computer other than the one hosting the applet.

LottoClient works with XmlRpcClient, connecting to a server at the URL http://localhost:4404:

String server = "http://localhost";

int port = 4404;

XmlRpcClient client = new XmlRpcClient(server + ":" + port);

The client's execute() method submits an XML-RPC request to the designated server:

Boolean result = (Boolean) client.execute("lotto.sendResult", params);

The first method argument identifies the XML-RPC method: lotto.sendResult. When this is called, the sendResult() method of the XML-RPC handler class, LottoCounter, will be executed.

The second holds a Vector object with all of the method arguments, in order. Vectors, a data structure that functions as an array that can change in size, were covered in Hour 12, "Making the Most of Existing Objects."

The sendResult() method takes six integer arguments:

Vector params = new Vector();

params.add(plays);

params.add(win3);

params.add(win4);

params.add(win5);

params.add(win6);

Boolean result = (Boolean) client.execute("lotto.sendResult", params);

When the XML-RPC method returns an object, the execute() method returns this object, which must be converted using casting.

When the method returns a basic data type, the matching class is returned. So a boolean value returned by sendResult() becomes a Boolean object when returned by execute().

The LottoClient class has a send() method that submits XML-RPC requests to the lottery server:

LottoClient lc = new LottoClient();

lc.send(plays, win3, win4, win5, win6);

Enter the text of Listing 25.4 and save the file as LottoClient.java when you're done.

Listing 25.4. The Full Text of LottoClient.java

 1: import java.io.*;

 2: import java.net.*;

 3: import java.util.*;

 4: import org.apache.xmlrpc.*;

 5:

 6: public class LottoClient {

 7:     XmlRpcClient client;

 8:     String server = "http://localhost";

 9:     int port = 4404;

10:

11:     public LottoClient() {

12:         try {

13:             client = new XmlRpcClient(server + ":" + port);

14:         } catch (MalformedURLException exception) {

15:             System.out.println("Bad URL: " + server + ":" + port);

16:         }

17:     }

18:

19:     public void send(int plays, int win3, int win4, int win5, int win6)

20:         throws IOException, XmlRpcException {

21:

22:          Vector<Integer> params = new Vector<Integer>();

23:         params.add(plays);

24:         params.add(win3);

25:         params.add(win4);

26:         params.add(win5);

27:         params.add(win6);

28:         Boolean result = (Boolean) client.execute("lotto.sendResult", params);

29:     }

30:

31:     public static void main(String[] arguments) {

32:         try {

33:             int plays = Integer.parseInt(arguments[0]);

34:             int win3 = Integer.parseInt(arguments[1]);

35:             int win4 = Integer.parseInt(arguments[2]);

36:             int win5 = Integer.parseInt(arguments[3]);

37:             int win6 = Integer.parseInt(arguments[4]);

38:             LottoClient lc = new LottoClient();

39:             lc.send(plays, win3, win4, win5, win6);

40:         } catch (Exception exception) {

41:             System.out.println("Error: " + exception.getMessage());

42:             exception.printStackTrace();

43:         }

44:     }

45: }

Compile and run the application with five arguments—the number of drawings, the number of 3-of-6 wins, 4-of-6 wins, 5-of-6 wins, and grand prize "I'm rich! I'm rich!" 6-of-6 jackpots:

java LottoClient 725 10 8 1 0

Try this out, then open the lotto.log file. You should see a new result element near the bottom of the document with the submitted results:

<result>

  <plays>725</plays>

  <win3>10</win3>

  <win4>8</win4>

  <win5>1</win5>

  <win6>0</win6>

  <date>Thu Jul 14 00:46:26 EDT 2005</date>

</result>


Workshop: Enhancing the LottoMadness Application

The LottoMadness application consists of two classes, the LottoMadness class that builds a graphical user interface and the LottoEvent class that receives user events—button clicks and check box selections.

The LottoMadness and LottoEvent classes were developed during Hour 17, "Creating Interactive Web Programs."

Copy these class files and their .java source code files to the same folder as the classes created so far this hour.

The LottoMadness class requires no modifications to work with XML-RPC.

Around 30 lines must be added to LottoEvent to cause it to submit XML-RPC requests.

In Listing 25.5, the shaded lines are new material. Add them, then resave the file in your editor.

Listing 25.5. The Full Text of LottoEvent.java

 1: import javax.swing.*;

 2: import java.awt.event.*;

 3:

 4: public class LottoEvent implements ItemListener, ActionListener,

 5:     Runnable {

 6:

 7:     LottoMadness gui;

 8:     Thread playing;

 9:     LottoClient client;

 10:

 11:     public LottoEvent(LottoMadness in) {

 12:         gui = in;

 13:         client = new LottoClient();

 14:     }

 15:

 16:     public void actionPerformed(ActionEvent event) {

 17:         String command = event.getActionCommand();

 18:         if (command == "Play") {

 19:             startPlaying();

 20:         }

 21:         if (command == "Stop") {

 22:             stopPlaying();

 23:         }

 24:         if (command == "Reset") {

 25:             clearAllFields();

 26:         }

 27:     }

 28:

 29:     void startPlaying() {

 30:         playing = new Thread(this);

 31:         playing.start();

 32:         gui.play.setEnabled(false);

 33:         gui.stop.setEnabled(true);

 34:         gui.reset.setEnabled(false);

 35:         gui.quickpick.setEnabled(false);

 36:         gui.personal.setEnabled(false);

 37:     }

 38:

 39:     void stopPlaying() {

 40:         gui.stop.setEnabled(false);

 41:         gui.play.setEnabled(true);

 42:         gui.reset.setEnabled(true);

 43:         gui.quickpick.setEnabled(true);

 44:         gui.personal.setEnabled(true);

 45:         playing = null;

 46:         sendResults();

 47:     }

 48:

 49:     void clearAllFields() {

 50:         for (int i = 0; i < 6; i++) {

 51:             gui.numbers[i].setText(null);

 52:             gui.winners[i].setText(null);

 53:         }

 54:         gui.got3.setText("0");

 55:         gui.got4.setText("0");

 56:         gui.got5.setText("0");

 57:         gui.got6.setText("0");

 58:         gui.drawings.setText("0");

 59:         gui.years.setText(null);

 60:     }

 61:

 62:     public void itemStateChanged(ItemEvent event) {

 63:         Object item = event.getItem();

 64:         if (item == gui.quickpick) {

 65:             for (int i = 0; i < 6; i++) {

 66:                 int pick;

 67:                 do {

 68:                     pick = (int) Math.floor(Math.random() * 50 + 1);

 69:                 } while (numberGone(pick, gui.numbers, i));

 70:                 gui.numbers[i].setText("" + pick);

 71:             }

 72:         } else {

 73:             for (int i = 0; i < 6; i++) {

 74:                 gui.numbers[i].setText(null);

 75:             }

 76:         }

 77:     }

 78:

 79:     void addOneToField(JTextField field) {

 80:         int num = Integer.parseInt("0" + field.getText());

 81:         num++;

 82:         field.setText("" + num);

 83:     }

 84:

 85:     boolean numberGone(int num, JTextField[] pastNums, int count) {

 86:         for (int i = 0; i < count; i++) {

 87:             if (Integer.parseInt(pastNums[i].getText()) == num) {

 88:                 return true;

 89:             }

 90:         }

 91:         return false;

 92:     }

 93:

 94:     boolean matchedOne(JTextField win, JTextField[] allPicks) {

 95:         for (int i = 0; i < 6; i++) {

 96:             String winText = win.getText();

 97:             if ( winText.equals( allPicks[i].getText() ) ) {

 98:                 return true;

 99:             }

100:         }

101:         return false;

102:     }

103:

104:     public void run() {

105:         Thread thisThread = Thread.currentThread();

106:         while (playing == thisThread) {

107:             addOneToField(gui.drawings);

108:             int draw = Integer.parseInt(gui.drawings.getText());

109:             float numYears = (float)draw / 104;

110:             gui.years.setText("" + numYears);

111:

112:             int matches = 0;

113:             for (int i = 0; i < 6; i++) {

114:                 int ball;

115:                 do {

116:                     ball = (int)Math.floor(Math.random() * 50 + 1);

117:                 } while (numberGone(ball, gui.winners, i));

118:                 gui.winners[i].setText("" + ball);

119:                 if (matchedOne(gui.winners[i], gui.numbers)) {

120:                     matches++;

121:                 }

122:             }

123:             switch (matches) {

124:                 case 3:

125:                     addOneToField(gui.got3);

126:                     break;

127:                 case 4:

128:                     addOneToField(gui.got4);

129:                     break;

130:                 case 5:

131:                     addOneToField(gui.got5);

132:                     break;

133:                 case 6:

134:                     addOneToField(gui.got6);

135:                     gui.stop.setEnabled(false);

136:                     gui.play.setEnabled(true);

137:                     playing = null;

138:             }

139:             try {

140:                 Thread.sleep(100);

141:             } catch (InterruptedException e) {

142:                 // do nothing

143:             }

144:         }

145:     }

146:

147:     private void sendResults() {

148:         try {

149:             int drawings = Integer.parseInt(gui.drawings.getText());

150:             int got3 = Integer.parseInt(gui.got3.getText());

151:             int got4 = Integer.parseInt(gui.got4.getText());

152:             int got5 = Integer.parseInt(gui.got5.getText());

153:             int got6 = Integer.parseInt(gui.got6.getText());

154:             client.send(drawings, got3, got4, got5, got6);

155:         } catch (NumberFormatException nfe) {

156:             // do nothing

157:         } catch (Exception exception) {

158:             System.out.println("Error: " + exception.getMessage());

159:             exception.printStackTrace();

160:         }

161:     }

162: }

When you compile LottoEvent.java, the compiler also prepares any other classes belonging to the project as needed. Run the application by executing LottoMadness with the interpreter:

java LottoMadness

The LottoMadness application opens as it did in Hour 15.

A new instance variable of the LottoClient class is declared in Line 9 and created in the constructor in Line 13:

LottoClient client;

client = new LottoClient();

Every time you stop an ongoing series of the drawings, the application calls a new sendResults() method in the stopPlaying() method in Line 46:

sendResults();

This method, defined in Lines 147–161, retrieves each drawing value from a field of the user interface:

int drawings = Integer.parseInt(gui.drawings.getText());

The gui object is the LottoMadness object holding the user interface, which has a text field called drawings. Calling its getText() method retrieves the contents of the field as a string.

The six fields become arguments to the LottoClient object's send() method:

client.send(drawings, got3, got4, got5, got6);


Summary

By design, this first look at XML-RPC programming in Java contained no details about the underlying XML delivered in each method call and returned value.

Apache XML-RPC makes this possible, as do other software libraries that support the protocol. Though it may prove helpful to extend your knowledge at some point into the nitty-gritty details of XML-RPC's data types, you can adopt the protocol entirely with techniques, data types, and classes in Java.

XML-RPC makes it possible to create web services with a small amount of coding, taking requests and exchanging information over the Internet, a home office network, or another environment.

If you branch out into another programming language, you're likely to find an XML-RPC implementation for it as well. This bridge from one language of expertise to another can be a great boon.

Because this hour doesn't officially exist, you already received my heartfelt congratulations on a job well done during Hour 24. We had a very emotional farewell. You probably haven't forgotten it, and I'll always cherish our time together despite the intemperate things you said back in Hour 2 when that program wouldn't compile.

I applaud you for devoting so much time and effort to a great programming language.

XML-RPC is an appropriate subject to end your first foray into programming because it brings together three of the most exciting things about developing software today: the Java language, the XML data formatting standard, and XML-RPC web services.

Using this kind of technology at no cost is a far cry from when I began programming professionally as a woefully awkward but understatedly handsome college freshman in the mid-'80s.

The choices of the day were C, dozens of cumbersome data formats specific to different software, and no online networks more sophisticated than a dialup, single-line computer running a bulletin board system at glacial 300-baud speed.

It's a cliche to compare the jolt of Java to the caffeine high of a cup of coffee, but that didn't stop me in the preceding 424 pages, and it won't stop me now.

When you're knowledgeable enough to code your own projects for Java that use XML and XML-RPC, it's a major buzz.


Q&A

Q1:

My XML-RPC handler class has public methods that return void because I don't need a returned value. Why don't these work in XML-RPC?

A1:

They may work in other implementations of the XML-RPC protocol, but Apache XML-RPC doesn't support void as a return type in classes that receive method calls.

The LottoCounter class didn't need to return a value in its sendRequest() method either, so it returns the Boolean value TRue in all circumstances.

Q2:

How does XML-RPC compare to RMI?

A2:

Remote Method Invocation (RMI) is a technique to call one Java class from another class over any network. RMI requires placeholder classes called stubs and skeletons that serve as proxies for classes on a different computer.

RMI also requires a registry tool that connects RMI clients and servers to ports, delivering method calls and responses back and forth.

Most XML-RPC implementations are simpler to implement than RMI. They require method-calling techniques different than Java, unlike an all-Java solution like RMI, but offer a compensating advantage: the ability to work with software developed in other languages.

Q3:

Did people really ask you questions about spam, ticket prices in the Colosseum, and brainfreeze, or did you just make up those questions like you made up this one?

A3:

Every one of those questions was legit. I used to write a newspaper column for the Fort Worth Star-Telegram and the New York Times Newspaper Syndicate that answered any question posed by readers, answering more than 2,500 of them.

If there are any of life's great mysteries you've yet to solve, such as the best way to make a batch of blueberry pancakes without buttermilk, visit this book's website at http://www.java24hours.com and use the feedback link. The ones I'm able to answer will appear on my weblog.

As for the pancakes, whisk one tablespoon of squeezed lemon juice into two cups milk, then let it sit while you prepare the other ingredients. And be careful with the fresh blueberries. Drop them in too early and the pancake will turn a funereal shade of gray.

Q4:

Boxers or briefs?

A4:

Candy-apple red thong underwear with the embroidered text "My dog can beat up Paris Hilton's dog."


Quiz

To see whether you can deliver information upon request across great distances, answer the following questions about XML-RPC in Java.

Questions

1:

What does XML-RPC stand for?

  1. XML Remote Procedure Call

  2. XML Rapid Paramilitary Commandos

  3. XML Resists Programmer Comprehension

2:

If a public method in an XML-RPC handler class returns an int, what form will it take when returned by a client's execute() method?

  1. int

  2. Integer

  3. It won't—XML-RPC doesn't support integers.

3:

An applet making an XML-RPC call can connect to how many different computers?

  1. 0

  2. 1

  3. As many as desired

Answers

A1: | a. Other techniques to make remote procedure calls include the Common Object Request Broker Architecture (CORBA), Open Network Computing RPC, and the web services protocol, SOAP.
A2: | b. The execute() method always returns an object that must be cast to the proper class. An int value is returned as an Integer object representing the same value.
A3: | b. For security reasons, the applet only may call an XML-RPC server on the same computer that served the applet to a browser.


Activities

To extend your knowledge of XML-RPC, code a response to the following activities:

  • The Advogato website offers an XML-RPC server at http://www.advogato.org/ XMLRPC that has a test.square method that returns the square of a specified number. Write an application that takes user input, calls this method, and displays the result.

  • Write an XML-RPC server application that mimics Advogato, taking the test.square call and returning the square of the number.

To see Java programs that implement these activities, visit the book's website at http://www.java24hours.com.


    Part VIII: Appendixes

    APPENDIX A Using the Java Development Kit

    APPENDIX B Programming with the Java Development Kit

    APPENDIX C Using the NetBeans Integrated Development Environment

    APPENDIX D Where to Go from Here: Java Resources

    APPENDIX E This Book's Website


Appendix A. Using the Java Development Kit

  • Choosing a Java Development Tool

  • Configuring the Java Development Kit

  • Using a Text Editor

  • Creating a Sample Program

  • Setting Up the CLASSPATH Variable

To spur development, Sun Microsystems offers the Java Development Kit, a free tool to write programs with the language.

The Java Development Kit is a set of command-line programs that are used to create, compile, and run Java programs. Every new release of Java is accompanied by a new release of the development kit: The current version is Java 2 JDK version 5.

Although more sophisticated Java programming tools such as Borland JBuilder, IntelliJ IDEA, and Eclipse JDT are available, many programmers continue to use the Java Development Kit. I've been using it as my primary Java programming tool for years.

This appendix covers how to download and install the Java Development Kit, set it up on your computer, and use it to create, compile, and run a simple Java program.

It also describes how to correct the most common cause of problems for a beginning Java programmer—a misconfigured Java Development Kit.


Choosing a Java Development Tool

If you're using a Microsoft Windows or Apple MacOS system, you probably have a Java interpreter installed that can run Java programs.

To develop Java programs, you need more than an interpreter. You also need a compiler and other tools that are used to create, run, and test programs.

The Java Development Kit includes a compiler, interpreter, debugger, file archiving program, and several other programs.

The kit is simpler than other development tools. It does not offer a graphical user interface, text editor, or other features that many programmers rely on.

To use the kit, you type commands at a text prompt. MS-DOS, Linux, and Unix users will be familiar with this prompt, which is also called a command line.

Here's an example of a command you might type while using the Java Development Kit:

javac RetrieveMail.java

This command tells the javac program—the Java compiler included with the JDK—to read a source code file called RetrieveMail.java and create one or more class files. These files contain compiled bytecode that can be executed by a Java interpreter.

When RetrieveMail.java is compiled, one of the files will be named RetrieveMail.class. If the class file was set up to function as an application, a Java interpreter can run it.

People who are comfortable with command-line environments will be at home using the Java Development Kit. Everyone else must become accustomed to the lack of a graphical point-and-click environment as they develop programs.

If you have another Java development tool and you're certain it is completely compatible with Java 2 Version 5, you don't need to use the Java Development Kit. Many different development tools can be used to create the tutorial programs in this book.

Watch Out!

If you have any doubts regarding compatibility, or this book is your first experience with the Java language, you should probably use JDK 5 or a tool described in Appendix C, "Using the NetBeans Integrated Development Environment."

NetBeans, which can be downloaded from Sun as a bundle with the JDK, offers a graphical user interface that functions on top of the JDK.

Installing the Java Development Kit

You can download the Java Development Kit from Sun's Java website at http://java.sun.com.

The website's Downloads section offers links to several different versions of the Java Development Kit, and it also offers the NetBeans development environment and other products related to the language. The product you should download is called the Java 2 Software Development Kit, Standard Edition, version 5. If you can't find it in the Downloads section of the site, look for an Early Access section that offers beta releases.

JDK 5 is available for the following platforms:

  • Windows 98, Me, NT (with Service Pack 4), 2000, XP Home, XP Professional (with Service Pack 1), and Server 2003

  • Solaris SPARC and Intel

  • Linux

The kit requires a computer with a Pentium processor that is 166 MHz or faster, 32MB of memory, and 150MB of free disk space. Sun recommends at least 48MB of memory if you're going to work with Java 2 applets (which you'll do in Hour 17, "Creating Interactive Web Programs").

Did you Know?

The Macintosh version of the JDK is available directly from Apple. To find out more about Apple's kit and download the tool, visit the website http://developer.apple.com/java/download.

When you're looking for this product, you might find that the Java Development Kit's version number has a third number after 5, such as "JDK 5.1." To fix bugs and address security problems, Sun periodically issues new releases of the kit and numbers them with an extra period and digit after the main version number. Choose the most current version of JDK 5 that's offered, whether it's numbered 5.0, 5.1, 5.2, or higher.

Watch Out!

Take care not to download two similarly named products from Sun by mistake: the Java 2 Runtime Environment, Standard Edition, version 5 or the Java 2 Software Development Kit, Standard Edition, Source Release.

To go directly to the kit's download page, the current address is http://java.sun.com/j2se/1.5.

To set up the kit, you must download and run an installation program (or install it from a CD). On Sun's website, after you choose the version of the kit that's designed for your operating system, you can download it as a single file.

After you have downloaded the file, you'll be ready to set up the development kit.

Windows Installation

Before installing the JDK, make sure that no other Java development tools are installed on your system (assuming, of course, which you don't need any other tool at the moment). Having more than one Java programming tool installed on your computer can often cause configuration problems with the Java Development Kit.

To set up the program on a Windows system, double-click the installation file or click Start, Run from the Windows taskbar to find and run the file.

The InstallShield wizard guides you through the process of installing the software. If you accept Sun's terms and conditions for using the kit, you'll be asked where to install the program, as shown in Figure A.1.

Figure A.1. Choose a destination folder for the JDK.

The wizard suggests a folder where the kit should be installed. In Figure A.1, the wizard is suggesting the folder C:\Program Files\Java\jdk1.5.0. When you install the kit, the suggested name might be different.

To choose a different folder, click the Change button, then either select or create a new folder and click OK. The wizard returns to the Custom Setup options.

Did you Know?

Before continuing, write down the name of the folder you have chosen. You'll need it later to configure the kit and fix any configuration problems that may occur.

You also are asked what parts of the Java Development Kit to install. By default, the wizard will install all components of the JDK:

  • Development Tools— The executable programs needed to create Java software

  • Demos— Java 2 programs you can run and the source code files used to create them, which you can examine to learn about the language

  • Source Code— The source code for the thousands of classes that make up the Java 2 class library

  • Public Java 2 Runtime Environment (JRE)— A Java interpreter you can distribute with the programs you create

If you accept the default installation, you need around 132MB of free hard disk space. You can save space by omitting everything but the program files. However, the demo programs and Java 2 runtime environment are extremely useful, so if you have the room, it's a good idea to install them.

The source files are not needed for any of the material in this book; they are primarily of interest to experienced Java programmers.

To prevent a component from being installed, click the hard drive icon next to its name and then choose the Don't Install This Feature Now option.

After you choose the components to install, click the Next button to continue. You may be asked whether to set up the Java Plug-in to work with the web browsers on your system.

The Java Plug-in is an interpreter that runs Java programs incorporated into web pages. These programs, which are called applets, can work with different interpreters, but most browsers do not include an interpreter that supports the current version of the Java language. Sun offers the plug-in to provide full language support to Microsoft Internet Explorer, Mozilla, Opera, and other browsers.

After you complete configuration, the InstallShield wizard installs the JDK on your system.


Configuring the Java Development Kit

After the InstallShield wizard installs the JDK, you must edit your computer's environment variables to include references to the kit.

Experienced MS-DOS users can finish setting up the JDK by adjusting two variables and then rebooting the computer:

  • Edit the computer's PATH variable and add a reference to the Java Development Kit's bin folder (which is C:\Program Files\Java\jdk1.5.0\bin if you installed the kit into the C:\Program Files\Java\jdk1.5.0 folder).

  • Edit or create a CLASSPATH variable so that it contains a reference to the current folder—a period character and semicolon (".;" without the quotation marks)—followed by a reference to the tools.jar file in the kit's lib folder (which is C:\Program Files\Java\jdk1.5.0\lib\tools.jar if the kit was installed into C:\Program Files\Java\jdk1.5.0).

For inexperienced MS-DOS users, the following section covers in detail how to set the PATH and CLASSPATH variables on a Windows system.

Users of other operating systems should follow the instructions provided by Sun on its Java Development Kit download page.

Using a Command-Line Interface

The Java Development Kit requires the use of a command line to compile Java programs, run them, and handle other tasks.

A command line is a way to operate a computer entirely by typing commands at your keyboard, rather than by using a mouse. Very few programs designed for Windows users require the command line today.

By the Way

To get to a command line in Windows:

  • On Windows 98 or Me, choose Start, Programs, and then choose MS-DOS Prompt.

  • On Windows NT or 2000, choose Start, Programs, Accessories, and then choose Command Prompt.

  • On Windows XP or Windows Server 2003, choose Start, All Programs, Accessories, and then choose Command Prompt.

When you open a command line in Windows, a new window opens in which you can type commands.

The command line in Windows uses commands adopted from MS-DOS, the Microsoft operating system that preceded Windows. MS-DOS supports the same functions as Windows—copying, moving, and deleting files and folders; running programs; scanning and repairing a hard drive; formatting a floppy disk; and so on. Figure A.2 shows a command-line window.

Figure A.2. Using a newly opened command-line window.

[View full size image]

In the window, a cursor blinks on the command line whenever you can type in a new command. In Figure A.2, C:\Documents and Settings\Rogers> is the command line.

Because MS-DOS can be used to delete files and even format your hard drive, you should learn something about the operating system before experimenting with its commands. If you would like to learn a lot about MS-DOS, a good book is Special Edition Using MS-DOS 6.22, Third Edition, published by Que (emphasis on the words "a lot"—the book is 1,056 pages long).

However, you only need to know a few things about MS-DOS to use the Java Development Kit: how to create a folder, how to open a folder, and how to run a program.

Opening Folders in MS-DOS

When you are using MS-DOS on a Windows system, you have access to all the folders you normally use in Windows. For example, if you have a Windows folder on your C: hard drive, the same folder is accessible as C:\Windows from a command line.

To open a folder in MS-DOS, type the command CD followed by the name of the folder and press Enter. Here's an example:

CD C:\TEMP

When you enter this command, the TEMP folder on your system's C: drive will be opened, if it exists. After you open a folder, your command line will be updated with the name of that folder, as shown in Figure A.3.

Figure A.3. Opening a folder in a command-line window.

[View full size image]

You also can use the CD command in other ways:

  • Type CD \to open the root folder on the current hard drive.

  • Type CD foldername to open a subfolder matching the name you've used in place of foldername, if that subfolder exists.

  • Type CD .. to open the folder that contains the current folder. For example, if you are in C:\Windows\Fonts and you use the CD .. command, C:\Windows will be opened.

One of the book's suggestions is to create a folder called J24work where you can create the tutorial programs described in the book. If you already have done this, you can switch to that folder by using the following commands:

  1. CD \

  2. CD J24work

If you haven't created that folder yet, you can accomplish the task using an MS-DOS command.

Creating Folders in MS-DOS

To create a folder from a command line, type the command MD followed by the name of the folder and press Enter, as in the following example:

MD C:\STUFF

The STUFF folder will be created in the root folder of the system's C: drive. To open a newly created folder, use the CD command followed by that folder's name, as shown in Figure A.4.

Figure A.4. Creating a new folder in a command-line window.

[View full size image]

If you haven't already created a J24work folder, you can do it from a command line:

  • Change to the root folder (using the CD \command).

  • Type the command MD J24work and press Enter.

After J24work has been created, you can go to it at any time from a command-line by using this command:

CD \J24work

The last thing you need to learn about MS-DOS to use the Java Development Kit is how to run programs.

Running Programs in MS-DOS

The simplest way to run a program at the command line is to type its name and press Enter. For example, type DIR and press Enter to see a list of files and subfolders in the current folder.

You also can run a program by typing its name followed by a space and some options that control how the program runs. These options are called arguments.

To see an example of this, change to the root folder (using CD \) and type DIR J24work. You'll see a list of files and subfolders contained in the J24work folder, if it contains any.

After you have installed the Java Development Kit, run the Java interpreter to see that it works. Type the following command at a command line:

java -version

In the preceding example, java is the name of the Java interpreter program and -version is an argument that tells the interpreter to display its version number.

You can see an example of this in Figure A.5, but your version number might be a little different depending on what version of the JDK you have installed.

Figure A.5. Running the Java interpreter in a command line window.

[View full size image]

If java -version works and you see a version number, it should begin with 1.5. Sun sometimes tacks on a third number, but as long as it begins with 1.5 you are using the correct version of the Java Development Kit.

If you see an incorrect version number or a Bad command or filename error after running java -version, you need to make some changes to how the Java Development Kit is configured on your system.

Watch Out!

Sun has used two numbers to describe the current version of Java, changing it from "Java 2 version 1.5" to "Java 2 version 5" shortly before release. The version number of the JDK was not changed internally, so it remains 1.5.

Adding to the confusion, Sun also recently revived the name Java Development Kit (JDK), a name it stopped using several years ago in favor of the Software Development Kit (SDK). You'll hear the kit described as both SDK 1.5 and SDK 5.

When all else fails, run the java -version command to make sure the right development tool has been installed on your system. If it begins with 1.5, you can develop programs for Java 2 version 5.

Correcting Configuration Errors

When you are writing Java programs for the first time, the most likely source for problems is not typos, syntax errors, or other programming mistakes. Most errors result from a misconfigured Java Development Kit.

If you type java -version at a command line and your system can't find the folder that contains java.exe, you will see one of the following error messages or something similar (depending on your operating system):

  • Bad command or file name

  • 'java' is not recognized as an internal or external command, operable program, or batch file

To correct this, you must configure your system's PATH variable.

Setting the PATH on Windows 98, or Me

On a Windows 98 or Me system, you configure the PATH variable by editing the AUTOEXEC.BAT file in the root folder of your main hard drive. This file is used by MS-DOS to set environment variables and configure how some command-line programs function.

AUTOEXEC.BAT is a text file you can edit with Windows Notepad. Start Notepad by choosing Start, Programs, Accessories, Notepad from the Windows taskbar.

The Notepad text editor opens. Choose File, Open from Notepad's menu bar, go to the root folder on your main hard drive, and then open the file AUTOEXEC.BAT.

When you open the file, you'll see a series of MS-DOS commands, each on its own line, as shown in Figure A.6.

Figure A.6. Editing the AUTOEXEC.BAT file with Notepad.

[View full size image]

The only commands you need to look for are any that begin with PATH.

The PATH command is followed by a space and a series of folder names separated by semicolons. It sets up the PATH variable, a list of folders that contain command-line programs you use.

PATH is used to help MS-DOS find programs when you run them at a command line. In the preceding example, the PATH command in Figure A.6 includes two folders:

  • C:\PROGRA~1\MSBOB

  • C:\jdk1.5.0\bin

You can see what PATH has been set to by typing the following command at a command line:

PATH

To set up the Java Development Kit correctly, the folder that contains the Java interpreter must be included in the PATH command in AUTOEXEC.BAT.

The interpreter has the filename java.exe. If you installed JDK 1.5 in the C:\Program Files\Java\jdk1.5.0 folder on your system, java.exe is in C:\Program Files\Java\jdk1.5.0\bin.

If you can't remember where you installed the kit, you can look for java.exe: Choose Start, Find, Files or Folders. You might find several copies in different folders. To see which one is correct, open a command-line window and do the following for each copy you have found:

  1. Use the CD command to open a folder that contains java.exe.

  2. Run the command java -version in that folder.

When you know the correct folder, create a blank line at the bottom of the AUTOEXEC.BAT file and add the following:

PATH rightfoldername;%PATH%

For example, if c:\Program Files\Java\jdk1.5.0\bin is the correct folder, the following line should be added at the bottom of AUTOEXEC.BAT:

PATH c:\"Program Files"\Java\jdk1.5.0\bin;%PATH%

The %PATH% text keeps you from wiping out any other PATH commands in AUTOEXEC.BAT. In this command, quote marks have been added around the folder name Program Files. Some versions of Windows require this to handle folder names that contain spaces.

After making changes to AUTOEXEC.BAT, save the file and reboot your computer. When this is done, try the java -version command.

If it displays the correct version of the Java Development Kit, your system is probably configured correctly. You'll find out for sure when you try to create a sample program later in this appendix.

Setting the Path on Windows NT, 2000, or XP

On a Windows NT, XP, 2000, or 2003 system, you configure the Path variable using the Environment Variables dialog, one of the features of the system's Control Panel.

To open this dialog box:

1.
Right-click the My Computer icon on your desktop or choose Start, Properties. The System Properties dialog box opens.

2.
Click the Advanced tab to bring it to the front.

3.
Click the Environment Variables button. The Environment Variables dialog box opens (see Figure A.7).

Figure A.7. Setting environment variables in Windows NT, XP, 2000, or 2003.

[View full size image]

You can edit two kinds of environment variables: system variables, which apply to all users on your computer, and user variables, which only apply to you.

Path is a system variable that helps MS-DOS find programs when you run them at a command line. It contains a list of folders separated by semicolons.

To set up the Java Development Kit correctly, the folder that contains the Java interpreter must be included in the Path. The interpreter has the filename java.exe. If you installed JDK 1.5 in the C:\Program Files\Java\jdk1.5.0 folder on your system, java.exe is in C:\Program Files\Java\jdk1.5.0\bin.

If you can't remember where you installed the kit, you can look for java.exe: Choose Start, Search. You might find several copies in different folders. To see what one is correct, open a command-line window and do the following for each copy you have found:

1. | Use the CD command to open a folder that contains java.exe.
2. | Run the command java -version in that folder.

When you know the correct folder, return to the Environment Variables dialog, select Path in the System variables list, and then click Edit. The Edit System Variable dialog opens with Path in the Variable name field and a list of folders in the Variable Value field (see Figure A.8).

Figure A.8. Changing your system's Path variable.

To add a folder to the Path, click the Variable Value field and move your cursor to the end without changing anything. At the end, add a semicolon followed by the name of the folder that contains the Java interpreter.

For example, if c:\Program Files\Java\jdk1.5.0\bin is the correct folder, the following text should be added to the end of the Path variable:

c:\Program Files\Java\jdk1.5.0\bin

After making the change, click OK twice: once to close the Edit System Variable dialog, and another time to close the Environment Variables dialog.

Try it: Open a command-line window and type the command java -version.

If it displays the right version of the Java Development Kit, your system is probably configured correctly, though you won't know for sure until you try to use the kit later in this appendix.


Using a Text Editor

Unlike more sophisticated Java development tools, the Java Development Kit does not include a text editor to use when you create source files.

For an editor or word processor to work with the kit, it must be able to save text files with no formatting.

This feature has different names in different editors. Look for a format option such as one of the following when you save a document or set the properties for a document:

  • Plain text

  • ASCII text

  • DOS text

  • Text-only

If you're using Windows, there are several editors included with the operating system.

Windows Notepad is a no-frills text editor that only works with plain-text files. It can handle only one document at a time. Choose Start, All Programs, Accessories, Notepad to run it on Windows XP or choose Start, Programs, Accessories, Notepad on other Windows systems.

Windows WordPad is a step above Notepad. It can handle more than one document at a time and can handle both plain-text and Microsoft Word formats. It also remembers the last several documents it has worked on and makes them available from the File pull-down menu. It's also on the Accessories menu along with Notepad.

Windows users also can use Microsoft Word, but must save files as text rather than in Word's proprietary format. (Unix and Linux users can author programs with emacs, pico, and vi; Macintosh users have SimpleText or any of the aforementioned Unix tools available for Java source file creation.)

One disadvantage of using simple text editors such as Notepad or WordPad is that they do not display line numbers as you edit.

Seeing the line number helps in Java programming because many compilers indicate the line number at where an error occurred. Take a look at the following error generated by the JDK compiler:

Palindrome.java:2: Class Font not found in type declaration.

The number 2 after the name of the Java source file indicates the line that triggered the compiler error. With a text editor that supports numbering, you can go directly to that line and start looking for the error.

Usually there are better ways to debug a program with a commercial Java programming package, but kit users must search for compiler-generated errors using the line number indicated by the javac tool. This is one of the best reasons to move on to an advanced Java development program after learning the language with the Java Development Kit.

Did you Know?

Another alternative is to use the kit with a programmer's text editor that offers line numbering and other features. One of the most popular for Java is jEdit, a free editor available for Windows, Linux, and other systems at the website http://www.jedit.org.

I can personally recommend UltraEdit, an excellent programmer and web designer's editor that sells for $35 at the time of this writing. To find out more and download a trial version, visit the website http://www.ultraedit.com.


Creating a Sample Program

Now that you have installed and set up the Java Development Kit, you're ready to create a sample Java program to make sure that it works.

Java programs begin as source code—a series of statements created using a text editor and saved as a text file. You can use any program you like to create these files, as long as it can save the file as plain, unformatted text.

The Java Development Kit does not include a text editor, but most other Java development tools include a built-in editor for creating source code files.

Run your editor of choice and enter the Java program in Listing A.1. Make sure all the parentheses, braces, and quotation marks in the listing are entered correctly and capitalize everything in the program exactly as shown. If your editor requires a filename before you start entering anything, call it HelloUser.java.

Listing A.1. Source Code of HelloUser.java

1: public class HelloUser {

2:     public static void main(String[] arguments) {

3:         String username = System.getProperty("user.name");

4:         System.out.println("Hello " + username);

5:     }

The line numbers and colons along the left side of Listing A.1 are not part of the program—they're included, so that I can refer to specific lines by number in each program. If you're ever unsure about the source code of a program in this book, you can compare it to a copy on the book's official World Wide Web site at the following address:

http://www.java24hours.com

After you finish typing in the program, save the file somewhere on your hard drive with the name HelloUser.java. Java source files must be saved with the extension .java.

Did you Know?

If you have created a folder called J24work, save HelloUser.java and all other Java source files from this book in that folder. This makes it easier to find them while using a command-line window.

If you're using Windows, a text editor such as Notepad might add an extra .txt file extension to the filename of any Java source files you save. For example, HelloUser.java is saved as HelloUser.java.txt. As a work-around to avoid this problem, place quotation marks around the filename when saving a source file. Figure A.9 shows this technique being used to save the source file HelloUser.java from Windows Notepad.

Figure A.9. Saving a source file from Windows Notepad.

[View full size image]

Did you Know?

A better solution is to permanently associate .java files with the text editor you'll be using: In Windows, open the folder that contains HelloUser.java and double-click the file. If you have never opened a file with the .java extension, you'll be asked what program to use when opening files of this type. Choose your preferred editor and select the option to make your choice permanent. From this point on, you can open a source file for editing by double-clicking the file.

The purpose of this project is to test the Java Development Kit—none of the Java programming concepts used in the five-line HelloUser program are described in this appendix.

You'll learn the basics of the language during the four hours of Part 1, "Getting Started!" If you have figured out anything about Java simply by typing in the source code of Listing A.1, it's entirely your own fault.

Compiling and Running the Program in Windows

Now you're ready to compile the source file with the Java Development Kit's Java compiler, a program called javac. The compiler reads a .java source file and creates one or more .class files that can be run by a Java interpreter.

Open a command-line window, and then open the folder where you saved HelloUser.java.

If you saved the file in the J24work folder inside the root folder on your main hard drive, the following MS-DOS command opens the folder:

cd \J24work

When you are in the correct folder, you can compile HelloUser.java by entering the following at a command prompt:\

javac HelloUser.java

Figure A.10 shows the MS-DOS commands used to switch to the \J24work folder and compile HelloUser.java.

Figure A.10. Compiling a Java program in a command-line window.

[View full size image]

The Java Development Kit compiler does not display any message if the program compiles successfully. If there are problems, the compiler enables you to know by displaying each error along with a line that triggered the error.

If the program compiled without any errors, a file called HelloUser.class is created in the same folder that contains HelloUser.java.

The class file contains the Java bytecode that will be executed by a Java interpreter. If you get any errors, go back to your original source file and make sure that you typed it exactly as it appears in Listing A.1.

After you have a class file, you can run that file using a Java interpreter. The JDK's interpreter is called java, and it also is run from the command line.

Run the HelloUser program by switching to the folder containing HelloUser.class and entering the following:

java HelloUser

You will see the text "Hello" followed by a comma and your username.

By the Way

When running a Java class with the kit's Java interpreter, don't specify the .class file extension after the name of the class. If you do, you'll see an error such as the following:

Exception in thread "main" java.lang.NoClassDefFoundError:

   HelloUser/class

Figure A.11 shows the successful output of the HelloUser application along with the commands used to get to that point.

Figure A.11. Running a Java application.

[View full size image]

If you can compile the program and run it successfully, your Java Development Kit is working and you are ready to start Hour 1 of this book.

If you cannot get the program to compile successfully even though you have typed it exactly at it appears in the book, there may be one last problem with how the Java Development Kit is configured on your system: the CLASSPATH environment variable might need to be configured.


Setting Up the CLASSPATH Variable

All the Java programs that you write rely on two kinds of class files: the classes you create and the Java class library, a set of hundreds of classes that represent the functionality of the Java language.

The Java Development Kit needs to know where to find Java class files on your system. In many cases, the kit can figure this out on its own by looking in the folder where it was installed.

You also can set it up yourself by creating or modifying another environment variable: CLASSPATH.

Setting the CLASSPATH on Windows 98 or Me

If you have compiled and run the HelloUser program successfully, the Java Development Kit has been configured successfully. You don't need to make any more changes to your system.

On the other hand, if you see a Class not found error or NoClassDefFound error whenever you try to run a program, you need to make sure your CLASSPATH variable is set up correctly.

To do this, run Windows Notepad, choose File, Open and go to the root folder on your system, and then open the file AUTOEXEC.BAT. A file containing several different MS-DOS commands is opened in the editor, as shown in Figure A.12.

Figure A.12. Editing your system's environment variables.

Look for a line in the file that contains the text SET CLASSPATH= command followed by a series of folder and filenames separated by semicolons.

CLASSPATH is used to help the Java compiler find the class files that it needs. The SET CLASSPATH= command in Figure A.12 included two things with a semicolon between them:

  • .

  • c:\jdk1.5.0\lib\tools.jar

A CLASSPATH can contain folders or files. It also can contain a period character ("."), which is another way to refer to the current folder in MS-DOS.

You can see your system's CLASSPATH variable by typing the following command at a command line:

ECHO %CLASSPATH%

If your CLASSPATH includes folders or files that you know are no longer on your computer, you should remove the references to them on the SET CLASSPATH= line in AUTOEXEC.BAT. Make sure to remove any extra semicolons also.

To set up the Java Development Kit correctly, the file containing the Java class library must be included in the SET CLASSPATH= command. This file has the filename tools.jar. If you installed the kit in the C:\Program Files\Java\jdk1.5.0 folder on your system, tools.jar is probably in the folder C:\Program Files\Java\jdk1.5.0\lib.

If you can't remember where you installed the kit, you can look for tools.jar by clicking Start, Find, Files or Folders from the Windows taskbar. If you find several copies, you should be able to find the correct one using this method:

1. | Use CD to open the folder that contains the Java interpreter (java.exe).
2. | Enter the command CD ...
3. | Enter the command CD lib.

The lib folder normally contains the right copy of tools.jar.

When you know the correct location, create a blank line at the bottom of the AUTOEXEC.BAT file and add the following:

SET CLASSPATH=%CLASSPATH%;.;rightlocation

For example, if tools.jar file is in the c:\Program Files\Java\jdk1.5.0\lib folder, the following line should be added at the bottom of AUTOEXEC.BAT:

SET CLASSPATH=%CLASSPATH%;.;c:\"Program Files"\Java\jdk1.5.0\lib\tools.jar

After making changes to AUTOEXEC.BAT, save the file and reboot your computer. After this is done, try to compile and run the HelloUser sample program again. You should be able to accomplish this after the CLASSPATH variable has been set up correctly.

Setting the Classpath on Windows NT, XP, 2000, or 2003

On a Windows NT, XP, 2000, or 2003 system, you also configure the Classpath variable using the Environment Variables dialog.

To open it:

1.
Right-click the My Computer icon on your desktop or Start menu and choose Properties. The System Properties dialog box opens.

2.
Click the Advanced tab to bring it to the front.

3.
Click the Environment Variables button. The Environment Variables dialog box opens (see Figure A.13).

Figure A.13. Setting environment variables in Windows NT, XP, 2000, or 2003.

[View full size image]

If your system has a Classpath variable, it will probably be one of the system variables. Your system may not a Classpath—the Java Development Kit can normally find class files without the variable.

However, if your system has a Classpath, it must be set up with at least two things: a reference to the current folder (a period) and a reference to a file that contains the Java class library: tools.jar.

If you installed the kit in the C:\Program Files\Java\jdk1.5.0 folder, tools.jar is in the folder C:\Program Files\Java\jdk1.5.0\lib.

If you can't remember where you installed the kit, you can look for tools.jar by clicking Start, Search from the Windows taskbar. If you find several copies, you should be able to find the correct one using this method:

1. | Use CD to open the folder that contains the Java interpreter (java.exe).
2. | Enter the command CD ...
3. | Enter the command CD lib.

The lib folder normally contains the right copy of tools.jar.

When you know the correct folder, return to the Environment Variables dialog shown in Figure A.13.

If your system does not have a Classpath, click the New button under the System variables list. The New System Variable dialog box opens.

If your system has a Classpath, choose it and click the Edit button. The Edit System Variable dialog box opens.

Both boxes contain the same thing: a Variable Name field, and a Variable Value field.

Enter Classpath in the Variable Name field and the correct value for your Classpath in the Variable Value field.

For example, if you installed the Java Development Kit in c:\Program Files\Java\jdk1.5.0, your Classpath should contain the following:

.;C:\"Program Files"\Java\jdk1.5.0\lib\tools.jar

Figure A.14 shows how I set up Classpath for my system, which has the Java Development Kit installed in C:\jdk1.5.0.

Figure A.14. Setting up a Classpath in Windows XP.

After setting up your Classpath, click OK twice: once to close the Edit or New System Variable dialog box, and another time to close the Environment Variables dialog.

Unlike Windows 98 and Me users, you don't have to reboot the system before you can try it out. Open a new command-line window and type the command java -version.

If it displays the right version of the Java Development Kit, your system might be configured correctly and require no more adjustments. Try creating the sample HelloUser program again—it should work after the classpath variable has been set up correctly.

Troubleshooting Your Kit Installation

This book has a website where you can find solutions to problems, corrections, answers to reader questions, and other useful material: http://www.java24hours.com.

If you are still having problems with the Java Development Kit, an online version of this appendix is available on the site.


Appendix B. Programming with the Java Development Kit

The Java Development Kit (JDK) can be used throughout this book to create, compile, and run Java programs.

The tools that make up the kit contain numerous features that many programmers don't explore at all, and some of the tools themselves might be new to you.

This appendix covers features of the JDK that you can use to create more reliable, better-tested, and faster-running Java programs.

The following topics will be covered:

  • Running Java applications with the interpreter

  • Compiling programs with the compiler

  • Running Java applets with the applet viewer

  • Creating documentation with the documentation tool

  • Finding bugs in your program and learning more about its performance with the debugger

  • Setting system properties with the interpreter and applet viewer


An Overview of the JDK

Although there are several dozen development environments you can use to create Java programs, the most widely used is the Java Development Kit (JDK) from Sun Microsystems, the set of command-line tools that are used to develop software with the Java language.

There are two main reasons for the popularity of the kit:

  • It's free. You can download a copy at no cost from Sun's official Java World Wide Web site at http://java.sun.com.

  • It's first. Whenever Sun releases a new version of the language, the first tools that support the new version are in the JDK.

The JDK uses the command line—also called the MS-DOS prompt, command prompt, or console under Windows; and the shell prompt under Unix. Commands are entered using the keyboard, as in the following example:

javac VideoBook.java

This command compiles a Java program called VideoBook.java using the JDK compiler. There are two elements to the command: the name of the JDK compiler, javac, followed by the name of the program to compile, VideoBook.java. A space character separates the two elements.

Each JDK command follows the same format: the name of the tool to use followed by one or more elements indicating what the tool should do. These elements are called arguments.

The following illustrates the use of command-line arguments:

java VideoBook add VHS "Invasion of the Bee Girls"

This command tells the Java interpreter to run a class file called VideoBook with three command-line arguments: the strings add, VHS, and Invasion of the Bee Girls.

By the Way

You might think there are more than three command-line arguments because of the spaces in the string Invasion of the Bee Girls. The quotation marks around that string cause it to be considered one command-line argument, which makes it possible to include spaces in an argument.

Some arguments used with the JDK modify how a tool functions. These arguments are preceded by a hyphen character and are called options.

The following command shows the use of an option:

java -version

This command tells the Java interpreter to display its version number rather than trying to run a class file. It's a good way to find out whether the JDK is correctly configured to run Java programs on your system. Here's an example of the output run on a system equipped with JDK 5.0:

java version "1.5.0"

Java(TM) 2 Runtime Environment, Standard Edition (build1.5.0)

Java HotSpot(TM) Client VM (build 1.5.0, mixed mode)

The version reflects Sun's internal number for the JDK 5, which is 1.5.

In some instances, you can combine options with other arguments. For example, if you compile a Java class that uses deprecated methods, you can see more information on these methods by compiling the class with a -deprecation option, as in the following:

javac -deprecation OldVideoBook.java


The java Interpreter

java, the Java interpreter, is used to run Java applications from the command line. It takes as an argument the name of a class file to run, as in the following example:

java BidMonitor

Although Java class files end with the .class extension, this extension will not be specified when using the interpreter.

The class loaded by the Java interpreter must contain a class method called main() that takes the following form:

public static void main(String[] arguments) {

    // Method here

}

Some simple Java programs might consist of only one class—the one containing the main() method. In more complex programs that make use of other classes, the interpreter automatically loads any other classes that are needed.

The Java interpreter runs bytecode—the compiled instructions that are executed by a Java virtual machine. After a Java program is saved in bytecode as a .class file, it can be run by different interpreters without modification. If you have compiled a Java 2 program, it will be compatible with any interpreter that fully supports Java 2.

By the Way

Interestingly enough, Java is not the only language that you can use to create Java bytecode. NetRexx, JPython, JRuby, JudoScript, and several dozen other languages will compile into .class files of executable bytecode through the use of compilers specific to those languages. Robert Tolksdorf maintains a comprehensive list of these languages that is currently available from the web page at http://www.robert-tolksdorf.de/vmlanguages.

There are two different ways to specify the class file that will be run by the Java interpreter. If the class is not part of any package, you can run it by specifying the name of the class, as in the preceding java BidMonitor example. If the class is part of a package, you must specify the class by using its full package and class name.

For example, consider a SellItem class that is part of the org.cadenhead.auction package. To run this application, the following command would be used:

java org.cadenhead.auction.SellItem

Each element of the package name corresponds to its own subfolder The Java interpreter will look for the SellItem.class file in several different places:

  • The org\cadenhead\auction subfolder of the folder where the java command was entered (if the command was made from the C:\J24work folder, for example, the SellItem.class file can be run successfully if it was in the C:\J24work\org\cadenhead\auction folder)

  • The org\cadenhead\auction subfolder of any folder in your CLASSPATH setting

If you're creating your own packages, an easy way to manage them is to add a folder to your CLASSPATH that's the root folder for any packages you create, such as C:\javapackages or something similar. After creating subfolders that correspond to the name of a package, place the package's class files in the correct subfolder

Java supports assertions, a debugging feature that only works when requested as a command-line option. To run a program using the Java interpreter and make use of any assertions that it contains, use the command line -ea, as in the following example:

java -ea Outline

The Java interpreter executes all assert statements in the application's class and all other class files that it uses, with the exception of classes from the Java class library.

To remove that exception and make use of all assertions, run a class with the -esa option.

If you don't specify one of the options that turns on the assertions feature, all assert statements will be ignored by the interpreter.


The javac Compiler

javac, the Java compiler, converts Java source code into one or more class files of bytecode that can be run by a Java interpreter.

Java source code is stored in a file with the .java file extension. This file can be created with any text editor or word processor that can save a document without any special formatting codes. The terminology varies depending on the text-editingsoftware being used, but these files are often called plain text, ASCII text, DOS text, or something similar.

A Java source code file can contain more than one class, but only one of the classes can be declared to be public. A class can contain no public classes at all if desired, although this isn't possible with applets because of the rules of inheritance.

If a source code file contains a class that has been declared to be public, the name of the file must match the name of that class. For example, the source code for a public class called BuyItem must be stored in a file called BuyItem.java.

To compile a file, the javac tool is run with the name of the source code file as an argument, as in the following:

javac BuyItem.java

You can compile more than one source file by including each separate filename as a command-line argument, such as this command:

javac BuyItem.java SellItem.java

You also can use javac, the Java compiler,wildcard characters such as * and ?. Use the following command to compile all .java files in a folder:

javac *.java

When you compile one or more Java source code files, a separate .class file will be created for each Java class that compiles successfully.

If you are compiling a program that makes use of assertions, you must use the -source 1.5 option, as in this command:

javac -source 1.5 Outline.java

If the -source option is not used and you try to compile a program that contains assertions, javac displays an error message and won't compile the file.

Another useful option when running the compiler is -deprecation, which causes the compiler to describe any deprecated methods that are being employed in a Java program.

A deprecated method is one that Sun Microsystems has replaced with a better alternative, either in the same class or a different class entirely. Although the deprecated method works, at some point Sun may decide to remove it from the class—the deprecation warning is a strong suggestion to stop using that method as soon as you can.

Normally, the compiler will issue a single warning if it finds any deprecated methods in a program. The -deprecation option causes the compiler to list each method that has been deprecated, as in the following command:

javac -deprecation SellItem.java

If you're more concerned with the speed of a Java program than the size of its class files, you can compile its source code with the -O option. This creates class files that have been optimized for faster performance. Methods that are static, final, or private might be compiled inline, a technique that makes the class file larger but causes the methods to be executed more quickly.

If you are going to use a debugger to look for bugs in a Java class, compile the source with the -g option to put all debugging information in the class file, including references to line numbers, local variables, and source code. (To keep all this out of a class, compile with the -g:none option.)

Normally, the Java compiler doesn't provide a lot of information as it creates class files. In fact, if the source code compiles successfully and no deprecated methods are employed, you won't see any output from the compiler at all. No news is good news in this case.

If you want to see more information on what the javac tool is doing as it compiles source code, use the -verbose option. The more verbose compiler will describe the time it takes to complete different functions, the classes that are being loaded, and the overall time required.


The appletviewer Browser

The appletviewer tool runs Java programs that require a web browser and are presented as part of an HTML document. It takes an HTML document as a command-line argument, as in the following example:

appletviewer NewAuctions.html

If the argument is a web address instead of a reference to a file, appletviewer will load the HTML document at that address. For example:

appletviewer http://www.javaonthebrain.com

Figure B.1 displays an applet loaded from this page, a site developed by cartoonist and Java game programmer Karl Hörnell.

Figure B.1. Viewing Java web applets outside of a browser.

When an HTML document is loaded by appletviewer, every applet on that document will begin running in its own window. The size of these windows depends on the HEIGHT and WIDTH attributes that were set in the applet's HTML tag.

Unlike a web browser, appletviewer cannot be used to view the HTML document itself. If you want to see how the applet is laid out in relation to the other contents of the document, you must use a Java-capable web browser.

Watch Out!

The current versions of Mozilla, Netscape Navigator, and Microsoft Internet Explorer do not offer built-in support for Java applets. Support for the language is available as a browser plug-in from Sun Microsystems. The Java Plug-in from Sun can be used to run a Java applet in a browser in place of the browser's Java interpreter. The Plug-in is included in the Java 2 Runtime Environment, an interpreter for running Java Programs that is installed along with the Java Development Kit. If it isn't already present on your system, you can download it from Sun's website at http://www.java.com.

Using appletviewer is reasonably straightforward, but you may not be familiar with some of the menu options that are available as the viewer runs an applet. The following menu options are available:

  • The Restart and Reload options are used to restart the execution of the applet. The difference between these two options is that Restart does not unload the applet before restarting it, whereas Reload does. The Reload option is equivalent to closing the applet viewer and opening it up again on the same web page.

  • The Start and Stop options are used to call the start() and stop() methods of the applet directly.

  • The Clone option creates a second copy of the same applet running in its own window.

  • The Tag option displays the program's APPLET or OBJECT tag, along with the HTML for any PARAM tags that configure the applet.

Another option on the Applet pull-down menu is Info, which calls the getAppletInfo() and getParameterInfo() methods of the applet. A programmer can implement these methods to provide more information about the applet and the parameters that it can handle.

The getAppletInfo() method will return a string that describes the applet. The getParameterInfo() method will return an array of string arrays that specify the name, type, and description of each parameter.

Listing B.1 contains a Java 2 applet that demonstrates the use of these methods.

Listing B.1. The Full Text of AppInfo.java

 1: import java.awt.*;

 2:

 3: public class AppInfo extends javax.swing.JApplet {

 4:     String name, date;

 5:     int version;

 6:

 7:     public String getAppletInfo() {

 8:         String response = "This applet demonstrates the "

 9:             + "use of the Applet's Info feature.";

10:         return response;

11:     }

12:

13:     public String[][] getParameterInfo() {

14:         String[] p1 = { "Name", "String", "Programmer's name" };

15:         String[] p2 = { "Date", "String", "Today's date" };

16:         String[] p3 = { "Version", "int", "Version number" };

17:         String[][] response = { p1, p2, p3 };

18:         return response;

19:     }

20:

21:     public void init() {

22:         name = getParameter("Name");

23:         date = getParameter("Date");

24:         String versText = getParameter("Version");

25:         if (versText != null) {

26:             version = Integer.parseInt(versText);

27:         }

28:     }

29:

30:     public void paint(Graphics screen) {

31:         Graphics2D screen2D = (Graphics2D) screen;

32:         screen2D.drawString("Name: " + name, 5, 50);

33:         screen2D.drawString("Date: " + date, 5, 100);

34:         screen2D.drawString("Version: " + version, 5, 150);

35:     }

36: ]

The main function of this applet is to display the value of three parameters: Name, Date, and Version. The getAppletInfo() method returns the following string:

This applet demonstrates the use of the Applet's Info feature.

The getParameterInfo() method is a bit more complicated if you haven't worked with multidimensional arrays. The following things are taking place:

  • Line 13 defines the return type of the method as a two-dimensional array of String objects.

  • Line 14 creates an array of String objects with three elements: "Name", "String", and "Programmer's Name". These elements describe one of the parameters that can be defined for the AppInfo applet. They describe the name of the parameter (Name in this case), the type of data that the parameter will hold (a string), and a description of the parameter ("Programmer's Name"). The three-element array is stored in the p1 object.

  • Lines 15–16 define two more String arrays for the Date and Version parameters.

  • Line 17 uses the response object to store an array that contains three string arrays: p1, p2, and p3.

  • Line 18 uses the response object as the method's return value.

Listing B.2 contains a web page that can be used to load the AppInfo applet.

Listing B.2. The Full Text of AppInfo.html

1: <applet code="AppInfo.class" height="200" width="170">

2: <param name="Name" value="Rogers Cadenhead">

3: <param name="Date" value="06/08/05">

4: <param name="Version" value="4">

5: </applet>

Figure B.2 shows the applet running with the applet viewer, and Figure B.3 is a screen capture of the dialog box that opens when the viewer's Info menu option is selected.

Figure B.2. The AppInfo applet running in appletviewer.

Figure B.3. The Info dialog box of the AppInfo applet.

These features require a browser that makes this information available to users. The JDK's appletviewer handles this through the Info menu option, but browsers such as Internet Explorer do not offer anything like it at this time.


The javadoc Documentation Tool

javadoc, the Java documentation creator, takes a .java source code file or package name as input and generates detailed documentation in HTML format.

For javadoc to create full documentation for a program, a special type of comment statement must be used in the program's source code. Tutorial programs in this book use //, /*, and */ in source code to create comments—information for people who are trying to make sense of the program.

Java also has a more structured type of comment that can be read by the javadoc tool. This comment is used to describe program elements such as classes, variables, objects, and methods. It takes the following format:

/** A descriptive sentence or paragraph.

  * @tag1 Description of this tag.

  * @tag2 Description of this tag.

 */

A Java documentation comment should be placed immediately above the program element it is documenting and should succinctly explain what the program element is. For example, if the comment precedes a class statement, it will describe the purpose of the class.

In addition to the descriptive text, different items can be used to document the program element further. These items, called tags, are preceded by an @ sign and are followed by a space and a descriptive sentence or paragraph.

Listing B.3 contains a thoroughly documented version of the AppInfo applet called AppInfo2. The following tags are used in this program:

  • @author— The program's author. This tag can be used only when documenting a class, and it will be ignored unless the –author option is used when javadoc is run.

  • @version text— The program's version number. This also is restricted to class documentation, and it requires the –version option when you're running javadoc or the tag will be ignored.

  • @return text— The variable or object returned by the method being documented.

  • @serial text— A description of the data type and possible values for a variable or object that can be serialized, saved to disk along with the values of its variables and retrieved later.

Listing B.3. The Full Text of AppInfo2.java

 1: import java.awt.*;

 2:

 3: /** This class displays the values of three parameters:

 4:   * Name, Date and Version.

 5:   * @author <a href="http://java24hours.com">Rogers Cadenhead</a>

 6:   * @version 4.0

 7:  */

 8: public class AppInfo2 extends javax.swing.JApplet {

 9:     /**

10:       * @serial The programmer's name.

11:      */

12:     String name;

13:     /**

14:       * @serial The current date.

15:      */

16:     String date;

17:     /**

18:       * @serial The program's version number.

19:      */

20:     int version;

21:

22:     /**

23:       * This method describes the applet for any browsing tool that

24:       * requests information from the program.

25:       * @return A String describing the applet.

26:      */

27:     public String getAppletInfo() {

28:         String response = "This applet demonstrates the "

29:             + "use of the Applet's Info feature.";

30:         return response;

31:     }

32:

33:     /**

34:       * This method describes the parameters that the applet can take

35:       * for any browsing tool that requests this information.

36:       * @return An array of String[] objects for each parameter.

37:      */

38:     public String[][] getParameterInfo() {

39:         String[] p1 = { "Name", "String", "Programmer's name" };

40:         String[] p2 = { "Date", "String", "Today's date" };

41:         String[] p3 = { "Version", "int", "Version number" };

42:         String[][] response = { p1, p2, p3 };

43:         return response;

44:     }

45:

46:     /**

47:       * This method is called when the applet is first initialized.

48:      */

49:     public void init() {

50:         name = getParameter("Name");

51:         date = getParameter("Date");

52:         String versText = getParameter("Version");

53:         if (versText != null) {

54:             version = Integer.parseInt(versText);

55:         }

56:     }

57:

58:     /**

59:       * This method is called when the applet's display window is

60:       * being repainted.

61:      */

62:     public void paint(Graphics screen) {

63:         Graphics2D screen2D = (Graphics2D)screen;

64:         screen.drawString("Name: " + name, 5, 50);

65:         screen.drawString("Date: " + date, 5, 100);

66:         screen.drawString("Version: " + version, 5, 150);

67:     }

The following command will create HTML documentation from the source code file AppInfo2.java:

javadoc -author -version AppInfo2.java

The Java documentation tool will create several different web pages in the same folder as AppInfo2.java. These pages will document the program in the same manner as Sun's official documentation for the Java 2 class library.

Did you Know?

To see the official documentation for Java 2 JDK 1.5 and the Java class libraries, visit http://java.sun.com/j2se/1.5.0/docs/api.

To see the documentation that javadoc has created for AppInfo2, load the newly created web page index.html on your web browser. Figure B.4 shows this page loaded with Mozilla Firefox.

Figure B.4. Java documentation for the AppInfo2 program.

[View full size image]

The javadoc tool produces extensively hyperlinked web pages. Navigate through the pages to see where the information in your documentation comments and tags shows up.

If you're familiar with HTML markup, you can use HTML tags such as A, TT, and B within your documentation comments. Line 5 of the AppInfo2 program uses an A tag to turn the text "Rogers Cadenhead" into a hyperlink to this book's website.

The javadoc tool also can be used to document an entire package by specifying the package name as a command-line argument. HTML files will be created for each .java file in the package, along with an HTML file indexing the package.

If you would like the Java documentation to be produced in a different folder than the default, use the -d option followed by a space and the folder name.

The following command creates Java documentation for AppInfo2 in a folder called C:\JavaDocs\:

javadoc -author -version -d C:\JavaDocs\ AppInfo2.java

The following list details the other tags you can use in Java documentation comments:

  • @deprecated text— A note that this class, method, object, or variable has been deprecated. This causes the javac compiler to issue a deprecation warning when the feature is used in a program that's being compiled.

  • @exception class description— Used with methods that throw exceptions, this tag documents the exception's class name and its description.

  • @param name description— Used with methods, this tag documents the name of an argument and a description of the values the argument can hold.

  • @see class— This tag indicates the name of another class, which will be turned into a hyperlink to the Java documentation of that class. This can be used without restriction in comments.

  • @see class#method— This tag indicates the name of a method of another class, which will be used for a hyperlink directly to the documentation of that method. This is usable without restriction.

  • @since text— This tag indicates a note describing when a method or feature was added to its class library.


The jar Java File Archival Tool

When you deploy a Java program, keeping track of all the class files and other files required by the program can be cumbersome.

To make this easier, the kit includes a tool called jar that can pack all a program's files into a Java archive—also called a JAR file. The jar tool also can be used to unpack the files in one of these archives.

JAR files can be compressed using the Zip format or packed without using compression.

To use the tool, type the command jar followed by command-line options and a series of filenames, folder names, or wildcards.

The following command packs all a folder's class and GIF image files into a single Java archive called Animate.jar:

jar cf Animate.jar *.class *.gif

The argument cf specifies two command-line options that can be used when running the jar program. The c option indicates that a Java archive file should be created, and f indicates that the name of the archive file will follow as one of the next arguments.

You also can add specific files to a Java archive with a command such as the following:

jar cf MusicLoop.jar MusicLoop.class muskratLove.mp3 shopAround.mp3

This creates a MusicLoop.jar archive containing three files: MusicLoop.class, muskratLove.mp3, and shopAround.mp3.

Run jar without any arguments to see a list of options that can be used with the tool.

One use for jar is to put all files necessary to run a Java applet in a single JAR file. This makes it much easier to deploy the applet on the Web.

The standard way of placing a Java applet on a web page is to use APPLET or OBJECT to indicate the primary class file of the applet. A Java-enabled browser then downloads and runs the applet. Any other classes and any other files needed by the applet are downloaded from the web server.

The problem with running applets in this way is that every single file an applet requires—helper classes, images, audio files, text files, or anything else—requires a separate connection from a web browser to the server containing the file. This can significantly increase the amount of time it takes to download an applet and everything it needs to run.

If you can reduce the number of files the browser has to load from the server by putting many files into one Java archive, your applet can be downloaded and run by a web browser more quickly. If the files in a Java archive are compressed, it loads even more quickly.

After you create a Java archive, the ARCHIVE attribute is used with the APPLET tag to show where the archive can be found. You can use Java archives with an applet with tags such as the following:

<applet code="MusicLoop.class" archive="MusicLoop.jar" width="45" height="42">

</applet>

This tag specifies that an archive called MusicLoop.jar contains files used by the applet. Browsers and browsing tools that support JAR files will look inside the archive for files that are needed as the applet runs.

Watch Out!

Although a Java archive can contain class files, the ARCHIVE attribute does not remove the need for the CODE attribute. A browser still needs to know the name of the applet's main class file to load it.

When using an OBJECT tag to display an applet that uses a JAR file, the applet's archive file is specified as a parameter using the PARAM tag. The tag should have the name attribute "archive" and a value attribute with the name of the archive file.

The following example is a rewrite of the preceding example to use OBJECT instead of APPLET:

<object code="MusicLoop.class" width="45" height="42">

    <param name="archive" value="MusicLoop.jar">

</object>


The jdb Debugger

jdb, the Java debugger, is a sophisticated tool that helps you find and fix bugs in Java programs. You can also use it to understand better what is taking place behind the scenes in the Java interpreter as a program is running. It has a large number of features, including some that might be beyond the expertise of a Java programmer who is new to the language.

You don't need to use the debugger to debug Java programs. This is fairly obvious, especially if you've been creating your own Java programs as you read this book. After the Java compiler generates an error, the most common response is to load the source code into an editor, find the line cited in the error message, and try to spot the problem. This dreaded compile-curse-find-fix cycle is repeated until the program compiles without complaint.

After using this debugging method for a while, you might think that the debugger isn't necessary to the programming process because it's such a complicated tool to master. This reasoning makes sense when you're fixing problems that cause compiler errors. Many of these problems are simple things such as a misplaced semicolon, unmatched { and } brackets, or the use of the wrong type of data as a method argument. However, when you start looking for logic errors—more subtle bugs that don't stop the program from compiling and running—a debugger is an invaluable tool.

The Java debugger has two features that are useful when you're searching for a bug that can't be found by other means: single-step execution and breakpoints. Single-step execution pauses a Java program after every line of code is executed. Breakpoints are points where execution of the program will pause. Using the Java debugger, these breakpoints can be triggered by specific lines of code, method calls, or caught exceptions.

The Java debugger works by running a program using a version of the Java interpreter that it has complete control over.

Before you use the Java debugger with a program, you will compile the program with the -g option, which causes extra information to be included in the class file. This information greatly aids in debugging. Also, you shouldn't use the -O option because its optimization techniques might produce a class file that does not directly correspond with the program's source code.

Debugging Applications

If you're debugging an application, the jdb tool can be run with a Java class as an argument. This is shown in the following:

jdb WriteBytes

This example runs the debugger with WriteBytes.class, an application that's available from the book's website at http://www.java24hours.com. Visit the site, select the Appendix B page, and then save the files WriteBytes.class and WriteBytes.java in the same folder that you run the debugger from.

The WriteBytes application writes a series of bytes to disk to produce the file pic.gif.

The debugger loads this program but does not begin running it, displaying the following output:

Initializing jdb...

>

The debugger is controlled by typing commands at the > prompt.

To set a breakpoint in a program, the stop in or stop at commands are used. The stop in command sets a breakpoint at the first line of a specific method in a class. You specify the class and method name as an argument to the command, as in the following hypothetical example:

stop in SellItem.SetPrice

This command sets a breakpoint at the first line of the SetPrice method. Note that no arguments or parentheses are needed after the method name.

The stop at command sets a breakpoint at a specific line number within a class. You specify the class and number as an argument to the command, as in the following example:

stop at WriteBytes:14

If you're trying this with the WriteBytes class, you'll see the following output after entering this command:

Deferring breakpoint WriteBytes:14

It will be set after the class is loaded.

You can set as many breakpoints as desired within a class. To see the breakpoints that are currently set, use the clear command without any arguments. The clear command lists all current breakpoints by line number rather than method name, even if they were set using the stop in command.

By using clear with a class name and line number as an argument, you can remove a breakpoint. If the hypothetical SellItem.SetPrice method was located at line 215 of SellItem, you can clear this breakpoint with the following command:

clear SellItem:215

Within the debugger, you can begin executing a program with the run command. The following output shows what the debugger displays after you begin running the WriteBytes class:

run WriteBytes

VM Started: Set deferred breakpoint WriteBytes:14

Breakpoint hit: "thread=main", WriteBytes.main(), line=14 bci=413

14                for (int i = 0; i < data.length; i++)

After you have reached a breakpoint in the WriteBytes class, experiment with the following commands:

  • list— At the point where execution stopped, this command displays the source code of the line and several lines around it. This requires access to the .java file of the class where the breakpoint has been hit, so that you must have WriteBytes.java in either the current folder or one of the folders in your CLASSPATH.

  • locals— This command lists the values for local variables that are currently in use or will soon be defined.

  • print text— This command displays the value of the variable, object, or array element specified by text.

  • step— This command executes the next line and stops again.

  • cont— This command continues running the program at the point it was halted.

  • !!— This command repeats the previous debugger command.

After trying out these commands within the application, you can resume running the program by clearing the breakpoint and using the cont command. Use the exit command to end the debugging session.

The WriteBytes application creates a file called pic.gif. You can verify that this file ran successfully by loading it with a web browser or image-editing software. You'll see a small letter J in black and white.

After you have finished debugging a program and you're satisfied that it works correctly, recompile it without the -g option.

Debugging Applets

You can't debug an applet by loading it using the jdb tool. Instead, use the -debug option of the appletviewer, as in the following example:

appletviewer -debug AppInfo.html

This will load the Java debugger, and when you use a command such as run, the appletviewer will begin running also. Try out this example to see how these tools interact with each other.

Before you use the run command to execute the applet, set a breakpoint in the program at the first line of the getAppletInfo method. Use the following command:

stop in AppInfo.getAppletInfo

After you begin running the applet, the breakpoint won't be hit until you cause the getAppletInfo() method to be called. This is accomplished by selecting Applet, Info from the appletviewer's menu.

Advanced Debugging Commands

With the features you have learned about so far, you can use the debugger to stop execution of a program and learn more about what's taking place. This might be sufficient for many of your debugging tasks, but the debugger also offers many other commands. These include the following:

  • up— Moves up the stack frame so you can use locals and print to examine the program at the point before the current method was called.

  • down— Moves down the stack frame to examine the program after the method call.

In a Java program, often there are places where a chain of methods is called. One method calls another method, which calls another method, and so on. At each point where a method is being called, Java keeps track of all the objects and variables within that scope by grouping them together. This grouping is called a stack, as if you were stacking these objects as you would a deck of cards. The various stacks in existence as a program runs are called the stack frame.

By using up and down along with commands such as locals, you can better understand how the code that calls a method interacts with that method.

You can also use the following commands within a debugging session:

  • classes— Lists the classes currently loaded into memory.

  • methods— Lists the methods of a class.

  • memory— Shows the total amount of memory and the amount that isn't currently in use.

  • threads— Lists the threads that are executing.

The threads command numbers all the threads, which enables you to use the suspend command followed by that number to pause the thread, as in suspend 1. You can resume a thread by using the resume command followed by its number.

Another convenient way to set a breakpoint in a Java program is to use the catch text command, which pauses execution when the Exception class named by text is caught.

You can also cause an exception to be ignored by using the ignore text command with the Exception class named by text.


Using System Properties

One obscure feature of the JDK is that the command-line option -D can modify the performance of the Java class library.

If you have used other programming languages prior to learning Java, you might be familiar with environment variables, which provide information about the operating system in which a program is running. An example is the CLASSPATH setting, which indicates the folders in which the Java interpreter should look for a class file.

Because different operating systems have different names for their environment variables, they cannot be read directly by a Java program. Instead, Java includes a number of different system properties that are available on any platform with a Java implementation.

Some properties are used only to get information. The following system properties are among those that should be available on any Java implementation:

  • java.version— The version number of the Java interpreter

  • java.vendor— A string identifying the vendor associated with the Java interpreter

  • os.name— The operating system in use

  • os.version— The version number of that operating system

Other properties can affect how the Java class library performs when being used inside a Java program. An example of this is the java.io.tmpdir property, which defines the folder that Java's input and output classes use as a temporary workspace.

A property can be set at the command line by using the –D option followed by the property name, an equal sign, and the new value of the property, as in this command:

java -Duser.timezone=Asia/Jakarta Auctioneer

The use of the system property in this example sets the default time zone to "Asia/Jakarta" before running the Auctioneer class. This affects any Date objects in a Java program that do not set their own zone.

These property changes are not permanent; they only apply to that particular execution of the class and any classes that it uses.

Did you Know?

In the java.util package, the TimeZone class includes a class method called getProperties() that returns a string array containing all the time zone identifiers that Java supports.

The following code displays these identifiers:

String[] ids = java.util.TimeZone.getAvailableIDs();

for (int i = 0; i < ids.length; i++) {

    System.out.println(ids[i]);

}

You also can create your own properties and read them using the getProperty() method of the System class, which is part of the java.lang package.

Listing B.4 contains the source code of a simple program that displays the value of a user-created property.

Listing B.4. The Full Text of ItemProp.java

1: class ItemProp {

2:     public static void main(String[] arguments) {

3:         String n = System.getProperty("item.name");

4:         System.out.println("The item is named " + n);

5:     }

6: }

If this program is run without setting the item.name property on the command line, the output is the following:

The item is named null

The item.name property can be set using the -D option, as in this command:

java -Ditem.name="Microsoft Bob" ItemProp

The output is the following:

The item is named Microsoft Bob

The -D option is used with the Java interpreter. To use it with the appletviewer as well, all you have to do differently is precede the -D with -J. The following command shows how this can be done:

appletviewer -J-Dtimezone=Asia/Jakarta AuctionSite.html

This example causes appletviewer to use the default time zone "Asia/Jakarta" with all applets on the web page AuctionSite.html.


Summary

This appendix explored several features of the JDK that are increasingly helpful as you develop more experience with Java:

  • Using the Java debugger with applets and applications

  • Creating an optimized version of a compiled class

  • Writing applet methods that provide information to a browser upon request

  • Using the Java documentation creation tool to describe a class, its methods, and other aspects of the program fully

These JDK features weren't required during the 24 hours of this book because of the relative simplicity of the tutorial programs. Although it can be complicated to develop a Swing application or to work with threads and streams for the first time, your biggest challenge lies ahead: integrating concepts such as these into more sophisticated Java programs.

Tools such as javadoc and the debugger really come into their own on complex projects.

When a bug occurs because of how two classes interact with each other, or similar subtle logic errors creep into your code, a debugger is the best way to identify and repair the problems.

As you create an entire library of classes, javadoc can easily document these classes and show how they are interrelated.


Q&A

Q1:

The official Java documentation is filled with long paragraphs that describe classes and methods. How can these be produced using javadoc?

A1:

In the Java documentation creator, there's no limit to the length of a description. Although they're often as brief as a sentence or two, they can be longer if necessary. End the description with a period, immediately followed by a new line with a tag of some kind or the end of the comment.

Q2:

Do I have to document everything in my Java classes if I'm planning to use the javadoc tool?

A2:

The Java documentation creator will work fine no matter how many or how few comments you use. Deciding what elements of the program need to be documented is up to you. You probably should describe the class and all methods, variables, and objects that aren't hidden from other classes.

The javadoc tool will display a warning each time a serializable object or variable is defined in a program without a corresponding Java documentation comment.


Appendix C. Using the NetBeans Integrated Development Environment

Most Java programmers learn the language using the Java Development Kit (JDK) from Sun Microsystems, a set of command-line tools used to create Java programs that were described in Appendix A, "Using the Java Development Kit," and Appendix B, "Programming with the Java Development Kit."

The JDK is highly popular, but it lacks some features most professional programmers take for granted such as a built-in text editor, graphical user interface, and project management tools. These features, which are essential for everyday programming, are typically supplied in an integrated development environment (IDE).

One IDE you can choose for creating Java software is the NetBeans Integrated Development Environment, which is offered as a free download from Sun Microsystems.

This appendix covers how to download and install NetBeans and use it to create, compile, and run a simple Java program.


Choosing a Java Development Tool

Several different integrated development environments are available for Java programming.

NetBeans includes tools you will use all the time: a text editor, compiler, graphical user interface designer, file archiving tool, and project manager.

The IDE also includes tools that aren't essential now, as you're getting started with the language, but may become indispensable later, including a debugger, Java servlet and JavaServer Pages editing and testing tool, and code versioning system.

NetBeans supports Java 2 version 5 and can be configured to support other versions, so you can continue using it as Sun releases new versions of Java.

Installing NetBeans

NetBeans works by using the Java Development Kit behind the scenes. For this reason, you must have both NetBeans and the JDK installed on your system.

Sun makes this easy by offering them as a "bundle" that can be downloaded and installed together. To see what versions are available for download, visit the web page http://java.sun.com/j2se/1.5.0/download.jsp.

When you visit the page for JDK 5, you should be able to download the bundle. At the time of this writing, the product is called the JDK 5.0 Update 3 with NetBeans 4.1 Bundle.

Did you Know?

By the time you visit the page, the name of this product may be different—Sun renames products frequently. Anything that's called a NetBeans "bundle" is probably what you need.

The NetBeans bundle is currently available for the following platforms:

  • Windows 98, ME, NT, XP, 2000, and Server 2003 (though Sun only states that it has been tested with XP Professional, 2000 Professional with Service Pack 3, and NT 4.0 with Service Pack 6)

  • Solaris SPARC and Intel

  • Linux

The Windows and Linux versions of NetBeans require a computer with a Pentium III processor that is 500 MHz or faster, around 600MB of free disk space, and 256MB of memory.

Did you Know?

There is no Macintosh version of NetBeans on Sun's site, but you can download it from Apple by visiting the website http://developer.apple.com/java/ netbeans.html. Apple also offers a free version of the JDK and XCode, an integrated development environment. To find out more about Apple's Java programming tools, visit the website http://developer.apple.com/java.

To set up NetBeans, you must download and run an installation program (or install it from a CD). After you have downloaded the file, you're ready to set it up on your system.

Running the Installation Wizard

To install up the NetBeans/JDK bundle on a Windows system, double-click the installation file icon or click Start, Run from the Windows taskbar to find and run the file.

An installation wizard guides you through the process of setting up the software. If you accept Sun's terms and conditions for using NetBeans and the JDK, you'll be asked where to install the program, as shown in Figure C.1.

Figure C.1. Choosing a destination folder for NetBeans.

[View full size image]

The wizard suggests a folder where the bundle should be installed. In Figure C.1, the wizard suggests the folder C:\Program Files\netbeans-4.1.

If you want to pick a different folder, click Browse and use the Open dialog box to find and select a location. After you have chosen the desired folder, click Next to continue.

The installation wizard may ask whether files ending with the .java and .nbm extensions should be associated with the software. These files are Java source code files and NetBeans modules files—check the boxes to make it possible to open these files in NetBeans by double-clicking them in a folder.

The wizard displays the folder where NetBeans will be installed and the amount of space required (107MB in the current release). Click Next to begin installation.


Creating a Sample Program

The first time you run NetBeans, you'll be asked several questions about how to configure the software.

To run the program, double-click the NetBeans IDE icon on the desktop or find it on the Start menu:

  • On Windows XP, choose Start, All Programs, open the NetBeans 4.1 folder, then click NetBeans IDE.

  • On other Windows systems, choose Start, Programs, open the NetBeans 4.1 folder, then click NetBeans IDE.

If you have never used an integrated development environment before, you're likely to be a little shell-shocked when you see NetBeans for the first time. There are numerous menu commands, toolbar buttons, and other interface components at your disposal, as shown in Figure C.2.

Figure C.2. Viewing the NetBeans graphical user interface.

[View full size image]

Most IDEs are designed to make experienced programmers more productive rather than to help new programmers learn a language. NetBeans is no exception.

It can be difficult to learn how to use an IDE at the same time you are learning Java. This is probably the biggest selling point for the Java Development Kit.

However, if you want to use the power and convenience of NetBeans while learning Java, this section and some supplementary reading should be enough to get started.

In this section, you create a short Java application and run it, displaying the output of the program.

NetBeans organizes Java programs into projects:

1.
Choose File, New Project. A template wizard opens, as shown in Figure C.3. All files are created from templates in NetBeans. There are templates for Java class files, JavaBeans, graphical user interface components, and other kinds of files.

Figure C.3. Choosing a template for a new Java class.

[View full size image]

2.
Choose the General folder icon in the Categories pane to see the class templates that are available.

3.
The Java Application template is suitable for the projects you will undertake in this book. It creates a simple Java class that can be run as an application. Choose its icon in the Projects pane and click Next.

The wizard asks for a name to give the class and the folder where it should be saved.

4.
Type the name HelloUser in the Project Name field.

5.
In the Project Location pane, if you don't like the folder NetBeans has designated for all programming projects, type a different folder.

6.
Leave the other values alone and click Finish.

When you create your first project, NetBeans scans your computer for Java classes, even looking inside .jar files that hold class libraries in the Java Archive format.

When the scan completes, NetBeans creates the source code for a Java application called HelloUser and opens it for editing in an editor window (see Figure C.4).

Figure C.4. Editing source code in NetBeans.

[View full size image]

All Java programs begin as source code—a series of statements created using a text editor and saved as a text file.

The NetBeans editor keeps track of the current position of the cursor in a bar that's circled in Figure C.4. The first number is the line, counting down from 1 at the top of the file, and the second number is the character position on that line, counting from left to right.

When you create the HelloUser project, it contains the following Java statements as lines 26–28:

public static void main(String[] args) {

    // TODO code application logic here

}

Delete the // TODO code application logic here comment and as a replacement, enter the following statements at that place in the file:

String username = System.getProperty("user.name");

System.out.println("Hello, " + username);

When you're finished, lines 26–29 should be the same as Listing C.1. Make sure that all the parentheses, braces, and quotation marks in the listing are entered correctly and capitalize everything in the program exactly as shown.

Listing C.1. Partial Source Code of HelloUser.java

26:     public static void main(String[] args) {

27:         String username = System.getProperty("user.name");

28:         System.out.println("Hello, " + username);

29:     }

The line numbers and colons along the left side of Listing C.1 are not part of the program—they're included so that I can refer to specific lines by number in this book. If you're ever unsure about the source code of a program in this book, you can compare it to a copy on the book's official World Wide Web site at the following address:

http://www.java24hours.com

After you finish typing in these lines, save the project by choosing File, Save from the menu.

Compiling and Running the Program

When you save a source code file, NetBeans stores it in the selected folder and displays the file in the Files pane inside that folder. (Choose Windows, Files to see this pane.)

The file must be compiled into Java bytecode before it can be used: Choose Build, Build Main Project.

NetBeans attempts to compile the file, opening an Output pane to display the results of the attempt (see Figure C.5).

Figure C.5. Successfully compiling a Java application.

[View full size image]

If it compiles successfully, the message "BUILD SUCCESSFUL" will be displayed in the Output pane. If it fails, one or more error messages are displayed.

To run the program after a successful compilation, choose Run, Run Main Project.

The Output pane displays the output of the program: the text "Hello," followed by your username. Figure C.6 displays the output produced on my system.

Figure C.6. Running a Java application.

[View full size image]

That's all the skills you need to create simple Java applications and other classes with NetBeans. The integrated development environment can be used to accomplish a lot more, but it will be easier to master the software after you have developed some experience with the Java language by completing the 24 hours of this book.

Did you Know?

Sun Microsystems offers a tutorial for beginning NetBeans users in the online help feature of the software: Choose Help, Help Contents; then double-click the Getting Started folder in the table of contents.

This book also has a website where you can find solutions to problems, corrections, answers to reader questions, and other useful material. The site is available at http://www.java24hours.com.


Appendix D. Where to Go from Here: Java Resources

  • Other Books to Consider

  • Sun's Official Java Site

  • Other Java Websites

  • Java Newsgroups

  • Internet Relay Chat

  • Job Opportunities

After you have finished this book, you might be wondering where you can go to improve your Java programming skills. This appendix lists some books, World Wide Web sites, Internet discussion groups, and other resources that you can use to expand your Java knowledge.


Other Books to Consider

Sams Publishing publishes a multitude of books on Java programming topics, including many that follow up on the material covered in this book. The following list includes ISBN numbers, which will be needed at bookstores if they don't currently carry the book that you're looking for:

  • Sams Teach Yourself Java 2 in 21 Days, Fourth Edition, by Rogers Cadenhead (me! me! me!) and Laura Lemay. ISBN: 0-67232-628-0. Though some of the material in the first two weeks of this book will be redundant, it covers it in more depth and adds a lot of advanced topics. If you're ready to make another 504-hour commitment to learning Java, this may be a suitable book.

  • Eclipse Kick Start by Carlos Valcarcel. ISBN 0-67232-610-8. A hands-on guide to the highly adaptable open source Java development environment.

  • Sams Teach Yourself J2EE in 21 Days by Martin Bond and others. ISBN: 0-67232-384-2. A tutorial for Java developers who want to use the Java 2 Enterprise Edition (J2EE).

  • JXTA: Java P2P Programming by Daniel Brookshier and others. ISBN: 0-67232-366-4. An introduction to Sun Microsystems' JXTA classes, which support peer-to-peer networked programming.

  • MySQL and JSP Web Applications: Data-Driven Programming Using Tomcat and MySQL by James Turner. ISBN: 0-67232-309-5. Advice and programming tutorials for JavaServer Pages programmers using the MySQL database with their web applications.

  • Developing Java Servlets, Second Edition, by James Goodwill and Samir Mehta. ISBN: 0-67232-107-6. A tutorial on Java servlet and JavaServer Pages programming and how to use them with XML, Enterprise Java Beans, and the Java 2 Enterprise Edition.

  • Jini and JavaSpaces Application Development by Robert Flenner. ISBN: 0-67232-258-7. A guide to wireless networked programming using JINI, Sun's technology for connecting different disconnected devices using Java.

Chapters and other material from many Sams Publishing Java books have been made available for free on the World Wide Web at InformIT, a website for information technology professionals produced in collaboration with Sams at http://www.informit.com.

The Sams Publishing website, http://www.samspublishing.com, includes an online catalog, a list of upcoming releases, and links to author websites. It's a good place to see what's coming up from Sams Publishing and other parts of the Pearson Technology Group.


Sun's Official Java Site

The Java software division of Sun Microsystems Inc. maintains three websites of interest to programmers and users of its language.

Java.Sun.Com, which is published at http://java.sun.com, is the first place to visit when looking for Java-related information. New versions of the Java Development Kit and other programming resources are available for downloading, along with documentation for the entire Java class library. There's also a bug database, support forums, and full documentation for the Java 2 class library.

Java.Net, launched in 2003 at http://www.java.net, is a community resource where Java programmers can participate in discussions, start their own weblogs focused on the language, and host open-source Java projects.

Java.Com, also launched that year at http://www.java.com, promotes the benefits of the language to consumers and non-programmers. The Java runtime environment can be downloaded from the site to support the latest version of the language in Web applets, Java Web Start applications, and other programs.

Java 2 Class Documentation

Perhaps the most useful part of Sun's Java site is the documentation for every class, variable, and method in Java 2's class library. Thousands of pages are online at no cost to show you how to use the classes in your programs.

To visit the class documentation for Java 2 version 5, visit the web page at http://java.sun.com/j2se/1.5.0/docs/api.


Other Java Websites

Because so much of the Java phenomenon was originally inspired by its use on web pages, a large number of websites focus on Java and Java programming.

This Book's Official Site

This book has an official website at http://www.java24hours.com which is described fully in Appendix E, "This Book's Website."

Café au Lait

Elliotte Rusty Harold, the author of several excellent books on Java programming, offers Café au Lait, a frequently updated weblog covering Java news, product releases, and other sites of interest to programmers. The site is a terrific resource for people interested in Java and is published at http://www.ibiblio.org/javafaq. Harold also offers a list of frequently asked questions related to Java, as well as some unofficial documentation compiled by programmers over the past several years.

Workbench

I also publish a weblog, Workbench, that covers Java, Internet technology, computer books, and similar topics. Frequently, I use the weblog to discuss new developments in the language, open source projects built with Java, and issues called to my attention by readers of my books. It's published at http://www.cadenhead.org/workbench.

InformIT

The tech reference site InformIT, which is available at http://www.informit.com, is a comprehensive resource that was co-created by the publisher of this book. The site devotes sections to more than a dozen subjects related to software development and the Internet, including a comprehensive Java section by software analyst and author Steven Haines. InformIT's Java section includes how-to articles, a beginner's reference, and a weblog.

Java Review Service

The Java Review Service reviews new programs, components, and tools that are published on the Web, recognizing some as Top 1%, Top 5%, or Top 25%. Resources also are categorized by topic, with a description of each resource and links to download the source code, if it is available. To access the Java Review Service (JARS) website, which is another directory that rates Java applets, direct your web browser to http://www.jars.com.

JavaWorld Magazine

A long-running magazine, JavaWorld publishes frequent tutorial articles along with Java development news and other features, which are updated monthly. Visit on the Web at http://www.javaworld.com.

Gamelan: Earthweb's Java Directory

Because Java is an object-oriented language that offers JavaBeans as a means to create self-contained programming components, it is easy to use resources created by other developers in your own programs. Before you start a Java project of any significance, you should scan the Web for resources that you might be able to use in your program.

A good place to start is Gamelan, Earthweb's Java directory. This site catalogs Java programs, programming resources, and other information at http://www.developer.com/java.


Java Newsgroups

A good resource for both novice and experienced Java programmers is Usenet, the international network of discussion groups that is available to most Internet users through either an Internet service provider or a news service, such as Google Groups, http://groups.google.com or NewsGuy, http://www.newsguy.com.

The following are descriptions of some of the Java discussion groups that are available on Usenet:

  • comp.lang.java.programmer— Because this group is devoted to questions and answers related to Java programming, it is the place for all subjects that don't belong in one of the other groups. Any Java-related topic is suitable for discussion here.

  • comp.lang.java.advocacy— This group is devoted to any Java discussions that are likely to inspire heated or comparative debate. If you want to argue the merits of Java against another language, this is the place for it. This group can be a good place to consult if you want to see whether Java is the right choice for a project that you're working.

  • comp.lang.java.announce— This group contains announcements, advertisements, and press releases of interest to the Java development community. It is moderated, so that all postings must be submitted for approval before they are posted to the group.

  • comp.lang.java.beans— This group is devoted to discussions related to JavaBeans programming, announcements of beans that have been made available, and similar topics concerning component software development.

  • comp.lang.java.corba— This advanced discussion group is devoted to Java-language implementations of CORBA, the Common Object Request Broker Architecture.

  • comp.lang.java.databases— This group is used for talk related to JDBC, the Java Database Connectivity Libraries, and other solutions for connecting Java programs to databases.

  • comp.lang.java.gui— This group is devoted to the Abstract Windowing Toolkit, Swing, and other graphical user interface class libraries and development tools.

  • comp.lang.java.help— This group provides a place to discuss installation problems related to Java programming tools and similar issues that bedevil beginners.

  • comp.lang.java.machine— The most advanced of the Java discussion groups, this group is devoted to discussing the implementation of the language, issues with porting it to new machines, the specifics of the Java Virtual Machine, and similar subjects.

  • comp.lang.java.programmer— This group contains questions and answers related to Java programming, which makes it another good place for new programmers to frequent.

  • comp.lang.java.security— This discussion group is devoted to security issues related to Java, especially in regard to running Java programs and other executable content on the World Wide Web.


Internet Relay Chat

For a more interactive place to seek guidance from Java programmers, try Internet Relay Chat (IRC), a network of live chat rooms—which are called channels—devoted to specific topics.

The #java channel on the Undernet network was highly recommended by a reader of a previous edition of this book.

Undernet servers can be accessed from any IRC chat client. You also can participate over the Web by visiting http://www.undernet.org.

A Java applet on the site provides the means to communicate in real time with the users in the channel.

Before seeking help, you should review the frequently asked questions for the channel, which have been published on the Web at http://javafaq.mine.nu.

The channel can be rough on new arrivals, as demonstrated by an excerpt from the FAQ: "treating people who are showing a lack of motivation to help themselves like dirt is part of the great master plan of #java to actually scare people, so that they rather investigate their problems at Google for hours before asking in the channel."


Job Opportunities

If you're one of those folks learning Java as a part of your plan to become a captain of industry, several of the resources listed in this appendix have a section devoted to job opportunities. Check out some of the Java-related job openings that may be available.

If you are interested in joining Sun's Java division itself, visit http://www.sun.com/corp_emp.

Although it isn't specifically a Java employment resource, the World Wide Web site Career Builder enables you to search the job classifieds of more than two dozen job databases, including newspaper classifieds and many other sources. You have to register to use the site, but it's free, and there are more than 100,000 job postings that you can search using keywords such as Java or Internet or snake charmer. Go to http://www.careerbuilder.com.


Appendix E. This Book's Website

As much as I would like to think otherwise, there are undoubtedly some things you're not clear about after completing the 24 hours of this book.

Programming is a specialized technical field that throws strange concepts and jargon at you, such as "instantiation," "ternary operators," and "big- and little-endian byte order." Some of these concepts are pretty big, and when they hit you, it hurts.

If you're unclear about any of the topics covered in the book, or if I was unclear about a topic (sigh), visit the book's website at http://www.java24hours.com for assistance.

I use the book's website to offer each of the following:

  • Error corrections and clarifications: When errors are brought to my attention, they will be described on the site with the corrected text and any other material that will help.

  • Answers to reader questions: If readers have questions that aren't covered in this book's Q&A sections, many will be presented on the site.

  • The source code, class files, and resources required for all programs you create during the 24 hours of this book.

  • Sample Java programs: Working versions of some programs featured in this book are available on the site.

  • Solutions, including source code, for activities suggested at the end of each hour.

  • Updated links to the sites mentioned in this book: If sites mentioned in the book have changed addresses and I know about the new URL, I'll offer it here.

You also can send email to me by visiting the book's site. Click the Feedback link and you'll be taken to a page where you can send email directly from the Web.

This doesn't have to be said, as I learned from past editions of this book, but I'll say it anyway: Feel free to voice all opinions, positive, negative, indifferent, or undecided.

I have been a user of the Internet and online services long enough to have my parentage questioned in seven spoken languages and one particularly memorable nonverbal one. Any criticism you send will be interpreted as "tough love," and nothing you say could be rougher than what my music teacher said after my audition for the lead in the Yale Elementary School production of Jesus Christ Superstar.

Rogers Cadenhead


Sun Microsystems, Inc. Binary Code License Agreement

READ THE TERMS OF THIS AGREEMENT AND ANY PROVIDED SUPPLEMENTALLICENSE TERMS (COLLECTIVELY"AGREEMENT") CAREFULLY BEFORE OPENING THE SOFTWARE MEDIA PACKAGE. BY OPENING THE SOFTWARE MEDIA PACKAGE, YOU AGREE TO THE TERMS OF THIS AGREEMENT. IF YOU ARE ACCESSING THE SOFTWARE ELECTRONICALLY, INDICATE YOUR ACCEPTANCE OF THESE TERMS BY SELECTING THE "ACCEPT" BUTTON AT THE END OF THIS AGREEMENT. IF YOU DO NOT AGREE TO ALL THESE TERMS, PROMPTLY RETURN THE UNUSED SOFTWARE TO YOUR PLACE OF PURCHASE FOR A REFUND OR, IF THE SOFTWARE IS ACCESSED ELECTRONICALLY, SELECT THE "DECLINE" BUTTON AT THE END OF THIS AGREEMENT.

  1. LICENSE TO USE. Sun grants you a non-exclusive and non-transferable license for the internal use only of the accompanying software and documentation and any error corrections provided by Sun (collectively "Software"), by the number of users and the class of computer hardware for which the corresponding fee has been paid.

  2. RESTRICTIONS Software is confidential and copyrighted. Title to Software and all associated intellectual property rights is retained by Sun and/or its licensors. Except as specifically authorized in any Supplemental License Terms, you may not make copies of Software, other than a single copy of Software for archival purposes. Unless enforcement is prohibited by applicable law, you may not modify, decompile, or reverse engineer Software. You acknowledge that Software is not designed, licensed or intended for use in the design, construction, operation or maintenance of any nuclear facility. Sun disclaims any express or implied warranty of fitness for such uses. No right, title or interest in or to any trademark, service mark, logo or trade name of Sun or its licensors is granted under this Agreement.

  3. LIMITED WARRANTY. Sun warrants to you that for a period of ninety (90) days from the date of purchase, as evidenced by a copy of the receipt, the media on which Software is furnished (if any) will be free of defects in materials and workmanship under normal use. Except for the foregoing, Software is provided "AS IS". Your exclusive remedy and Sun's entire liability under this limited warranty will be at Sun's option to replace Software media or refund the fee paid for Software.

  4. DISCLAIMER OF WARRANTY. UNLESS SPECIFIED IN THIS AGREEMENT, ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT THESE DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.

  5. LIMITATION OF LIABILITY. TO THE EXTENT NOT PROHIBITED BY LAW, IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR SPECIAL, INDIRECT, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF OR RELATED TO THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. In no event will Sun's liability to you, whether in contract, tort (including negligence), or otherwise, exceed the amount paid by you for Software under this Agreement. The foregoing limitations will apply even if the above stated warranty fails of its essential purpose.

  6. Termination. This Agreement is effective until terminated. You may terminate this Agreement at any time by destroying all copies of Software. This Agreement will terminate immediately without notice from Sun if you fail to comply with any provision of this Agreement. Upon Termination, you must destroy all copies of Software.

  7. Export Regulations. All Software and technical data delivered under this Agreement are subject to US export control laws and may be subject to export or import regulations in other countries. You agree to comply strictly with all such laws and regulations and acknowledge that you have the responsibility to obtain such licenses to export, re-export, or import as may be required after delivery to you.

  8. U.S. Government Restricted Rights. If Software is being acquired by or on behalf of the U.S. Government or by a U.S. Government prime contractor or subcontractor (at any tier), then the Government's rights in Software and accompanying documentation will be only as set forth in this Agreement; this is in accordance with 48 CFR 227.7201 through 227.7202-4 (for Department of Defense (DOD) acquisitions) and with 48 CFR 2.101 and 12.212 (for non-DOD acquisitions).

  9. Governing Law. Any action related to this Agreement will be governed by California law and controlling U.S. federal law. No choice of law rules of any jurisdiction will apply.

  10. Severability. If any provision of this Agreement is held to be unenforceable, this Agreement will remain in effect with the provision omitted, unless omission would frustrate the intent of the parties, in which case this Agreement will immediately terminate.

  11. Integration. This Agreement is the entire agreement between you and Sun relating to its subject matter. It supersedes all prior or contemporaneous oral or written communications, proposals, representations and warranties and prevails over any conflicting or additional terms of any quote, order, acknowledgment, or other communication between the parties relating to its subject matter during the term of this Agreement. No modification of this Agreement will be binding, unless in writing and signed by an authorized representative of each party.

For inquiries please contact: Sun Microsystems, Inc. 4140 Network Circle, Santa Clara, CA 950


JAVA™ DEVELOPMENT TOOLS JAXP.JAR AND PARSER.JAR ARCHIVE FILES FROM JAVA API FOR XML PARSING, VERSION 1.0 SUPPLEMENTAL LICENSE TERMS

These supplemental license terms ("Supplemental Terms") add to or modify the terms of the Binary Code License Agreement (collectively, the "Agreement") for the jaxp.jar and parser.jar Archive Files from Java API for XML Parsing, Version 1.0 software ("XML JAR Files Software"). Capitalized terms not defined in these Supplemental Terms shall have the same meanings ascribed to them in the Agreement. These Supplemental Terms shall supersede any inconsistent or conflicting terms in the Agreement, or in any license contained within the XML JAR Files Software.

  1. Internal Use and Development License Grant. Subject to the terms and conditions of this Agreement, including, but not limited to, Section 3 (JavaTM Technology Restrictions) of these Supplemental Terms, Sun grants you a non-exclusive, non-transferable, limited license to reproduce internally and use internally the binary form of the XML JAR Files Software for the sole purpose of designing, developing and testing your JavaTM API for XML Parsing compatible parsers (the "Programs").

  2. License to Distribute Software. In addition to the license granted in Section 1 (Internal Use and Development License Grant) of these Supplemental Terms, subject to the terms and conditions of this Agreement, Sun grants you a non-exclusive, non- transferable, limited license to reproduce and distribute the XML JAR Files Software in binary code form only, provided that you: (i) (a) either distribute the XML JAR Files Software complete and unmodified in their original Java Archive file, but only bundled as part of your Programs into which the XML JAR Files Software is incorporated, and do not distribute additional software intended to replace any components of the XML JAR Files Software; or, alternatively (b) distribute the complete and unmodified archive file "jaxp.jar" without the archive file "parser.jar," but with a parser implementation that is compliant with the JAXP specification, only bundled as part of your Programs into which the "jaxp.jar" file is incorporated, and do not distribute additional software intended to replace any components of the archive file "jaxp.jar", (ii) do not remove or alter any proprietary legends or notices contained in the XML JAR Files Software, (iii) only distribute the XML JAR Files Software subject to a license agreement that protects Sun's interests consistent with the terms contained in this Agreement; and (iv) agree to defend and indemnify Sun and its licensors from and against any damages, costs, liabilities, settlement amounts and/ or expenses (including attorneys' fees) incurred in connection with any claim, lawsuit or action by any third party that arises or results from the use or distribution of any and all Programs and/or the XML JAR Files Software.

  3. JavaTM Technology Restrictions. You may not modify the JavaTM Platform Interface ("JPI", identified as classes contained within the "java" package or any subpackages of the "java" package), by creating additional classes within the JPI or otherwise causing the addition to or modification of the classes in the JPI. In the event that you create an additional class and associated API(s) which (i) extends the functionality of the JavaTM Platform, and (ii) is exposed to third party software developers for the purpose of developing additional software which invokes such additional API, you must promptly publish broadly an accurate specification for such API for free use by all developers. You may not create, or authorize your licensees to create additional classes, interfaces, or subpackages that are in any way identified as "java", "javax", "sun" or similar convention as specified by Sun in any naming convention designation.

  4. JavaTM Runtime Availability. Refer to the appropriate version of the JavaTM Runtime Environment binary code license (currently located at http://www.java.sun.com/jdk/index.html) for the availability of runtime code which may be distributed with JavaTM applets and applications.

  5. Trademarks and Logos. You acknowledge and agree as between you and Sun that Sun owns the JavaTM trademark and all Java-related trademarks, service marks, logos and other brand designations including the Coffee Cup logo and Duke logo ("JavaTM Marks") and you agree to comply with the Sun Trademark and Logo Usage Requirements currently located at http://www.sun.com/policies/trademarks. Any use you make of the JavaTM Marks inures to Sun's benefit.

  6. Source Code. The XML JAR File Software may contain source code that is provided solely for reference purposes pursuant to the terms of this Agreement. Source code may not be redistributed.

  7. Termination . Either party may terminate this Agreement immediately should any part of the XML JAR Files Software become, or in either party's opinion be likely to become, the subject of a claim of infringement of a patent, trade secret, copyright or other intellectual property right.


JAVAHELP™ VERSION 2.0 SUPPLEMENTAL LICENSE TERMS

These supplemental license terms ("Supplemental Terms") add to or modify the terms of the Binary Code License Agreement (collectively, the "Agreement"). Capitalized terms not defined in these Supplemental Terms shall have the same meanings ascribed to them in the Agreement. These Supplemental Terms shall supersede any inconsistent or conflicting terms in the Agreement, or in any license contained within the Software.

  1. Software Internal Use and Development License Grant. Subject to the terms and conditions of this Agreement, including, but not limited to Section 4 (Java™ Technology Restrictions) of these Supplemental Terms, Sun grants you a non- exclusive, non transferable, limited license to reproduce internally and use internally the binary form of the Software complete and unmodified for the sole purpose of designing, developing and testing your Java applets and applications intended to run on the Java platform ("Programs").

  2. License to Distribute Software. In addition to the license granted in Section 1 (Software Internal Use and Development License Grant) of these Supplemental Terms, subject to the terms and conditions of this Agreement, including but not limited to Section 4 (Java Technology Restrictions), Sun grants you a non-exclusive, non-transferable, limited license to reproduce and distribute the Software in binary form only, provided that you (i) distribute the Software complete and unmodified and only bundled as part of your Programs, (ii) do not distribute additional software intended to replace any component(s) of the Software, (iii) do not remove or alter any proprietary legends or notices contained in the Software, (iv) only distribute the Software subject to a license agreement that protects Sun's interests consistent with the terms contained in this Agreement, and (v) agree to defend and indemnify Sun and its licensors from and against any damages, costs, liabilities, settlement amounts and/or expenses (including attorneys' fees) incurred in connection with any claim, lawsuit or action by any third party that arises or results from the use or distribution of any and all Programs and/or Software.

  3. License to Distribute Redistributables. In addition to the license granted in Section 1 (Software Internal Use and Development License Grant) of these Supplemental Terms, subject to the terms and conditions of this Agreement, including but not limited to Section 3 (Java Technology Restrictions) of these Supplemental Terms, Sun grants you a non-exclusive, non-transferable, limited license to reproduce and distribute those files specifically identified as redistributable in the Software "README" file ("Redistributables") provided that: (i) you distribute the Redistributables complete and unmodified (unless otherwise specified in the applicable README file), and only bundled as part of your Programs, (ii) you do not distribute additional software intended to supersede any component(s) of the Redistributables, (iii) you do not remove or alter any proprietary legends or notices contained in or on the Redistributables, (iv) you only distribute the Redistributables pursuant to a license agreement that protects Sun's interests consistent with the terms contained in the Agreement, and (v) you agree to defend and indemnify Sun and its licensors from and against any damages, costs, liabilities, settlement amounts and/or expenses (including attorneys' fees) incurred in connection with any claim, lawsuit or action by any third party that arises or results from the use or distribution of any and all Programs and/or Software.

  4. Java Technology Restrictions. You may not modify the Java Platform Interface ("JPI", identified as classes contained within the "java" package or any subpackages of the "java" package), by creating additional classes within the JPI or otherwise causing the addition to or modification of the classes in the JPI. In the event that you create an additional class and associated API(s) which (i) extends the functionality of the Java platform, and (ii) is exposed to third party software developers for the purpose of developing additional software which invokes such additional API, you must promptly publish broadly an accurate specification for such API for free use by all developers. You may not create, or authorize your licensees to create, additional classes, interfaces, or subpackages that are in any way identified as "java", "javax", "sun" or similar convention as specified by Sun in any naming convention designation.

  5. Java Runtime Availability. Refer to the appropriate version of the Java Runtime Environment binary code license (currently located at http://www.java.sun.com/jdk/index.html) for the availability of runtime code which may be distributed with Java applets and applications.

  6. Trademarks and Logos. You acknowledge and agree as between you and Sun that Sun owns the SUN, SOLARIS, JAVA, JINI, FORTE, and iPLANET trademarks and all SUN, SOLARIS, JAVA, JINI, FORTE, and iPLANET-related trademarks, service marks, logos and other brand designations ("Sun Marks"), and you agree to comply with the Sun Trademark and Logo Usage Requirements currently located at http://www.sun.com/policies/trademarks. Any use you make of the Sun Marks inures to Sun's benefit.

  7. Source Code. Software may contain source code that is provided solely for reference purposes pursuant to the terms of this Agreement. Source code may not be redistributed unless expressly provided for in this Agreement. Some source code may contain alternative license terms that apply only to that source code file.

  8. Termination for Infringement. Either party may terminate this Agreement immediately should any Software become, or in either party's opinion be likely to become, the subject of a claim of infringement of any intellectual property right.

For inquiries please contact: Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, California 95054.(LFI#135834/Form ID#011801)


JAVA™ DEVELOPMENT TOOLS JAVAC COMPILER SUPPLEMENTAL LICENSE TERMS

These supplemental license terms ("Supplemental Terms") add to or modify the terms of the Binary Code License Agreement (collectively, the "Agreement") for the javac compiler ("Javac Compiler Software"). Capitalized terms not defined in these Supplemental Terms shall have the same meanings ascribed to them in the Agreement. These Supplemental Terms shall supersede any inconsistent or conflicting terms in the Agreement, or in any license contained within the Javac Compiler Software.

  1. Internal Use and Development License Grant. Subject to the terms and conditions of this Agreement, including, but not limited to, Section 3 (JavaTM Technology Restrictions) of these Supplemental Terms, Sun grants you a non-exclusive, non- transferable, limited license to reproduce internally and use internally the binary form of the Javac Compiler Software for the sole purpose of designing, developing and testing your JavaTM applets and applications intended to run on a compatible JavaTM platform (the "Programs")

  2. License to Distribute Software. In addition to the license granted in Section 1 (Internal Use and Development License Grant) of these Supplemental Terms, subject to the terms and conditions of this Agreement, Sun grants you a non-exclusive, non- transferable, limited license to reproduce and distribute the Javac Compiler Software in binary code form only, provided that you (i) distribute the Javac Compiler Software complete and unmodified, only bundled for the sole purpose of running your Programs into which the Javac Compiler Software is incorporated, (ii) do not distribute additional software intended to replace any component(s) of the Javac Compiler Software, (iii) do not remove or alter any proprietary legends or notices contained in the Javac Compiler Software, (iv) only distribute the Javac Compiler Software subject to a license agreement that protects Sun's interests consistent with the terms contained in this Agreement, and (v) agree to defend and indemnify Sun and its licensors from and against any damages, costs, liabilities, settlement amounts and/ or expenses (including attorneys' fees) incurred in connection with any claim, lawsuit or action by any third party that arises or results from the use or distribution of any and all Programs and/or Javac Compiler Software.

  3. JavaTM Technology Restrictions. You may not modify the JavaTM Platform Interface ("JPI", identified as classes contained within the "java" package or any subpackages of the "java" package), by creating additional classes within the JPI or otherwise causing the addition to or modification of the classes in the JPI. In the event that you create an additional class and associated API(s) which (i) extends the functionality of the JavaTM Platform, and (ii) is exposed to third party software developers for the purpose of developing additional software which invokes such additional API, you must promptly publish broadly an accurate specification for such API for free use by all developers. You may not create, or authorize your licensees to create additional classes, interfaces, or subpackages that are in any way identified as "java", "javax", "sun" or similar convention as specified by Sun in any naming convention designation. For a particular version of the Java platform, any executable output generated the Javac Compiler Software must (i) only be compiled from source code that conforms to the corresponding version of the OEM Java Language Specification; (ii) be in the class file format defined by the corresponding version of the OEM Java Virtual Machine Specification; and (iii) execute properly on a reference runtime, as specified by Sun, associated with such version of the Java platform.

  4. JavaTM Runtime Availability. Refer to the appropriate version of the JavaTM Runtime Environment binary code license (currently located at http://www.java.sun.com/jdk/index.html) for the availability of runtime code which may be distributed with JavaTM applets and applications.

  5. Trademarks and Logos. You acknowledge and agree as between you and Sun that Sun owns the JavaTM trademark and all Java-related trademarks, service marks, logos and other brand designations including the Coffee Cup logo and Duke logo ("JavaTM Marks") and you agree to comply with the Sun Trademark and Logo Usage Requirements currently located at http://www.sun.com/policies/trademarks. Any use you make of the JavaTM Marks inures to Sun's benefit.

  6. Source Code. The Javac Compiler Software may contain source code that is provided solely for reference purposes pursuant to the terms of this Agreement. Source code may not be redistributed.

  7. Termination. Either party may terminate this Agreement immediately should any Javac Compiler Software become, or in either party's opinion be likely to become, the subject of a claim of infringement of a patent, trade secret, copyright or other intellectual property right.

A Make Tool for the Java™ Language License -Java Make Tool

This is a language-specific make tool for Java applications. Copyright © 2001-2002, Sun Microsystems, Inc.

Redistribution and use in binary form, with or without modification, is permitted provided that the following conditions are met:

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

The name of Sun Microsystems, Inc. (the "Copyright Holder") may not be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER `AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

You acknowledge that this software is not designed, licensed or intended for use in the design, construction, operation or maintenance of any nuclear facility.


JAVA™ INTERFACE CLASSES J2EE™ DEPLOYMENT SPECIFICATION INTERFACE CLASSES 1.1 SUPPLEMENTAL LICENSE TERMS

These supplemental license terms ("Supplemental Terms") add to or modify the terms of the Binary Code License Agreement (collectively, the "Agreement"). Capitalized terms not defined in these Supplemental Terms shall have the same meanings ascribed to them in the Agreement. These Supplemental Terms shall supersede any inconsistent or conflicting terms in the Agreement, or in any license contained within the Software.

  1. Software Internal Use and Development License Grant. Subject to the terms and conditions of this Agreement, including, but not limited to Section 3 (Java™ Technology Restrictions) of these Supplemental Terms, Sun grants you a non- exclusive, non transferable, limited license to reproduce internally and use internally the binary form of the Software, complete and unmodified, for the sole purpose of designing, developing and testing your Java applets and applications ("Programs").

  2. License to Distribute Software. In addition to the license granted in Section 1 (Software Internal Use and Development License Grant) of these Supplemental Terms, subject to the terms and conditions of this Agreement, including but not limited to Section 3 (Java Technology Restrictions), Sun grants you a non-exclusive, non-transferable, limited license to reproduce and distribute the Software in binary form only, provided that you (i) distribute the Software complete and unmodified and only bundled as part of your Programs, (ii) do not distribute additional software intended to replace any component(s) of the Software, (iii) do not remove or alter any proprietary legends or notices contained in the Software, (iv) only distribute the Software subject to a license agreement that

    protects Sun's interests consistent with the terms contained in this Agreement, and (v) agree to defend and indemnify Sun and its licensors from and against any damages, costs, liabilities, settlement amounts and/or expenses (including attorneys' fees) incurred in connection with any claim, lawsuit or action by any third party that arises or results from the use or distribution of any and all Programs and/or Software.

  3. Java Technology Restrictions. You may not modify the Java Platform Interface ("JPI", identified as classes contained within the "java" package or any subpackages of the "java" package), by creating additional classes within the JPI or otherwise causing the addition to or modification of the classes in the JPI. In the event that you create an additional class and associated API(s) which (i) extends the functionality of the Java Platform, and (ii) is exposed to third party software developers for the purpose of developing additional software which invokes such additional API, you must promptly publish broadly an accurate specification for such API for free use by all developers. You may not create, or authorize your licensees to create additional classes, interfaces, or subpackages that are in any way identified as "java", "javax", "sun" or similar convention as specified by Sun in any naming convention designation.

  4. Trademarks and Logos. You acknowledge and agree as between you and Sun that Sun owns the SUN, SOLARIS, JAVA, JINI, FORTE, and iPLANET trademarks and all SUN, SOLARIS, JAVA, JINI, FORTE, and iPLANET-related trademarks, service marks, logos and other brand designations ("Sun Marks"), and you agree to comply with the Sun Trademark and Logo Usage Requirements currently located at http://www.sun.com/policies/trademarks. Any use you make of the Sun Marks inures to Sun's benefit.

  5. Source Code. Software may contain source code that is provided solely for reference purposes pursuant to the terms of this Agreement. Source code may not be redistributed unless expressly provided for in this Agreement.

  6. Termination for Infringement. Either party may terminate this Agreement immediately should any Software become, or in either party's opinion be likely to become, the subject of a claim of infringement of any intellectual property right.

For inquiries please contact: Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, California 95054. (LFI#136590/Form ID#011801)


JAVA 2, ENTERPRISE EDITION (J2EE™) MANAGEMENT, VERSION 1.0 JAVA™ INTERFACE CLASSES SUPPLEMENTAL LICENSE TERMS

These supplemental license terms ("Supplemental Terms") add to or modify the terms of the Binary Code License Agreement (collectively, the "Agreement"). Capitalized terms not defined in these Supplemental Terms shall have the same meanings ascribed to them in the Agreement. These Supplemental Terms shall supersede any inconsistent or conflicting terms in the Agreement, or in any license contained within the Software.

  1. Software Internal Use and Development License Grant. Subject to the terms and conditions of this Agreement, including, but not limited to Section 3 (Java(™) Technology Restrictions) of these Supplemental Terms, Sun grants you a non- exclusive, non transferable, limited license to reproduce internally and use internally the binary form of the Software, complete and unmodified, for the sole purpose of designing, developing and testing your Java applets and applications ("Programs").

  2. License to Distribute Software. In addition to the license granted in Section 1 (Software Internal Use and Development License Grant) of these Supplemental Terms, subject to the terms and conditions of this Agreement, including but not limited to Section 3 (Java Technology Restrictions), Sun grants you a non-exclusive, non-transferable, limited license to reproduce and distribute the Software in binary form only, provided that you (i) distribute the Software complete and unmodified and only bundled as part of your Programs, (ii) do not distribute additional software intended to replace any component(s) of the Software, (iii) do not remove or alter any proprietary legends or notices contained in the Software, (iv) only distribute the Software subject to a license agreement that protects Sun's interests consistent with the terms contained in this Agreement, and (v) agree to defend and indemnify Sun and its licensors from and against any damages, costs, liabilities, settlement amounts and/or expenses (including attorneys' fees) incurred in connection with any claim, lawsuit or action by any third party that arises or results from the use or distribution of any and all Programs and/or Software.

  3. Java Technology Restrictions. You may not modify the Java Platform Interface ("JPI", identified as classes contained within the "java" package or any subpackages of the "java" package), by creating additional classes within the JPI or otherwise causing the addition to or modification of the classes in the JPI. In the event that you create an additional class and associated API(s) which (i) extends the functionality of the Java Platform, and (ii) is exposed to third party software developers for the purpose of developing additional software which invokes such additional API, you must promptly publish broadly an accurate specification for such API for free use by all developers. You may not create, or authorize your licensees to create additional classes, interfaces, or subpackages that are in any way identified as "java", "javax", "sun" or similar convention as specified by Sun in any naming convention designation.

  4. Trademarks and Logos. You acknowledge and agree as between you and Sun that Sun owns the SUN, SOLARIS, JAVA, JINI, FORTE, and iPLANET trademarks and all SUN, SOLARIS, JAVA, JINI, FORTE, and iPLANET-related trademarks, service marks, logos and other brand designations ("Sun Marks"), and you agree to comply with the Sun Trademark and Logo Usage Requirements currently located at http://www.sun.com/policies/trademarks.

    Any use you make of the Sun Marks inures to Sun's benefit.

  5. Source Code. Software may contain source code that is provided solely for reference purposes pursuant to the terms of this Agreement. Source code may not be redistributed unless expressly provided for in this Agreement.

  6. Termination for Infringement. Either party may terminate this Agreement immediately should any Software become, or in either party's opinion be likely to become, the subject of a claim of infringement of any intellectual property right.

For inquiries please contact: Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, California 95054. (LFI#121544/Form ID#011801)


JAVA™ INTERFACE CLASSES ENTERPRISE JAVABEANS™, VERSION 2.0, INTERFACE CLASSES SUPPLEMENTAL LICENSE TERMS

These supplemental license terms ("Supplemental Terms") add to or modify the terms of the Binary Code License Agreement (collectively, the "Agreement"). Capitalized terms not defined in these Supplemental Terms shall have the same meanings ascribed to them in the Agreement. These Supplemental Terms shall supersede any inconsistent or conflicting terms in the Agreement, or in any license contained within the Software.

  1. Software Internal Use and Development License Grant. Subject to the terms and conditions of this Agreement, including, but not limited to Section 3 (Java Technology Restrictions) of these Supplemental Terms, Sun grants you a non-exclusive, non- transferable, limited license to reproduce internally and use internally the binary form of the Software, complete and unmodified, for the sole purpose of designing, developing and testing your Java applets and applications ("Programs").

  2. License to Distribute Software. In addition to the license granted in Section 1 (Software Internal Use and Development License Grant) of these Supplemental Terms, subject to the terms and conditions of this Agreement, including but not limited to Section 3 (Java Technology Restrictions), Sun grants you a non-exclusive, non-transferable, limited license to reproduce and distribute the Software in binary form only, provided that you (i) distribute the Software complete and unmodified and only bundled as part of your Programs, (ii) do not distribute additional software intended to replace any component(s) of the Software, (iii) do not remove or alter any proprietary legends or notices contained in the Software, (iv) only distribute the Software subject to a license agreement that protects Sun's interests consistent with the terms contained in this Agreement, and (v) agree to defend and indemnify Sun and its licensors from and against any damages, costs, liabilities, settlement amounts and/or expenses (including attorneys' fees) incurred in connection with any claim, lawsuit or action by any third party that arises or results from the use or distribution of any and all Programs and/or Software.

  3. Java Technology Restrictions. You may not modify the Java Platform Interface ("JPI", identified as classes contained within the "java" package or any subpackages of the "java" package), by creating additional classes within the JPI or otherwise causing the addition to or modification of the classes in the JPI. In the event that you create an additional class and associated API(s) which (i) extends the functionality of the Java Platform, and (ii) is exposed to third party software developers for the purpose of developing additional software which invokes such additional API, you must promptly publish broadly an accurate specification for such API for free use by all developers. You may not create, or authorize your licensees to create additional classes, interfaces, or subpackages that are in any way identified as "java", "javax", "sun" or similar convention as specified by Sun in any naming convention designation.

  4. Trademarks and Logos. You acknowledge and agree as between you and Sun that Sun owns the SUN, SOLARIS, JAVA, JINI, FORTE, and iPLANET trademarks and all SUN, SOLARIS, JAVA, JINI, FORTE, and iPLANET-related trademarks, service marks, logos and other brand designations ("Sun Marks"), and you agree to comply with the Sun Trademark and Logo Usage Requirements currently located at http://www.sun.com/policies/trademarks. Any use you make of the Sun Marks inures to Sun's benefit.

  5. Source Code. Software may contain source code that is provided solely for reference purposes pursuant to the terms of this Agreement. Source code may not be redistributed unless expressly provided for in this Agreement.

  6. Termination for Infringement. Either party may terminate this Agreement immediately should any Software become, or in either party's opinion be likely to become, the subject of a claim of infringement of any intellectual property right.

For inquiries please contact: Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, California 95054. (LFI#124415/Form ID#011801)


JAVA™ OPTIONAL PACKAGE JMX™, VERSION 1.2 SUPPLEMENTAL LICENSE TERMS

These supplemental license terms ("Supplemental Terms") add to or modify the terms of the Binary Code License Agreement (collectively, the "Agreement"). Capitalized terms not defined in these Supplemental Terms shall have the same meanings ascribed to them in the Agreement. These Supplemental Terms shall supersede any inconsistent or conflicting terms in the Agreement, or in any license contained within the Software.

  1. Software Internal Use and Development License Grant. Subject to the terms and conditions of this Agreement, including, but not limited to Section 3 (Java Technology Restrictions) of these Supplemental Terms, Sun grants you a non-exclusive, non- transferable, limited license to reproduce internally and use internally the binary form of the Software, complete and unmodified, for the sole purpose of designing, developing and testing your Java applets and applications ("Programs").

  2. License to Distribute Software. In addition to the license granted in Section 1 (Software Internal Use and Development License Grant) of these Supplemental Terms, subject to the terms and conditions of this Agreement, including but not limited to, Section 3 (Java Technology Restrictions) of these Supplemental Terms, Sun grants you a non-exclusive, non-transferable, limited license to reproduce and distribute the Software in binary code form only, provided that you (i) distribute the Software complete and unmodified and only bundled as part of your Programs, (ii) do not distribute additional software intended to replace any component(s) of the Software, (iii) do not remove or alter any proprietary legends or notices contained in the Software, (iv) only distribute the Software subject to a license agreement that protects Sun's interests consistent with the terms contained in this Agreement, and (v) agree to defend and indemnify Sun and its licensors from and against any damages, costs, liabilities, settlement amounts and/or expenses (including attorneys' fees) incurred in connection with any claim, lawsuit or action by any third party that arises or results from the use or distribution of any and all Programs and/or Software.

  3. Java Technology Restrictions. You may not modify the Java Platform Interface ("JPI", identified as classes contained within the "java" package or any subpackages of the "java" package), by creating additional classes within the JPI or otherwise causing the addition to or modification of the classes in the JPI. In the event that you create an additional class and associated API(s) which (i) extends the functionality of the Java platform, and (ii) is exposed to third party software developers for the purpose of developing additional software which invokes such additional API, you must promptly publish broadly an accurate specification for such API for free use by all developers. You may not create, or authorize your licensees to create additional classes, interfaces, or subpackages that are in any way identified as "java", "javax", "sun" or similar convention as specified by Sun in any naming convention designation.

  4. Trademarks and Logos. You acknowledge and agree as between you and Sun that Sun owns the SUN, SOLARIS, JAVA, JINI, FORTE, and iPLANET trademarks and all SUN, SOLARIS, JAVA, JINI, FORTE, and iPLANET-related trademarks, service marks, logos and other brand designations ("Sun Marks"), and you agree to comply with the Sun Trademark and Logo Usage Requirements currently located at http://www.sun.com/policies/trademarks. Any use you make of the Sun Marks inures to Sun's benefit.

  5. Source Code. Software may contain source code that is provided solely for reference purposes pursuant to the terms of this Agreement. Source code may not be redistributed unless expressly provided for in this Agreement.

  6. Termination for Infringement. Either party may terminate this Agreement immediately should any Software become, or in either party's opinion be likely to become, the subject of a claim of infringement of any intellectual property right.

For inquiries please contact: Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. (LFI#135010Form ID#011801)


J2EEeditor.jar SUPPLEMENTAL LICENSE TERMS

These supplemental license terms ("Supplemental Terms") add to or modify the terms of the Binary Code License Agreement (collectively, the "Agreement"). Capitalized terms not defined in these Supplemental Terms shall have the same meanings ascribed to them in the Binary Code License Agreement . These Supplemental Terms shall supersede any inconsistent or conflicting terms in the Binary Code License Agreement, or in any license contained within the Software.

  1. Software Internal Use and Development License Grant. Subject to the terms and conditions of this Agreement, including, but not limited to Section 3 (Java™ Technology Restrictions) of these Supplemental Terms, Sun grants you a non- exclusive, non transferable, limited license to reproduce internally and use internally the binary form of the Software, complete and unmodified, for the sole purpose of designing, developing and testing your Java applets and applications ("Programs").

  2. License to Distribute Software. In addition to the license granted in Section 1 (Software Internal Use and Development License Grant) of these Supplemental Terms, subject to the terms and conditions of this Agreement, including but not limited to, Section 3 (Java Technology Restrictions) of these Supplemental Terms, Sun grants you a non-exclusive, non-transferable, limited license to reproduce and distribute the Software in binary code form only, provided that you (i) distribute the Software complete and unmodified and only bundled as part of your Programs, (ii) do not distribute additional software intended to replace any component(s) of the Software, (iii) do not remove or alter any proprietary legends or notices contained in the Software, (iv) only distribute the Software subject to a license agreement that protects Sun's interests consistent with the terms contained in this Agreement, and (v) agree to defend and indemnify Sun and its licensors from and against any damages, costs, liabilities, settlement amounts and/or expenses (including attorneys' fees) incurred in connection with any claim, lawsuit or action by any third party that arises or results from the use or distribution of any and all Programs and/or Software.

  3. Java Technology Restrictions. You may not modify the Java Platform Interface ("JPI", identified as classes contained within the "java" package or any subpackages of the "java" package), by creating additional classes within the JPI or otherwise causing the addition to or modification of the classes in the JPI. In the event that you create an additional class and associated API(s) which (i) extends the functionality of the Java platform, and (ii) is exposed to third party software developers for the purpose of developing additional software which invokes such additional API, you must promptly publish broadly an accurate specification for such API for free use by all developers. You may not create, or authorize your licensees to create additional classes, interfaces, or subpackages that are in any way identified as "java", "javax", "sun" or similar convention as specified by Sun in any naming convention designation.

  4. Trademarks and Logos. You acknowledge and agree as between you and Sun that Sun owns the SUN, SOLARIS, JAVA, JINI, FORTE, and iPLANET trademarks and all SUN, SOLARIS, JAVA, JINI, FORTE, and iPLANET-related trademarks, service marks, logos and other brand designations ("Sun Marks"), and you agree to comply with the Sun Trademark and Logo Usage Requirements currently located at http://www.sun.com/policies/trademarks. Any use you make of the Sun Marks inures to Sun's benefit.

  5. Source Code. Software may contain source code that is provided solely for reference purposes pursuant to the terms of this Agreement. Source code may not be redistributed unless expressly provided for in this Agreement.

  6. Termination for Infringement. Either party may terminate this Agreement immediately should any Software become, or in either party's opinion be likely to become, the subject of a claim of infringement of any intellectual property right.

For inquiries please contact: Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, California 95054. (LFI#128129/Form ID#011801)


resolver-1_1_nb.jar Based on Sun's XML Resolver 1.0 Software License Agreement

SUN MICROSYSTEMS, INC. ("SUN") IS WILLING TO LICENSE XML ENTITY AND URI RESOLVERS, VERSION 1.0 SOFTWARE TO YOU ONLY UPON THE CONDITION THAT YOU ACCEPT ALL OF THE TERMS CONTAINED IN THIS LICENSE AGREEMENT ("AGREEMENT"). PLEASE READ THE TERMS AND CONDITIONS OF THIS AGREEMENT CAREFULLY. BY INSTALLING THIS SOFTWARE, YOU ACCEPT THE TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU ARE NOT WILLING TO BE BOUND BY ITS TERMS, SELECT THE "DECLINE" BUTTON AT THE BOTTOM OF THIS PAGE AND THE INSTALLATION PROCESS WILL NOT CONTINUE.

1.0 DEFINITIONS

"Licensed Software" means the XML Entity and URI Resolvers, Version 1.0 Software, any other machine readable materials (including, but not limited to, libraries, source files, header files, and data files) and any user manuals, programming guides and other documentation provided to you by Sun under this Agreement.

2.0 LIMITED LICENSE

2.1 Sun grants to you, a non-exclusive, non-transferable, royalty-free and limited license to reproduce, modify, and create derivative works of the Licensed Software for the sole purpose of adding value and improving the Licensed Software for the development of applications ("Programs").

2.2 In addition to the license granted in Section 2.1, Sun grants to you, a non-exclusive, non-transferable, royalty-free and limited license to distribute the Licensed Software modified by you as permitted in Section 2.1 ("Modified Software") in source or binary form, provided that; (i) the Modified Software is only distributed bundled as a part of your Programs, (ii) the Modified Software improves on and adds value to the Licensed Software, (iii) you do not remove any proprietary legends or notices contained in the Software, (iv) the Programs are only distributed subject to a license agreement that protects Sun's interests consistent with the terms and conditions contained in this Agreement, and (v) you agree to defend and indemnify Sun and its licensors from and against any damages, costs, liabilities, settlement amounts and/or expenses (including attorneys' fees) incurred in connection with any claim, lawsuit or action by any third party that arises or results from the use or distribution of any and all Modified Software and/or Licensed Software.

3.0 LICENSE RESTRICTIONS

3.1 You agree to reproduce any copyright and other proprietary right notices on any such copy.

3.2 Except as otherwise provided by Section 2.0, you may not modify or create derivative works of the Licensed Software, or reverse engineer, disassemble or decompile binary portions of the Licensed Software, or otherwise attempt to derive the source code from such portions.

3.3 No right, title, or interest in or to Licensed Software, any trademarks, service marks, or trade names of Sun or Sun's licensors is granted under this Agreement.

4.0 NO SUPPORT Sun is under no obligation to support Licensed Software or to provide you with updates or error corrections (collectively "Software Updates"). If Sun at its sole option, supplies Software Updates to you, the Software Updates will be considered part of Licensed Software, and subject to the terms of this Agreement.

5.0 TERM AND TERMINATION OF AGREEMENT

5.1 You may terminate this Agreement at any time by destroying all copies of Software.

5.2 Either party may terminate this Agreement immediately should any Software become, or in either party's opinion be likely to become, the subject of a claim of infringement of any intellectual property right.

5.3 This Agreement will terminate immediately without notice from Sun if the you fail to comply with any provision of this Agreement.

5.4 Upon termination or expiration of this Agreement, you shall immediately cease use of and destroy Licensed Software and any copies thereof.

5.5 Rights and obligations under this Agreement which by their nature should survive, will remain in effect after termination or expiration hereof.

6.0 DISCLAIMER OF WARRANTY

6.1 Licensee acknowledges that Licensed Software may contain errors and is not designed or intended for use in the design, construction, operation or maintenance of any nuclear facility ("High Risk Activities"). Sun disclaims any express or implied warranty of fitness for such uses. You represent and warrant to Sun that you will not use, distribute or license the Licensed Software for High Risk Activities.

6.2 LICENSED SOFTWARE IS PROVIDED "AS IS". ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS, AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.

7.0 LIMITATION OF LIABILITY

7.1 You acknowledge that the Licensed Software is experimental. You acknowledge that the Licensed Software may have defects or deficiencies which cannot or will not be corrected by Sun. You will hold Sun harmless from any claims based on your use or inability to use the Licensed Software for any purpose, and from any claims that later versions or releases of any Licensed Software furnished to you are incompatible with the Licensed Software provided to you under this Agreement.

7.2 You shall have the sole responsibility to protect adequately and backup your data and/or equipment used in connection with the Licensed Software. You shall not claim against Sun for lost data, re-run time, inaccurate output, work delays or lost profits resulting from your use of the Licensed Software.

7.3 In no event will Sun be liable for any indirect, punitive, special, incidental or consequential damage in connection with or arising out of this Agreement (including loss of business, revenue, profits, use, data or other economic advantage), however it arises, whether for breach or in tort, even if that Sun has been previously advised of the possibility of such damage.

8.0 U.S. GOVERNMENT RIGHTS If this Software is being acquired by or on behalf of the U.S. Government or by a U.S. Government prime contractor or subcontractor (at any tier), then the Government's rights in the Software and accompanying documentation shall be only as set forth in this license; this is in accordance with 48 C.F.R. 227.7201 through 227.7202-4 (for Department of Defense (DoD) acquisitions) and with 48 C.F.R. 2.101 and 12.212 (for non-DoD acquisitions).

9.0 GENERAL TERMS

9.1 Any action related to this Agreement will be governed by California law and controlling U.S. federal law. The U.N. Convention for the International Sale of Goods and the choice of law rules of any jurisdiction will not apply.

9.2 Licensed Software and technical data delivered under this Agreement are subject to U.S. export control laws and may be subject to export or import regulations in other countries. You agree to comply strictly with all such laws and regulations and acknowledge that you have the responsibility to obtain such licenses to export, re-export or import as may be required after delivery to you.

9.3 Neither party may assign or otherwise transfer any of its rights or obligations under this Agreement, without the prior written consent of the other party, except that Sun may assign this Agreement to an affiliated company.

9.4 This Agreement is the parties' entire agreement relating to its subject matter. It supersedes all prior or contemporaneous oral or written communications, proposals, conditions, representations and warranties and prevails over any conflicting or additional terms of any quote, order, acknowledgment, or other communication between the parties relating to its subject matter during the term of this Agreement. No modification to this Agreement will be binding, unless in writing and signed by an authorized representative of each party.


What's on the CD-ROM

The companion CD-ROM contains Sun Microsystem's Java 2 Platform Standard Edition, the NetBeans 4.1 IDE, jEdit, XOM Class Library, Apache XML-RPC, Java Outline Editor, and the source code from the book.


Windows Installation Instructions

1. | Insert the disc into your CD-ROM drive.
2. | From the Windows desktop, double-click on the My Computer icon.
3. | Double-click on the icon representing your CD-ROM drive.
4. | Double-click on the icon titled start.exe to run the installation program.
5. | Follow the on-screen prompts to finish the installation.

NOTE

If you have the AutoPlay feature enabled, the start.exe program starts automatically whenever you insert the disc into your CD-ROM drive.


UNIX and UNIX-like Installation Instructions

These installation instructions assume that you have a passing familiarity with UNIX commands and the basic setup of your machine. As UNIX has many flavors, only generic commands are used. If you have any problems with the commands, please consult the appropriate man page or your system administrator.

Insert CD-ROM in CD drive.

If you have a volume manager, mounting of the CD-ROM will be automatic. If you don't have a volume manager, you can mount the CD-ROM by typing

mount -tiso9660 /dev/cdrom /mnt/cdrom

NOTE

/mnt/cdrom is just a mount point, but it must exist when you issue the mount command. You may also use any empty directory for a mount point if you don't want to use /mnt/cdrom.

Open the readme.html file for descriptions and installation instructions.

Use of this software is subject to the Sun Microsystems, Inc. Binary Code License Agreement contained on page 535 of the accompanying book. Read this agreement carefully. By opening this package, you are agreeing to be bound by the terms and conditions of this agreement.

By opening this package, you are also agreeing to be bound by the following agreement:

You may not copy or redistribute the entire CD-ROM as a whole, Copying and redistribution of individual software programs on the CD-ROM is governed by terms set by individual copyright holders.

The installer and code from the author(s) are copyrighted by the publisher and the author(s). Individual programs and other items on the CD-ROM are copyrighted or are under GNU license by their various authors or other copyright holders.

This software is sold as-is without warranty of any kind, either expressed or implied, including but not limited to the implied warranties of merchantability and fitness for a particular purpose. Neither the publisher nor its dealers or distributors assumes any liability for any alleged or actual damages arising from the use of this program. (Some states do not allow for the exclusion of implied warranties, so the exclusion may not apply to you.)

NOTE

This CD-ROM uses long and mixed-case filenames requiring the use of a protected-mode CD-ROM Driver.


Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

Previous Section < Day Day Up >


index_SYMBOL

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

!! command (jdb)
!= (inequality operator)
" (double quotation mark)
$ (dollar sign)
% operator
' (single quotation mark)
' (single quotation marks)
escape code
(angle brackets)
(backslash)
escape code
(greater than operator) 2nd
(newline character)
(semicolon) 2nd 3rd
* (multiplication operator)
+ (plus sign)
addition operator (+)
concatenation operator 2nd 3rd
+= operator 2nd
- (minus sign)
decrement operator (--)
subtraction operator
-- (decrement operator)
-O option (javac)
. (period)
.class extensions
.class file extension
/ (division operator)
/ (forward slash)
// (double slashes)
program syntax
2D graphics 2nd 3rd 4th
arcs
drawing 2nd
circles
drawing
ellipses
drawing
lines
drawing 2nd 3rd 4th
PiePanel application 2nd
PieApplet.java 2nd 3rd 4th
PiePanel.java source code 2nd
PieSlice class 2nd
polygons
drawing 2nd
rectangles
drawing 2nd
; (semi-colon) program syntax
; (semicolon), program syntax
< (less than operator) 2nd 3rd
= (equal sign) 2nd
== (equality operator)
== operator
? (question mark)
ternary operator 2nd
@ [See tag (javadoc)]
@author tag (javadoc)
@deprecated tag (javadoc)
@exception tag (javadoc)
@param tag (javadoc)
@return tag (javadoc)
@serial tag (javadoc)
@since tag (javadoc)
@version tag (javadoc)
[ ] (brackets)
_ (underscore)
{} (braces) 2nd 3rd 4th
loops
program syntax

Previous Section < Day Day Up >


index_A

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

Abstract Windowing Toolkit [See AWT]
access control
definition of
methods
public methods
variables
default
private variables
protected variables
ActionListener interface 2nd
actionPerformed() method 2nd 3rd 4th 5th 6th 7th
ActiveX controls
versus applets
add() method
addActionListener() method
addChangeListener() method
addHandler() method
LottoServer class (XML-RPC)
addItemListener() method 2nd 3rd 4th 5th
addition operator (+)
addKeyListener() method
addOneToField() method
addSlice() method
ALIGN attribute (APPLET tag)
alphabet
numeric range of
AlphaTrade.com website 2nd 3rd
Animate applet 2nd
HTML markup 2nd
images
displaying 2nd 3rd
loading 2nd 3rd
storing 2nd
output
parameters
source code 2nd
animation
Bouncing Ball application 2nd 3rd
HTML markup
Java source code
creating 2nd 3rd 4th
images
displaying 2nd 3rd
loading 2nd 3rd
storing 2nd
pausing
speed
threads
Apache XML-RPC [See also XML-RPC]
core packages
current version
downloads
installing
Apache.org website
apostrophes (')
AppInfo application
Listing B.1 2nd 3rd
Listing B.2 2nd
AppInfo2 application
Apple Developer website
NetBeans downloads
Apple.com
JDK version
APPLET HTML tag
CODE attribute
Applet menu commands
Clone
Info
Reload
Restart
Start
Stop
Tag
APPLET tag
attributes
ARCHIVE
APPLET tag (HTML) 2nd 3rd
ALIGN attribute
CODEBASE attribute 2nd
HEIGHT attribute
WIDTH attribute
applets 2nd 3rd 4th [See also JApplet class]
access requirements 2nd
Animate 2nd 3rd 4th
displaying images 2nd 3rd 4th 5th 6th
HTML markup 2nd 3rd 4th
loading images 2nd 3rd 4th 5th 6th
output 2nd
parameters 2nd
source code 2nd 3rd 4th
stored images 2nd
storing related images 2nd
animation
creating 2nd 3rd 4th
displaying 2nd 3rd
loading 2nd 3rd
speed
storing 2nd
threads
class files
compared to applications 2nd
debugging 2nd
definition of 2nd 3rd
displaying
drawString() method 2nd
paint() method 2nd
repaint() method
downloading
event handling 2nd
actionPerformed() method 2nd
check boxes 2nd
combo boxes 2nd
event listeners 2nd 3rd
keyboard events 2nd 3rd
events
Full Text of BlanksApplet.html (Listing 4.6) 2nd
Full Text of BlanksApplet.java (Listing 4.5) 2nd
graphics
loading
HTML markup
APPLET tag 2nd 3rd
PARAM tag 2nd 3rd
initializing 2nd
Java Applet Ratings Service (JARS) website
Java on the Brain website
loading
troubleshooting
methods
destroy()
init() 2nd
paint() 2nd
repaint()
start() 2nd
stop() 2nd
online tutorial 2nd
parameters 2nd
naming
passing 2nd
receiving 2nd
ShowWeight applet example 2nd
popularity of
real-word examples
NASA J-Track 2nd
real-world examples
AlphaTrade.com 2nd 3rd
Gamelan website 2nd 3rd
Visible Human Project Website 2nd
Wurm Online 2nd
Revolve 2nd
class declaration 2nd
error handling 2nd
event handling 2nd
HTML markup 2nd
initializing 2nd
screen updates 2nd
source code 2nd
threads 2nd 3rd 4th 5th 6th
variables 2nd
RootApplet
HTML file 2nd
parameters
source coded
RootApplet.html (Listing 4.4) 2nd
RootApplet.java (Listing 4.3) 2nd
SalutonApplet
displaying 2nd
HTML markup
testing 2nd
SalutonApplet.java (Listing 17.1) 2nd
security
digital signatures
ShowWeight
HTML markup 2nd
output
source code 2nd 3rd
source code
viewing
starting 2nd
stopping 2nd
structure
testing
threaded 2nd
class declarations 2nd
error handling 2nd
event handling 2nd
initializing 2nd
running 2nd
screen updates 2nd
starting 2nd
stopping 2nd
variables 2nd
versus ActiveX controls
versus applications
syntax differences
windows
sizing 2nd
appletviewer browser
JDK
AppInfo sample application 2nd 3rd 4th 5th
appletviewer browser (JDK)
Applet menu commands 2nd
appletviewer tool
applications 2nd [See also programs] [See also applets]
AppInfo (Listing B.1) 2nd 3rd
AppInfo (Listing B.2) 2nd
AppInfo2
arguments
sending to 2nd 3rd
storing in arrays
string storage
autodialers 2nd 3rd
Bounce 2nd 3rd 4th 5th 6th
drawing images 2nd 3rd 4th
HTML markup 2nd
source code 2nd 3rd 4th
variables 2nd 3rd 4th
ClockFrame 2nd
ClockPanel 2nd 3rd 4th 5th
ClockTalk
output 2nd
source code 2nd 3rd
colors
HSB values 2nd
RGB values 2nd 3rd
setting 2nd
compared to applets 2nd
compiling 2nd
compiling (javac) 2nd
creating 2nd
Credits
code listing
compiling
output
running
Danger
class declaration
HTML markup 2nd
pausing
screen updates 2nd
sizing
source code 2nd
text displays
textColor object
textFont object
variables
debugging 2nd 3rd 4th 5th
definition of
distributing with Java Web Start 2nd
capabilities 2nd
Java Web Start Web site
JNLP (Java Network Launching Protocol) files 2nd 3rd 4th 5th
LottoMadness example 2nd 3rd 4th 5th
running applications 2nd 3rd 4th 5th 6th 7th 8th
security 2nd
Elvis
code listing
compiling
operators 2nd
output 2nd
running
FindPrimes
fonts
displaying
Fonts
displaying
Font class
point sizes 2nd
source code 2nd
styles
Game
output
source code
LottoMadness 2nd 3rd 4th 5th 6th 7th 8th
applet version
event listeners 2nd
Java Web Start 2nd 3rd 4th 5th
LottoEvent.java class 2nd
methods 2nd 3rd
multithreading
Name
output 2nd
Nines
output 2nd
source code 2nd
NoSpaces 2nd
organizing
block statements 2nd 3rd
PageCatalog 2nd 3rd
pausing
PiePanel 2nd
PieApplet.java 2nd 3rd 4th
PiePanel.java source code 2nd
PieSlice class 2nd
programming languages
selecting 2nd 3rd
ReadConsole 2nd
ReadID3 2nd
Repeat
compiling
running
source code 2nd 3rd
Root
compiling 2nd
source code
running 2nd
running via interpreter
Saluton
class declaration
class statement
compiling (javac) 2nd
debt variable
debugging 2nd 3rd
final source code
greeting variable 2nd 3rd 4th
initial source code 2nd
line-by-line breakdown
main() block
running 2nd
saving 2nd
Tool
Variable
char variables 2nd
floating-point variables 2nd
int statement
integer variables 2nd
string variables 2nd
variable types
Varible
code listing 2nd
versus applets
syntax differences
Virus
class constructor
getSeconds() method
infectFile() method
setSeconds() method
showVirusCount()
source code 2nd
tauntUser() method
VirusLook
output
source code 2nd
testing
Wheel of Fortune 2nd 3rd
character arrays
integer arrays
letterCount array
nested loops
output
source code 2nd
string arrays
Arc2D class
ARCHIVE attribute (<APPLET tag)
archiving Java files
jar tool (JDK) 2nd 3rd 4th
arcs
drawing 2nd
arguments
applications
storing in arrays
command line (JDK)
passing
to methods 2nd
sending to applications 2nd 3rd
string storage
ArrayIndexOutOfBoundsException class
ArrayIndexOutOfBoundsException errors
arrayoutofbounds errors
arrays 2nd
application arguments
storing
creating 2nd 3rd
declaring
definition of
elements
numbering 2nd
initial values 2nd
multidimensional
declaring 2nd
ranges
sample application 2nd
sorting 2nd 3rd 4th 5th 6th
website demo
tuned quicksorts
upper limits
checking
Wheel of Fortune application 2nd 3rd
output
source code 2nd
assert statement 2nd 3rd 4th
AssertionError exception 2nd 3rd
assertions 2nd 3rd 4th
assigning
variable types 2nd
variable values 2nd 3rd 4th
starting values
asterisk (*)
multiplication operator
attributes 2nd
(HTML) 2nd
<APPLET tag
ARCHIVE
ALIGN
CODE
CODEBASE 2nd
HEIGHT
inheritance 2nd
hierarchy 2nd
NAME
PARAM tag
SRC
WIDTH
autodialers 2nd 3rd
AUTOEXEC.BAT
editing
AWT 2nd
(Abstract Windowing Toolkit) 2nd
AWT (Abstract Windows Toolkit)
Insets class 2nd 3rd

Previous Section < Day Day Up >


index_B

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

Babelfish website
language translation features
backslash (
escape code
backspaces
escape code
Bart Simpson Chalkboard Punishments website
BASIC
(Beginner's All Symbolic Instruction Code)
BASIC language
bad writing habits
Liberty BASIC interpreter
BBEdit Lite
programs
writing source code in 2nd
Beginner's All Symbolic Instruction Code [See BASIC]
behavior [See also methods]
(objects)
inheritance 2nd
hierarchy 2nd
blank spaces in source code
Blanks application 2nd
block statements 2nd 3rd 4th
blocks
braces ({}) notation
in statements
blocks in statements
BOLD style (fonts)
books
Java resources
Boole, George
boolean variables 2nd 3rd
BorderLayout manager 2nd 3rd
borders
Insets class 2nd 3rd
Bounce application 2nd 3rd
HTML markup
images
drawing 2nd
source code
variables 2nd
Bounce.java (Listing 24.4) 2nd 3rd
BouncePanel class
source code
BouncePanel.java (Listing 24.3) 2nd 3rd
BoxLayout manager 2nd
braces ({}) 2nd 3rd
program syntax
braces {}
loops
brackets ([ ])
brackets ({}) 2nd
blocks
loops
brackets [ ]
break statement 2nd 3rd
breaking
loops 2nd
breakpoints
deleting 2nd
jdb debugger
setting 2nd
browser (appletviewer)
JDK
AppInfo sample application 2nd 3rd 4th 5th
Applet menu commands 2nd
browsers
Java Plug-in
downloading
Navigator
configuring
buffered input streams 2nd 3rd 4th
creating
ReadConsole application 2nd
reading
bugs 2nd [See also debugging]
Builder class (XML)
built-in methods
support
buttons
creating 2nd 3rd
byte streams
byte variable type
bytecode
bytecode interpreters
bytes
arguments versus streams

Previous Section < Day Day Up >


index_C

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

C++
Stroustrop, Bjarne
versus Java
Cafeconleche.org
CafeConLeche.org
XML libraries
downloading
calling
methods
start()
stop()
cannot resolve symbol (error message)
career opportunities
CareerBuilder website
Sun Microsystems website
career resources
CareerBuilder.com
CareerBuilder.com
carriage returns
escape code
case
changing
strings 2nd 3rd
case sensitivity
variable names
case statements
casting
definition of
destinations
objects 2nd
sources
strings
variables 2nd 3rd
catch statement 2nd 3rd
catching
errors 2nd
catching exceptions 2nd 3rd 4th
multiple exceptions 2nd
PageCatalog sample application 2nd 3rd
try-catch blocks 2nd 3rd 4th 5th 6th 7th 8th
DivideNumbers sample application 2nd
SumNumbers sample application 2nd 3rd 4th 5th
try-catch-finally blocks 2nd
CD command (MS-DOS) 2nd
CE product markings
EU-approval
CE-Mark.com
CENTER tag (HTML)
change listeners
ColorSlide sample application 2nd
registering objects as 2nd
ChangeListener interface
changing
string case 2nd 3rd
char variables
declaring 2nd 3rd
characters
definition of 2nd 3rd
special
escape codes 2nd
chat rooms
Java resources
Internet Relay Chat (IRC)
Undernet.org 2nd
check boxes
creating 2nd
event handling 2nd
checkAuthor() method
choice lists [See combo boxes]
event handling 2nd
choosing
text editors 2nd 3rd 4th
circles
coordinates for constructor method
drawing
clases
threaded 2nd 3rd 4th 5th
class files
specifying
class methods
declaring 2nd
class statement 2nd 3rd
class variables
creating 2nd
values
changing
classes
Arc2D
ArrayIndexOutOfBoundsException
Color 2nd
declaring
class statement
declaring via class statement
documentation for Java 2
Ellipse2D
encapsulation
Exception
expanding
file 2nd
FileInputStream
FileOutputStream
Float
Font
FontMetrics
Graphics
Graphics2D 2nd 3rd 4th
arcs 2nd
circles
ellipses
lines 2nd 3rd 4th
polygons 2nd
rectangles 2nd
hierarchy 2nd
inheritance 2nd 3rd 4th 5th 6th 7th
establishing
hierarchy 2nd
inner classes 2nd 3rd 4th
Insets 2nd 3rd
JApplet 2nd
inheritance 2nd 3rd
methods 2nd 3rd 4th 5th 6th
subclasses
JButton 2nd
JCheckBox 2nd
JComboBox 2nd 3rd
JFrame 2nd
JLabel 2nd
JMenu 2nd 3rd
JMenuBar 2nd 3rd
JMenuItem 2nd
JPanel 2nd
JScrollPane
JSlider
JTextArea
JTextField 2nd
Line2D 2nd
LottoEvent 2nd 3rd 4th 5th 6th
Modem
packages
creating
PieSlice 2nd
Point
Point3D
creating 2nd
testing 2nd 3rd
private
ReadConsole 2nd 3rd
Rectangle2D 2nd
referencing
Revolve
creating
sub
creating
subclasses
creating 2nd 3rd 4th 5th 6th
superclasses
creating
multiple
testing 2nd 3rd
Thread
Virus
classes command (jdb)
CLASSPATH variable
Windows 98/Me
setting (JDK) 2nd 3rd
Windows NT/2000/XP
setting (JDK) 2nd 3rd
clear command (jdb)
clearAllFields() method
clients
XML-RPC
creating 2nd 3rd
ClockFrame application 2nd
ClockPanel application 2nd 3rd 4th 5th
ClockTalk application
Gregorian calendar system
output 2nd
source code 2nd 3rd
ClockTalk Program (Listing 7.3) 2nd 3rd 4th 5th 6th
clocls [See Clock application, ClockTalk application]
Clone command (Applet menu)
close() method
closePath() method
closing
streams
CODE attribute (APPLET tag)
code listings
Dog.java
Elvis application
output
FindPrimes application
PiePanel.java source code
ReadConsole application
Repeat program
source code
RootApplet
parameters
CODEBASE attribute (APPLET tag) 2nd
CODEBASE attribute (OBJECT tag)
color
GUI components
Hexadecimal Hues website
Color class 2nd
colors [See also Danger application]
displaying
HSB values 2nd
RGB values 2nd 3rd
GUIs
HSB values 2nd
monitor limitations
RGB values 2nd 3rd
setting 2nd 3rd 4th
ColorSlide application 2nd
com object
creating 2nd
combo boxes
creating 2nd 3rd
event handling 2nd
command line
options (JDK) 2nd
command line utility
arguments (JDK)
command line utility (JDK)
command-line interfaces
JDK
configuring 2nd
commands
Applet menu
Clone
Info
Reload
Restart
Start
Stop
Tag
doskey (MS-DOS)
jar (JDK) 2nd 3rd 4th
javac 2nd
jdb (debugger)
!!
classes
clear
cont
down
exit
ignore
list
locals
memory
methods
print
run
step
stop at 2nd
stop in
suspend
threads
up
JDK
format
MS-DOS
CD 2nd
MD 2nd
Start menu
Run
View menu
Page Source
Source
Windows 98/Me
CLASSPATH variable, setting (JDK) 2nd 3rd
PATH variable, setting (JDK) 2nd 3rd
Windows NT/2000/XP
CLASSPATH variable, setting (JDK) 2nd 3rd
PATH variable, setting (JDK) 2nd 3rd
comments
in programs
program syntax
souce code
comp.lang.java.advocacy newsgroup
comp.lang.java.announce newsgroup
comp.lang.java.beans newsgroup
comp.lang.java.databases newsgroup
comp.lang.java.gui newsgroup
comp.lang.java.help newsgroup
comp.lang.java.machine newsgroup
comp.lang.java.programmer newsgroup 2nd
comp.lang.java.security newsgroup
comparing
strings 2nd 3rd
equal/not equal comparisons 2nd
less/greater than comparisons 2nd
compiled languages
performance
versus interpreted languages
compiler (javac)
JDK 2nd 3rd 4th
compilers
error messages
line-specific
function of 2nd
javac 2nd
error messages 2nd 3rd
compiling
applications 2nd
Credits
javac tool 2nd
files
javac compiler 2nd 3rd 4th
multiple
Java programs
in Windows 2nd 3rd
programs
NetBeans 2nd
Variable application
complex for loops 2nd
components 2nd 3rd
buttons
creating 2nd 3rd
change listeners
ColorSlide sample application 2nd
registering objects as 2nd
check boxes
creating 2nd
event handling 2nd
ClockFrame application 2nd
ClockPanel application 2nd 3rd 4th 5th
colors
changing
combo boxes 2nd 3rd
event handling 2nd
disabling 2nd
enabling 2nd
frames 2nd
adding components to
creating 2nd 3rd 4th
sizing
image icons 2nd 3rd 4th
creating 2nd 3rd
Tool sample application
labels
creating 2nd
menus
creating 2nd 3rd 4th 5th
JMenu component 2nd 3rd
JMenuBar component 2nd 3rd
JMenuItem component 2nd
panels 2nd
scroll panes
adding components to
creating 2nd
WriteMail sample application 2nd
sliders 2nd
creating 2nd 3rd 4th
labels
text areas
creating
text fields
creating 2nd
write protecting
TextField
toolbars 2nd 3rd 4th
creating 2nd 3rd
dockable toolbars
Tool sample application
windows 2nd 3rd 4th 5th 6th 7th 8th
concatenating
strings 2nd
concatenation operator (+) 2nd 3rd
conditionals 2nd
ClockTalk application
output 2nd
source code 2nd 3rd
if 2nd 3rd 4th 5th 6th
blocks 2nd 3rd
equal/not equal comparisons 2nd
less thn/greater thn comparisons
less/greater than comparisons
if-else 2nd
switch 2nd
ternary operator (?) 2nd
configuration properties
programs
reading 2nd 3rd
writing 2nd 3rd
configuring
JDK
on Windows OS 2nd 3rd 4th
Netscape Navigator
constants
advantages
constructor methods
arguments
declaring
inheritance
constructors
cont command (jdb)
container objects
Panel 2nd
containers
continue statement
controlling access [See access control]
controls (ActiveX)
versus applets
converting [See also casting]
objects 2nd
source code
javac compiler 2nd 3rd 4th
strings
to floating-point numbers
variables to objects 2nd 3rd
counter variables
(for loops)
definition of
initializing
createNewFile() method
creating
arrays 2nd 3rd
classes
packages
folders
MS-DOS (JDK) 2nd
MS-DOS folders in JDK 2nd
source files
Credits application
code listing
compiling
output
running
Credits Program (Listing 6.1) 2nd 3rd 4th
currentThread() method

Previous Section < Day Day Up >


index_D

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

Danger application
class declaration
HTML markup 2nd
methods
drawString()
paint() 2nd
pause() 2nd
repaint()
setColor()
size()
update()
objects
textColor
textFont
pausing
screen updates 2nd
sizing
source code listing 2nd
text
displaying
variables
danger messages, displaying [See Danger application]
data types [See type values]
boolean 2nd 3rd
byte
char 2nd 3rd
long 2nd
short
String
date/time, displaying
ClockFrame application 2nd
ClockPanel application 2nd 3rd
debugger (jdb) 2nd
applet debugging 2nd
application debugging
breakpoints
deleting 2nd
setting
commands
!!
classes
clear
cont
down
exit
ignore
list
locals
memory
methods
print
run
step
stop at 2nd
stop in
suspend
threads
up
JDK
application debugging
breakpoints
single-step execution 2nd 3rd
debugging
applets 2nd
applications
via jdb tool (JDK)
breakpoints
deleting 2nd
setting
definition of
jbd debugger
single-step execution 2nd 3rd
jdb debugger
breakpoints
OOP applications 2nd
programs
javac tool
Saluton program 2nd 3rd
declaring
arrays
multidimensional 2nd
classes
class statement 2nd
subclasses 2nd 3rd 4th 5th
methods
class methods 2nd
constructors
public methods
variables 2nd 3rd 4th
boolean 2nd 3rd
byte type
char
char variables 2nd
class variables 2nd
floating-point
integers
long
object variables 2nd
Revolve applet
Revolve program
short
strings 2nd 3rd
decrement operator (--)
decrementing
variables 2nd 3rd 4th
default statement
defining
classes
inner classes 2nd 3rd
deleting
breakpoints 2nd
files
Demos component (JDK)
deprecation option (javac)
destinations (casting)
destroy() method
determining
string lengths 2nd
developing
Java programs
Developing Java Servlets, Second Edition
development tools
installing
NetBeans
installing 2nd
selecting 2nd
versus JDK 2nd
Development Tools component (JDK)
development toos
compatibility with Java 2
dialects (XML)
digital signatures
disabling
components 2nd
displaying
applets
drawString() method 2nd
paint() method 2nd
repaint() method
colors 2nd
HSB values 2nd
RGB values 2nd 3rd
danger messages [See Danger application]
errors
fonts 2nd
images 2nd 3rd
strings
println() method 2nd
special characters 2nd
variable contents 2nd
displaySpeed() method 2nd
distributing applications
Java Web Start 2nd
capabilities 2nd
Java Web Start Web site
JNLP (Java Network Launching Protocol) files 2nd 3rd 4th 5th
LottoMadness example 2nd 3rd 4th 5th
running applications 2nd 3rd 4th 5th 6th 7th 8th
security 2nd
division operator (/)
do-while loops 2nd 3rd 4th 5th
exiting 2nd
dockable toolbars
DOCTYPE statement (XML)
documentation
Java
downloading
Java 2
Swing
documentation tool (javadoc)
AppInfo2 sample application
JDK 2nd 3rd 4th 5th 6th
tags 2nd 3rd
documentation tools
javadoc
AppInfo2 sample application
tags 2nd 3rd 4th
documents
HTML
viewing
dollar sign ($)
doskey command (MS-DOS)
double quotation mark (")
double slashes (//)
program syntax
down command (jdb)
downloading
Apache XML-RPC
Java documentation
JDK 2nd 3rd
draw() method
drawImage() method 2nd
drawing
arcs 2nd
circles
ellipses
lines 2nd
lines of different widths 2nd
pie graphs 2nd
PieApplet.java 2nd 3rd 4th
PiePanel.java source code 2nd
PieSlice class 2nd
polygons 2nd
rectangles 2nd
drawing images
Bouncing Ball application 2nd
drawRoundRect() method 2nd
drawString() method 2nd 3rd 4th

Previous Section < Day Day Up >


index_E

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

Eclipse Kick Start
editing
AUTOEXEC.BAT
system properties
JDK 2nd 3rd 4th
editors (text) [See text editors]
choosing
programs
writing 2nd
educational applications
Visible Human Project website 2nd
Element class (XML)
methods
elements
initial values 2nd
numbering 2nd
Ellipse2D class
ellipses
coordinates for constructor method
drawing
else statements 2nd
Elvis application
code listing
compiling
operators 2nd
output 2nd
running
Elvis program
Elvis Program (Listing 5.2) 2nd
employment opportunities
CareerBuilder website
Sun Microsystems website
empty strings
declaring
enabling
components 2nd
encapsulation
endless loops
environment variables
equal sign (=) 2nd
equality operator (==)
equality operator (==)
equals() method 2nd
error handling 2nd 3rd
assertions 2nd 3rd 4th
catching exceptions 2nd 3rd 4th
multiple exceptions 2nd
PageCatalog sample application 2nd 3rd
try-catch blocks 2nd 3rd 4th 5th 6th 7th 8th
try-catch-finally blocks 2nd
creating exceptions
ignoring exceptions 2nd
memory errors
stack overflows
throwing exceptions 2nd 3rd
PageCatalog sample application 2nd 3rd
throw statements
try-catch statements
try...catch statements 2nd
error messages
cannot resolve symbol
compilers
line-specific
errors
arrayoutofbounds
bugs
debugging 2nd 3rd
displaying
exceptions 2nd
ArrayIndexOutOfBoundsException
javac error messages 2nd 3rd
JDK configuration
correcting 2nd
logic
operators
logic errors
escape codes 2nd
Esperanto language
origins
European Free Trade Association
CE product markings
European Union
CE product markings
evaluating
expressions
operator precedence
event handling 2nd
actionPerformed() method 2nd 3rd 4th
check boxes 2nd
combo boxes 2nd
event listeners 2nd
ActionListener interface
LottoMadness application 2nd
keyboard events 2nd 3rd
event listeners 2nd
ActionListener interface
actionPerformed() method 2nd
adding
LottoMadness application 2nd
EventListener interfaces 2nd
Exception class
exceptions 2nd
ArrayIndexOutOfBoundsException
AssertionError 2nd 3rd
assertions 2nd 3rd 4th
catching 2nd 3rd 4th
multiple exceptions 2nd
PageCatalog sample application 2nd 3rd
try-catch blocks 2nd 3rd 4th 5th 6th 7th 8th
try-catch-finally blocks 2nd
creating
ignoring 2nd
throwing 2nd 3rd
PageCatalog sample application 2nd 3rd
throw statements
execute() method
LottoClient class 2nd 3rd
executing [See starting]
programs in MS-DOS (JDK) 2nd 3rd
exists() method
exit command (jdb)
exiting
loops 2nd
expanding
classes
expressions 2nd 3rd 4th
advantages 2nd
Elvis Program (Listing 5.2) 2nd
operator precedence 2nd 3rd 4th
Zsee also operators
extends statement 2nd
Extensible Markup Language (XML)
extensions
.class
extensions (file)
.class

Previous Section < Day Day Up >


index_F

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

File class 2nd
file extensions
.class
FileInputStream class
filename extensions
.java
programs, saving as
FileOutputStream class
files
archiving via jar utility (JDK) 2nd 3rd 4th
checking existance of
compiling
compiling (javac compiler) 2nd 3rd 4th
creating
deleting
File class 2nd
file extensions
.class
finding size of
formats
jar 2nd 3rd 4th
mulitple
compiling
reading
ReadID3 application 2nd 3rd 4th 5th
streams 2nd 3rd
renaming
writing to
streams 2nd 3rd
fill() method
fillRect() method
fillRoundRect() method
finding
strings within strings 2nd
FindPrimes application
Finished Version of the Saluton Program (Listing 2.2)
Float class
float statement
floating-point numbers
converting strings to
floating-point variables
declaring
floatValue() method
FlowLayout manager 2nd 3rd 4th
folders
MS-DOS folders
creating (JDK) 2nd
opening (JDK) 2nd
Font class
FontMetrics class
fonts [See also Danger application]
displaying 2nd 3rd
Font class
point size
limitations
specifying
styles
Fonts application
source code 2nd
for loops 2nd 3rd 4th 5th 6th
complex for loops 2nd
counter variables 2nd
empty sections
exiting 2nd
multiple statement sections
sample application 2nd 3rd 4th
syntax 2nd 3rd
forcing
screen updates
formfeeds
escape codes
forward slash (/)
frames
adding components to
creating 2nd 3rd
SalutonFrame.java example 2nd 3rd
sizing
Full Source Code of Name.java (Listing 9.2) 2nd 3rd
Full Source Code of Repeat.java (Listing 8.2) 2nd 3rd 4th
Full Source Code of Wheel.java (Listing 9.2)
Full Source Code of Wheel.java (Listing 9.3)
Full Text of Aggregator.java (Listing 21.4) 2nd 3rd
Full Text of Animate.html (Listing 24.2)
Full Text of Animate.java (Listing 24.1) 2nd 3rd
Full Text of AppInfo.html (Listing B.2) 2nd
Full Text of AppInfo.java (Listing B.1) 2nd 3rd
Full Text of Blanks.java (Listing 4.2) 2nd
Full Text of BlanksApplet.html (Listing 4.6) 2nd
Full Text of BlanksApplet.java (Listing 4.5) 2nd
Full Text of CableModem.java (Listing 10.3)
Full Text of ClockFrame.java (Listing 13.4) 2nd
Full Text of ClockPanel.java (Listing 13.3) 2nd 3rd 4th
Full Text of ColorSlide.java (Listing 16.2) 2nd 3rd 4th 5th
Full Text of Crisis.java (Listing 14.1) 2nd 3rd
Full Text of Danger.java (Listing 22.2) 2nd
Full Text of DangerFrame.java (Listing 22.3) 2nd
Full Text of DivideNumbers.java (Listing 18.3) 2nd
Full Text of DslModem.java (Listing 10.4)
Full Text of FindPrimes.java (Listing 19.1) 2nd 3rd
Full Text of HomePage.java (Listing 18.4) 2nd 3rd
Full Text of ItemProp.java application (Listing B.4)
Full Text of KeyView.java (Listing 15.1) 2nd
Full Text of lotto.log (Listing 25.2) 2nd
Full Text of LottoClient.java (Listing 25.4) 2nd 3rd
Full Text of LottoCounter.java (Listing 25.1) 2nd 3rd 4th
Full Text of LottoEvent.java (Listing 15.2) 2nd 3rd 4th 5th 6th
Full Text of LottoEvent.java (Listing 25.5) 2nd 3rd 4th 5th 6th 7th
Full Text of LottoMadness,jnlp (Listing 17.5) 2nd 3rd 4th 5th 6th
Full Text of LottoMadness.java (Listing 14.2) 2nd 3rd 4th 5th 6th
Full Text of LottoServer.java (Listing 25.3) 2nd 3rd
Full Text of Madness.java (Listing 15.3) 2nd 3rd 4th
Full Text of Modem.java (Listing 10.2)
Full Text of NewRoot.java (Listing 10.1) 2nd
Full Text of NewSumNumbers.java (Listing 18.2) 2nd
Full Text of Nines.java (Listing 8.1) 2nd 3rd
Full Text of NoSpaces.java (Listing 9.1) 2nd
Full Text of PageCatalog.java (Listing 18.5) 2nd 3rd
Full Text of PieApplet.html (Listing 23.4)
Full Text of PiePanel.java (Listing 23.2) 2nd 3rd
Full Text of Playback.java (Listing 13.2) 2nd
Full Text of Player.java (Listing 22.1) 2nd 3rd
Full Text of Point3D.java (Listing 12.2) 2nd
Full Text of properties.xml (Listing 21.2) 2nd 3rd 4th
possible document type declaration (dtd) error
Full Text of PropertyFileCreator.java (Listing 21.1) 2nd
Full Text of PropertyFileReader.java (Listing 21.3) 2nd 3rd
Full Text of ReadConsole.java (Listing 20.2) 2nd 3rd
Full Text of ReadID3.java (Listing 20.1) 2nd 3rd
Full Text of Revolve.java (Listing 19.2) 2nd 3rd
Full Text of RootApplet.html (Listing 4.4) 2nd
Full Text of RootApplet.java (Listing 4.3) 2nd
Full Text of SalutonApplet.html (Listing 17.2) 2nd
Full Text of SalutonApplet.java (Listing 17.1) 2nd
Full Text of SalutonFrame.java (Listing 13.1) 2nd
Full Text of ShowWeight.html (Listing 17.4)
Full Text of ShowWeight.java (Listing 17.3) 2nd 3rd
Full Text of Sign.java (Listing 23.1) 2nd 3rd
Full Text of StringLister.java (Listing 12.1) 2nd 3rd
Full Text of SumNumbers.java (Listing 18.1) 2nd 3rd
Full Text of Tag Cleaner.java (Listing 20.6) 2nd 3rd 4th 5th
Full Text of TestModem.java (Listing 10.5) 2nd 3rd
Full Text of Tool.java (Listing 16.3) 2nd
Full Text of TryPoints.java (Listing 12.3) 2nd 3rd
Full Text of Virus.java (Listing 11.1) 2nd
Full Text of VirusLook.java (Listing 11.2) 2nd 3rd
Full Text of WriteMail.java (Listing 16.1) 2nd 3rd
functions
tools
modifying (JDK)

Previous Section < Day Day Up >


index_G

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

Game application
output
source code
Game Program (Listing 7.1) 2nd
Gamelan Web site
Gamelan website
Java Applet Ratings Service (JARS) 2nd
games
lotto [See LottoMadness application]
Wurms Online 2nd
getActionCommand() method 2nd
getAppletInfo() method 2nd 3rd
getCodeBase() method
getImage() method
getInsets() method
getKeyChar() method
getKeyCode() method
getKeyText() method
getName() method
getParameter() method 2nd
getParameterInfo() method
getSeconds() method
getSource() method 2nd
getStateChange() method
getTimeZone() method
getURL() method
getValueIsAdjusting() method
getVirusCount() method
Google Groups website
newsgroup resources 2nd
Gosling, James
Java development
graphical user interfaces [See GUIs]
graphics 2nd 3rd 4th 5th 6th
animation
Bouncing Ball application 2nd 3rd
creating 2nd 3rd
pausing
arcs
drawing 2nd
circles
drawing
color
HSB values 2nd
monitor limitations
RGB values 2nd 3rd
setting 2nd
ellipses
drawing
fonts
displaying 2nd
Font class
point size
point sizes
styles
Graphics class
icons 2nd 3rd 4th
creating 2nd 3rd
Tool sample application
images
displaying 2nd 3rd 4th 5th
drawing 2nd
loading 2nd 3rd 4th 5th
storing 2nd
lines
drawing 2nd 3rd 4th
loading 2nd 3rd
PiePanel application 2nd
PieApplet.java 2nd 3rd 4th
PiePanel.java source code 2nd
PieSlice class 2nd
polygons
drawing 2nd
rectangles
drawing 2nd
storing 2nd
Graphics class
Graphics2D class 2nd 3rd 4th
arcs
drawing 2nd
circles
drawing
ellipses
drawing
lines
drawing 2nd 3rd 4th
polygons
drawing 2nd
rectangles
drawing 2nd
graphs
pie graphs, creating 2nd
PieApplet.java 2nd 3rd 4th
PiePanel.java source code 2nd
PieSlice class 2nd
greater than operator 2nd
greeting variable
declaring 2nd
displaying contents of 2nd
Gregorian calendar system
ClockTalk application
GridLayout manager 2nd 3rd
GridLayout() method
GUIs 2nd 3rd 4th
AWT (Abstract Windowing Toolkit) 2nd
buttons
creating 2nd 3rd
change listeners
ColorSlide sample application 2nd
registering objects as 2nd
check boxes
creating 2nd
event handling 2nd
ClockFrame application 2nd
ClockPanel application 2nd 3rd 4th 5th
combo boxes
creating 2nd 3rd
event handling 2nd
enabling/disabling components 2nd
event handling
event listeners 2nd
ActionListener interface
actionPerformed() method 2nd
adding
frames
adding components to
creating 2nd 3rd
SalutonFrame.java example 2nd 3rd
sizing
image icons 2nd 3rd 4th
creating 2nd 3rd
Tool sample application
Insets 2nd 3rd
labels
creating 2nd
layout managers
BorderLayout 2nd 3rd
BoxLayout 2nd
FlowLayout 2nd 3rd 4th
GridLayout 2nd 3rd
LottoMadness sample application 2nd 3rd 4th 5th 6th
menus
creating 2nd 3rd 4th 5th
JMenu component 2nd 3rd
JMenuBar component 2nd 3rd
JMenuItem component 2nd
panels
creating 2nd
scroll panes
adding components to
creating 2nd
sliders 2nd 3rd 4th 5th 6th 7th
WriteMail sample application 2nd
Swing 2nd
text areas
creating
text fields
creating 2nd
write-protecting
toolbars 2nd 3rd 4th
creating 2nd 3rd
dockable toolbars
Tool sample application
windows 2nd 3rd 4th 5th 6th 7th 8th 9th

Previous Section < Day Day Up >


index_H

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

H [image] rnell. Karl
handlers
XML-RPC
creating 2nd 3rd 4th 5th 6th
handling errors [See error handling]
hardware
JDK requirements
NetBeans support
HEIGHT attribute (APPLET tag)
Hello World! Program [See Saluton application]
Hexadecimal Hues website
hierarchies
Java classes
homepage tag (JNL)
HomePage.java listing
horizontal sliders
creating
labels
HSB values
(hue, saturation, brightness) 2nd
HTML
tags
(angle brackets)
APPLET 2nd 3rd
CENTER
IMG
P
PARAM 2nd
HTML documents
viewing
Hue, Saturation, Brightness (HSB) color system 2nd
hyphen (-)
subtraction operator

Previous Section < Day Day Up >


index_I

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

I/O (input/output)
streams 2nd 3rd
buffered input streams 2nd 3rd 4th
byte streams
closing
defined 2nd
reading data from 2nd 3rd 4th 5th 6th 7th 8th
writing data to 2nd 3rd
iBiolio.org site
icons 2nd 3rd 4th
creating 2nd 3rd
Tool sample application
if statements 2nd 3rd 4th 5th 6th
blocks 2nd 3rd
equal/not equal comparisons 2nd
less than/greater than comparisons 2nd
if-else statements 2nd
ignore command (jdb)
ignoring exceptions 2nd
ImageIcon() method
images [See graphics]
drawing
Bouncing Ball application 2nd
IMG tag (HTML)
SRC attribute
import java.awt.* statement
import statement 2nd 3rd
incrementing
variables 2nd 3rd 4th
indexOf() method 2nd 3rd
inequality operator (!=)
infectFile() method
infinite loops
Inflation Calculator website
Info command (Applet menu)
information tag (JNL)
InformIT site
InformIT website
inheritance 2nd 3rd 4th 5th 6th 7th 8th 9th
constructors
establishing
hierarchy 2nd
init() block statements
init() method 2nd 3rd 4th
initializing
applets 2nd
Resolve 2nd
definition of
inner classes 2nd 3rd 4th
Insets class 2nd 3rd
installing
Apache XML-RPC
development tools
NetBeans 2nd
JDK 2nd
on Windows OS 2nd 3rd
troubleshooting installation
installing applications
Java Web Start 2nd
capabilities 2nd
Java Web Start Web site
JNLP (Java Network Launching Protocol) files 2nd 3rd 4th 5th
LottoMadness example 2nd 3rd 4th 5th
running applications 2nd 3rd 4th 5th 6th 7th 8th
security 2nd
InstallShield wizard
JDK installations on Windows OS
int statement
int variable
versus Integer object
Integer object
versus int variable
integers
arrays
creating
variable types
interfaces
ActionListener 2nd
ChangeListener
command-line
JDK configuration 2nd
defined
EventListener 2nd
ItemListener
KeyListener
Runnable
International Components for Unicode for Java website
Internet Assigned Numbers Authority (IANA) website
Internet Explorer
Java Plug-in
downloading
Internet Movie Database website
Internet Relay Chat (IRC)
interpreted languages
performance
versus compiled languages
interpreter (java)
JDK 2nd 3rd 4th
interpreters
definition of
Java Plug-in
Liberty BASIC interpreter
web browser support
Invalid argument error message
ITALIC style (fonts)
ItemListener interface
itemStateChanged() method 2nd
iteration [See loops]
iterators

Previous Section < Day Day Up >


index_J

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

JApplet class 2nd
inheritance 2nd 3rd
methods
add()
equals()
overriding 2nd
setBackground()
setLayout()
subclasses
creating
jar utility (JDK) 2nd 3rd 4th
JARS (Java Review Service)
Java
applications
running
compilers
development of
development tools
NetBeans 2nd
selecting 2nd
developmental history 2nd 3rd 4th
ease in learning language
Gosling, James
historical development
major version releases 2nd
programs
running without web browsers
virus dangers
Swing interface tool
versus C++ 2nd
versus other programming languages 2nd 3rd
Java 2 Enterprise Edition (J2EE)
versus Java 2 Standard Edition (J2SE)
Java 2 Java Development Kit version 5 [See JDK]
Java 2 Standard Edition (J2SE)
versus Java 2 Enterprise Edition (J2EE)
Java Applet Ratings Service (JARS)
card games directory
Gamelan website 2nd
Java Applet Ratings Service (JARS) website
applet resources
Java Database Connectivity (JDBC)
java interpreter (JDK) 2nd 3rd 4th
Java Network Launching Protocol (JNLP) 2nd 3rd 4th 5th
Java on the Brain website
Java Plug-in
downloading 2nd
Java programs
compiling
in Windows 2nd 3rd
developing
running in Windows 2nd 3rd
speed
Java Review Service
Java Web Start 2nd
capabilities 2nd
JNLP (Java Network Launching Protocol) files 2nd 3rd 4th 5th
LottoMadness example 2nd 3rd 4th 5th
running applications with 2nd 3rd 4th 5th 6th 7th 8th
security 2nd
Web site
Java website
Java.com
Java.net
Java24.com
NetBeans resources
Java24Hours.com
applet resources 2nd
features of
troubleshooting resources
XML-RPC resources
Java24Hours.com website
javac
options
-depreciation
-O
-verbose
javac command 2nd
javac compiler 2nd
error messages 2nd 3rd
javac compiler (JDK) 2nd 3rd 4th
javac tool
programs
debugging
javadoc
tags 2nd
@author
@deprecated
@exception
@param
@return
@see
@serial
@since
@version
javadoc documentation tool
AppInfo2 sample application
tags 2nd 3rd
javadoc documentation tool (JDK) 2nd 3rd 4th 5th 6th
JavaWorld Magazine Website 2nd 3rd
JavaWorld Magazine website
JButton objects 2nd
JCheckBox class 2nd
JComboBox class 2nd 3rd
jdb debugger 2nd
applet debugging 2nd
application debugging
breakpoints
deleting 2nd
setting
commands
!!
classes
clear
cont
down
exit
ignore
list
locals
memory
methods
print
run
step
stop at 2nd
stop in
suspend
threads
up
jdb debugger (JDK)
application debugging
breakpoints
single-step execution 2nd 3rd
JDBC-ODBC Bridge
JDK
(Java 2 Java Development Kit version 5)
CLASSPATH variable
setting in Windows 98/Me 2nd 3rd
setting in Windows NT/2000/XP 2nd 3rd
command line
arguments
commands
format
components of 2nd
configuration errors
correcting 2nd
configuring
on Windows OS 2nd 3rd 4th
Demos component
Development Tools component
downloading 2nd 3rd 4th
folders
creating in MS-DOS 2nd
opening in MS-DOS 2nd
function of
hardware requirements
installing 2nd
on Windows OS 2nd 3rd
Macintosh version
new version releases 2nd
non-GUI tool 2nd
PATH variable (Windows 98/Me)
setting 2nd 3rd
PATH variable (Windows NT/2000/XP)
setting 2nd 3rd
programs
running and compiling example 2nd
running in MS-DOS 2nd 3rd
Public Java 2 Runtime Environment (JRE)
sample program
creating (Listing A.1) 2nd 3rd
Source Code component
supported platforms
system properties
editing 2nd 3rd 4th
troubleshooting installations
utilities
appletviewer browser 2nd 3rd 4th 5th 6th
command line
jar 2nd 3rd 4th
java interpreter 2nd 3rd 4th
javac compiler 2nd 3rd 4th
javadoc documentation tool 2nd 3rd 4th 5th 6th 7th
jdb debugger 2nd 3rd
options 2nd
version number avaliability
versus conventional development tools 2nd
versus SDK terminology
jEdit text editor
JFrame class 2nd
Jini and JavaSpaces Application Development
JLabel class 2nd
JMenu class 2nd 3rd
JMenuBar class 2nd 3rd
JMenuItem class 2nd
JNLP (Java Network Launching Protocol) files 2nd 3rd 4th 5th
jnlp tag (JNL)
job opportunities
CareerBuilder website
Sun Microsystems website
Joy, Bill
JPanel class 2nd
JPython language
JRuby language
JScrollPane class
JScrollPane() method
JSlider class
JSlider() method
JTextArea class
JTextField class 2nd
JToolBar() method
JudoScript language
JXTA
Java P2P Programming

Previous Section < Day Day Up >


index_K

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

keyboard
event handling 2nd 3rd
KeyListener interface

Previous Section < Day Day Up >


index_L

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

Label() method
labels
creating 2nd
sliders
languages
Java bytecode
support for
JPython
JRuby
JudoScript
NetRexx
launching
NetBeans
layout managers
BorderLayout
FlowLayout 2nd 3rd 4th
GridLayout 2nd 3rd
LottoMadness sample application 2nd 3rd 4th 5th 6th
length variable 2nd 3rd
length() method 2nd
lengths of strings
determining 2nd
less than operator (<) 2nd 3rd
Liberty BASIC interpreter
website resources
libraries (XML)
downloading (CafeConLeche.org)
Line-by-Line Breakdown of the Saluton Program (Listing 2.3)
Line2D class 2nd
lines
drawing 2nd
lines of different widths 2nd
lineTo() method
linking
variables with strings 2nd
list command (jdb)
listeners 2nd
ActionListener interface
actionPerformed() method 2nd
adding
change listeners
ColorSlide sample application 2nd
registering objects as 2nd
LottoMadness application 2nd
listFiles() method
listings
Bounce.java (24.4) 2nd 3rd
BouncePanel.java (24.3) 2nd 3rd
ClockTalk Program (7.3) 2nd 3rd 4th 5th 6th
Credits Program (6.1) 2nd 3rd 4th
Elvis Program (5.2) 2nd
Finished Version of the Saluton Program (2.2)
Full Source Code of Name.java (9.2) 2nd 3rd
Full Source Code of Repeat.java (8.2) 2nd 3rd 4th
Full Source Code of Wheel.java (9.2)
Full Source Code of Wheel.java (9.3)
Full Text of Aggregator.java (21.4) 2nd 3rd
Full Text of Animate.html (24.2)
Full Text of Animate.java (24.1) 2nd 3rd
Full Text of AppInfo.html (B.1) 2nd
Full Text of AppInfo.java (B.1) 2nd 3rd
Full Text of Blanks.java (4.2) 2nd
Full Text of BlanksApplet.html (4.6) 2nd
Full Text of BlanksApplet.java (4.5) 2nd
Full Text of CableModem.java (10.3)
Full Text of ClockFrame.java (13.4) 2nd
Full Text of ClockPanel.java (13.3) 2nd 3rd 4th
Full Text of ColorSlide.java (16.2) 2nd 3rd 4th 5th
Full Text of Crisis.java (14.1) 2nd 3rd
Full Text of Danger.java (22.2) 2nd
Full Text of DangerFrame.java (22.3) 2nd
Full Text of DivideNumbers.java (18.3) 2nd
Full Text of DslModem.java (10.4)
Full Text of FindPrimes.java (19.1) 2nd 3rd
Full Text of HomePage.java (18.4) 2nd 3rd
Full Text of ItemProp.java (B.4)
Full Text of KeyView.java (15.1) 2nd
Full Text of lotto.log (25.2) 2nd
Full Text of LottoClient.java (25.4) 2nd 3rd
Full Text of LottoCounter.java (25.1) 2nd 3rd 4th
Full Text of LottoEvent.java (15.2) 2nd 3rd 4th 5th 6th
Full Text of LottoEvent.java (25.5) 2nd 3rd 4th 5th 6th 7th
Full Text of LottoMadness,jnlp (17.5) 2nd 3rd 4th 5th 6th
Full Text of LottoMadness.java (14.2) 2nd 3rd 4th 5th 6th
Full Text of LottoMadness.java (15.3) 2nd 3rd 4th
Full Text of LottoServer.java (25.3) 2nd 3rd
Full Text of Modem.java (10.2)
Full Text of NewRoot.java (10.1) 2nd
Full Text of NewSumNumbers,java (18.2) 2nd
Full Text of Nines.java (8.1) 2nd 3rd
Full Text of NoSpaces.java (9.1) 2nd
Full Text of PageCatalog.java (18.5) 2nd 3rd
Full Text of PieApplet.html (23.4)
Full Text of PieApplet.java (23.3) 2nd 3rd
Full Text of PiePanel.java (23.2) 2nd 3rd
Full Text of Playback.java (13.2) 2nd
Full Text of Player.java (22.1) 2nd 3rd
Full Text of Point3D.java (12.2) 2nd
Full Text of properties.xml (21.2) 2nd 3rd 4th
possible document type declaration (dtd) error
Full Text of PropertyFileCreator.java (21.1) 2nd
Full Text of PropertyFileReader.java (21.3) 2nd 3rd
Full Text of ReadConsole.java (20.2) 2nd 3rd
Full Text of ReadID3.java (20.1) 2nd 3rd
Full Text of Revolve.java (19.2) 2nd 3rd
Full Text of Root,java (4.1)
Full Text of SalutonApplet.html (17.2) 2nd
Full Text of SalutonApplet.java (17.1) 2nd
Full Text of SalutonFrame.java (13.1) 2nd
Full Text of ShowWeight.html (17.4)
Full Text of ShowWeight.java (17.3) 2nd 3rd
Full Text of Sign.java (23.1) 2nd 3rd
Full Text of StringLister.java (12.1) 2nd 3rd
Full Text of SumNumbers,java (18.1) 2nd 3rd
Full Text of Tag Cleaner.java (20.6) 2nd 3rd 4th 5th
Full Text of TestModem.java (10.5) 2nd 3rd
Full Text of Tool.java (16.3) 2nd
Full Text of TryPoints.java (12.3) 2nd 3rd
Full Text of Virus.java (11.1) 2nd
Full Text of VirusLook.java (11.2) 2nd 3rd
Full Text of WriteMail.java (16.1) 2nd 3rd
Game Program (7.1) 2nd
Line-by-Line Breakdown of the Saluton Program (2.3)
Output of the Credits Program (6.2)
Output of the Elvis Program (5.3) 2nd 3rd
Output of the Game Program (7.2) 2nd
Output of the Wheel Program (9.3) 2nd 3rd
Output of the Wheel Program (9.4)
Partial Source Code of HelloUser.java (C.1) 2nd
RootApplet.html (4.4) 2nd
RootApplet.java (4.3) 2nd
Saluton Program, The (2.1) 2nd
Source Code of HelloUser.java (A.1) 2nd 3rd
Variable Program (5.1)
lists
choice lists
event handling 2nd
loading
applets
troubleshooting
graphics
images 2nd 3rd
locals command (jdb)
logic errors 2nd
operators
logos
animating 2nd 3rd 4th
long variable type
values
looping through vectors 2nd 3rd 4th
loops
definition of 2nd
do-while 2nd 3rd 4th 5th
exiting 2nd
for 2nd 3rd 4th 5th 6th
complex for loops 2nd
counter variables 2nd
empty sections
multiple statement sections
sample application 2nd 3rd 4th
syntax 2nd 3rd
infinite loops
naming 2nd
nesting
Repeat application
compiling
running
source code 2nd 3rd
while 2nd
LottoClient class (XML-RPC)
execute() method 2nd 3rd
Full Text of LottoClient.java (Listing 25.4) 2nd 3rd
sendResult() method 2nd 3rd
LottoCounter class
XML-RPC call handling 2nd 3rd 4th 5th 6th
LottoEvent class
Full Text of LottoEvent.java (Listing 25.5) 2nd 3rd 4th 5th 6th 7th
LottoMadness application 2nd 3rd 4th 5th 6th 7th 8th
applet version
event listeners
Java Web Start 2nd 3rd 4th 5th
listings
Full Text of lotto.log (25.2) 2nd
Full Text of LottoClient.java (25.4) 2nd 3rd 4th
Full Text of LottoCounter.java (25.1) 2nd 3rd 4th
Full Text of LottoEvent.java (25.5) 2nd 3rd 4th 5th 6th 7th
Full Text of LottoServer.java (25.3) 2nd 3rd 4th
LottoEvent.java class
methods
actionPerformed()
addOneToField()
clearAllFields()
getActionCommand()
itemStateChanged()
matchedOne()
numberGone()
LottoMadness() method
LottoServer class (XML-RPC) 2nd 3rd
addHandler() method
Full Text of LottoServer.java (Listing 25.3) 2nd 3rd
sendRequest() method
lowercase
changing strings to 2nd

Previous Section < Day Day Up >


index_M

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

magazines
JavaWorld 2nd 3rd
main() blocks
Saluton program
main() method
MalformedURLException errors
managers [See layout managers]
matchedOne() method
MD command (MS-DOS) 2nd
memory command (jdb)
memory errors
menus
creating 2nd 3rd 4th 5th
JMenu component 2nd 3rd
JMenuBar component 2nd 3rd
JMenuItem component 2nd
methods 2nd 3rd 4th
actionPerformed() 2nd 3rd 4th 5th 6th 7th
add()
addActionListener()
addChangeListener()
addItemListener() 2nd
addKeyListener()
addOneToField()
addSlice()
arguments 2nd
checkAuthor()
class methods
declaring 2nd
clearAllFields()
close()
closePath()
constructors 2nd
arguments
declaring
inheritance
createNewFile()
currentThread()
declaring
definition of
destroy()
displaySpeed() 2nd
draw()
drawImage() 2nd
drawRoundRect()
drawString() 2nd 3rd 4th
equals() 2nd
exists()
fill()
fillRect()
fillRoundRect()
floatValue()
getActionCommand() 2nd
getAppletInfo() 2nd 3rd
getCodeBase()
getImage()
getInsets()
getKeyChar()
getKeyCode()
getKeyText()
getName()
getParameter() 2nd
getParameterInfo()
getSeconds()
getSource() 2nd
getStateChange()
getTimeZone()
getURL()
getValueIsAdjusting()
getVirusCount()
GridLayout()
ImageIcon()
indexOf() 2nd 3rd
infectFile()
init() 2nd 3rd 4th
init() blocks
itemStateChanged() 2nd
JScrollPane()
JSlider()
JToolBar()
Label()
length() 2nd
lineTo()
listFiles()
LottoMadness()
main()
main() blocks
Saluton program
matchedOne()
moveTo()
numberGone()
overriding 2nd 3rd 4th
paint() 2nd 3rd 4th
overriding 2nd
paint() blocks
paintComponent() 2nd 3rd
parseInt() 2nd 3rd
println() 2nd 3rd 4th 5th 6th
public
read()
readLine() 2nd
renameTo()
repaint() 2nd 3rd
return values 2nd
roll()
run() 2nd 3rd 4th 5th
setBackground() 2nd
setColor() 2nd
setDefault() 2nd
setDefaultCloseOperation()
setEditable() 2nd
setEnabled()
setFont() 2nd
setForeground()
setLayout() 2nd
setSeconds()
setSize()
setStroke()
setText()
setTitle()
showDocument()
showVirusCount()
sin()
skip()
sleep() 2nd
sort()
start() 2nd 3rd 4th
calling
stateChanged()
stop() 2nd 3rd 4th 5th
calling
stringWidth()
substring()
tauntUser()
TextArea()
toCharArray()
toLowerCase()
toUpperCase() 2nd
valueOf()
variable scope 2nd
void keyPressed()
void keyReleased()
void keyTyped()
write()
methods command (jdb)
minus sign (-)
decrement operator (--)
subtraction operator
MMORPGs
(massively multiplayer online role-playing games) 2nd
Modem class
Modem objects
modulus operator (%)
Monitor objects
monitors
color substitutions
mouse clicks
handling 2nd
moveTo() method
MS-DOS
CLASSPATH variable
Windows 98/Me, setting in (JDK) 2nd 3rd
Windows NT/2000/XP, setting in (JDK) 2nd 3rd
commands
CD 2nd
MD 2nd
doskey command
folders
creating (JDK) 2nd
opening (JDK) 2nd
programs
executing (JDK) 2nd 3rd
MS-DOS prompt (JDK)
multidimensional arrays
declaring 2nd
multiple files
compiling
multiplication operator (*)
multithreading 2nd 3rd [See also threads]
Nasa J-Track applet example
Zsee also threaded applets
MySQL and JSP Web Applications
Data-Driven Programming Using Tomcat and MySQL

Previous Section < Day Day Up >


index_N

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

Name application
output 2nd
NAME attribute
PARAM tag
names
file extensions
.class
naming conventions
loops 2nd
parameters
variables 2nd 3rd
NASA J-Track applet website 2nd
multithreading uses
navigational components [See components]
Navigator
configuring
Java Plug-in
downloading
nesting
classes 2nd 3rd 4th
loops
NetBeans
development tools
installing 2nd
graphical user interface
hardware requirement
Installation Wizard
running 2nd
Java24.com resources
launching
listings
Partial Source Code of HelloUser.java (C.1) 2nd
Macintosh version
platform support
programs
compiling 2nd
sample program
creating 2nd 3rd 4th 5th
software configuration
NetRexx language
Netscape Navigator
configuring
Java Plug-in
downloading
new statement 2nd
newline character
newline characters
escape codes
NewRoot application 2nd
news aggregators
RSS syndication feeds
newsgroups
Google Groups 2nd
NewsGuy 2nd
NewsGuy website
newsgroup resources 2nd
Nines application
output 2nd
source code 2nd
NoSpaces application 2nd
Notepad
programs
writing source code in 2nd
writing features for programs
NumberFormatException errors
numberGone() method
numbering
array elements 2nd
numbers
prime numbers, displaying sequence of 2nd 3rd 4th

Previous Section < Day Day Up >


index_O

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

Oak language
forerunner of Java name
OBJECT tag (HTML)
CODEBASE attribute
object variables
declaring 2nd 3rd
object-oriented programming [See OOP]
objects [See also classes]
attributes 2nd
autoboxing 2nd 3rd 4th
behavior
casting 2nd
classes
converting 2nd
converting to variables 2nd 3rd
creating 2nd 3rd 4th 5th 6th 7th
inheritance 2nd 3rd 4th 5th 6th 7th 8th
establishing
hierarchy 2nd
Modem
Monitor
PieChart
referencing
this statement 2nd
sharing 2nd
storing (Vector class) 2nd 3rd
TimeZone
creating
unboxing 2nd 3rd 4th
variables
private
protected
offline-allowed tag (JNL)
OOP 2nd 3rd [See also classes]
(object-oriented programming) 2nd
advantages 2nd 3rd
applications
debugging
debugging
encapsulation
inheritance 2nd 3rd 4th 5th 6th 7th 8th 9th
establishing
hierarchy 2nd
objects [See objects]
casting 2nd
converting 2nd
creating 2nd 3rd 4th 5th 6th 7th
opening
folders
MS-DOS (JDK) 2nd
MS-DOS folders in JDK 2nd
operators 2nd
+= 2nd
==
addition (+)
concatenation (+) 2nd 3rd
decrement (--)
division (/)
equality (==)
greater than () 2nd
inequality (!=)
less than (<) 2nd 3rd
logic errors
modulus (%)
multiplication (*)
precedence 2nd 3rd
subtraction (-)
ternary (?) 2nd
Oracle and Java Development
order of precedence
operators 2nd 3rd
organizing
applications
block statements 2nd 3rd
Output of the Credits Program (Listing 6.2)
Output of the Elvis Program (Listing 5.3) 2nd 3rd
Output of the Game Program (Listing 7.2) 2nd
Output of the Wheel Program (Listing 9.3) 2nd 3rd
Output of the Wheel Program (Listing 9.4)
overriding
methods 2nd 3rd 4th

Previous Section < Day Day Up >


index_P

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

P tag (HTML)
packages
classes
creating
Page Source command (View menu)
PageCatalog application 2nd 3rd
pageTitle array
paint() block statements
paint() method 2nd 3rd 4th 5th
overriding 2nd
paintComponent() method 2nd 3rd
panels
creating 2nd
PARAM tag (HTML) 2nd 3rd 4th
NAME attribute 2nd
VALUE attribute
parameters
handling
ShowWeight applet 2nd
naming
passing
to applets 2nd 3rd
passing to applets
receiving 2nd
sending to applets
values
assigning
parseInt() method 2nd 3rd
Partial Source Code of HelloUser.java (C.1) 2nd
passing
arguments
to methods 2nd
parameters
to applets 2nd 3rd 4th
pasting
into strings 2nd
strings together 2nd
pausing
animation
applications
percent sign (%)
modulus operator
period (.)
Peter Principle
Piano Web site
pie graphs, creating 2nd
PieApplet.java 2nd 3rd 4th
PiePanel.java source code 2nd
PieSlice class 2nd
PieApplet.java (Listing 23.3) 2nd 3rd
PieChart object
PiePanel application 2nd
PieApplet.java 2nd 3rd 4th
PiePanel.java source code 2nd
PieSlice class 2nd
PiePanel.java source code 2nd
PieSlice class 2nd
PLAIN style (fonts)
platform independence
platforms
JDK support
NetBeans support
XML-RPC support
plug-ins
definition of
Java Plug-in
downloading
plus sign (+)
addition operator
concatenation operator 2nd 3rd
increment operator (++)
Point class
point sizes
limitations
specifying
Point3D class
creating 2nd
testing 2nd
polygons
drawing 2nd
Population Research Bureau website
postfixing
precedence
operators 2nd 3rd
prefixing
prime numbers, displaying sequence of 2nd 3rd 4th
print command (jdb)
printing
strings
println() method 2nd
special character 2nd
println() method 2nd 3rd 4th 5th 6th
private classes
private variables
procedures
System.out.println() (Elvis program)
programming languages
BASIC
bugs
C++
compilers
function of 2nd
errors
blame for
interpreted types
interpreters
function of
Liberty BASIC
interpreter
programs
saving
selecting 2nd 3rd
statements
definition of
role of 2nd
syntax errors 2nd
text editors
writing in
versus Java 2nd 3rd
Visual Basic 2nd
programs [See applications]
compiling (javac) 2nd
compiling (NetBeans) 2nd
configuration properties
reading 2nd 3rd
writing 2nd 3rd
debugging
debugging (javac tool)
development tools
installing
Java [See Java programs]
java filename extension
MS-DOS
executing (JDK) 2nd 3rd
NetBeans
creating 2nd 3rd 4th 5th
Revolve
threads
security measures 2nd 3rd
software [See applications]
syntax
blank space issue
windowing programs
word processors
selecting
writing with text editors 2nd
{} (braces) syntax usage
programs (Java)
developing
properties
system properties
ediing (JDK) 2nd 3rd 4th
protected variables
protocols
JNLP (Java Network Launching Protocol) 2nd 3rd 4th 5th
Public Java 2 Runtime Environment (JRE)
public methods
public statements
public variables
declaring

Previous Section < Day Day Up >


index_Q

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

question mark (?)
ternary operator 2nd
quotation marks
double (")
escape codes
single (')

Previous Section < Day Day Up >


index_R

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

read() method
ReadConsole application 2nd
ReadID3 application 2nd
reading
configuration properties
in programs 2nd 3rd
files
read() method
ReadID3 application 2nd 3rd 4th 5th
skip() method
RSS syndication feeds 2nd 3rd 4th
streams
buffered input streams
XML files 2nd 3rd 4th 5th 6th
readLine() method 2nd
real-world Java projects
AlphaTrade.com 2nd 3rd
Gamelan website 2nd 3rd
JavaWorld Magazine Website 2nd 3rd
NASA J-Track applet 2nd
Visible Human Project Website 2nd
Wurm Online 2nd
Rectangle2D class 2nd
rectangles
drawing 2nd
Red, Green Blue (RGB) color system 2nd 3rd
referencing
classes
objects
this statement 2nd
registering
objects as change listeners 2nd
Reload command (Applet menu)
renameTo() method
renaming
files
repaint() method 2nd 3rd
Repeat application
compiling
running
source code 2nd 3rd
resource
websites
Gamelan.com
resources [See also websites]
chat rooms
Internet Relay Chat (IRC)
Undernet.org 2nd
Java 2 class documentation
Java books
Java Users Groups (Sun Microsystems website)
Java24Hours.com
job opportunities
CareerBuilder
Sun Microsystems
newsgroups
Google Groups 2nd
NewsGuy 2nd
Oracle and Java Development
Sams Teach Yourself Java 2 in 21 Days
websites
iBiolio.org
InformIT
JARS (Java Review Service)
Java.com
Java.net
Java24Hours.com 2nd
JavaWorld Magazine
Sun Microsystem Java
resources tag (JNL)
resourcesSams Teach Yourself Java 2 in 21 Days, Fourth Edition
Restart command (Applet menu)
restricting access [See access control]
return values (methods) 2nd
reusable object [See JavaBeans]
Revolve applet 2nd
class declaration 2nd
error handling 2nd
event handling 2nd
HTML markup 2nd
methods
actionPerformed() 2nd
init() 2nd
paint()
run() 2nd
start() 2nd
stop() 2nd
screen updates 2nd
source code 2nd
threads
running 2nd
starting 2nd
stopping 2nd
variables 2nd
Revolve class
creating
RGB values
(red, green, blue) 2nd 3rd
RMI (Remote Method Invocation)
versus XML-RPC 2nd
roll() method
Root application
compiling 2nd
Root application (Listing 4.1)
RootApplet applet
HTML file 2nd
parameters
source code
rounded rectangles
drawing
RSS Advisory Board website
RSS syndication feeds
news aggregators
reading 2nd 3rd 4th
run command (jdb)
Run command (Start menu)
run() method 2nd 3rd 4th 5th
Runnable interface
running
applications 2nd
Credits
Repeat
via interpreter
Java programs
in Windows 2nd 3rd
Saluton program 2nd
threads 2nd
running applications
Java Web Start 2nd 3rd 4th 5th 6th 7th 8th

Previous Section < Day Day Up >


index_S

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

Saluton application
(Hello World!)
class declaration
class statement
compiling (javac tool) 2nd
debugging 2nd 3rd
Esperanto language-inspired
final source code
initial source code 2nd
main() block
running 2nd
saving 2nd
variables
declaring 2nd
displaying
displaying contents of 2nd
Saluton Program, The (Listing 2.1) 2nd
SalutonApplet applet
displaying 2nd
HTML markup
APPLET tag
testing 2nd
SalutonFrame.java 2nd 3rd 4th
Sams Publishing website
Sams Teach Yourself J2EE in 21 Days
Sams Teach Yourself Java 2 in 21 Days
Sams Teach Yourself Java 2 in 21 Days, Fourth Edition
Sams Teach Yourself Java 2 in 21 Days, Fourth Edition
saving
programs
.java file extension
Saluton program 2nd
scope (variables) 2nd
screens
updating
forced updates
paint() method 2nd
repaint() method
scroll panes
adding components to
creating 2nd
WriteMail sample application 2nd
SDK
versus JDK terminology
SDK 2
utilities
appletviewer browser 2nd
javadoc documentation tool 2nd
jdb debugger 2nd 3rd 4th 5th
SDK utilities
jdb
commands 2nd
security
digital signatures
Java programs 2nd 3rd
Java Web Start 2nd
trusted developers
viruses
selecting
development tools 2nd
programming languages
for applications 2nd 3rd
word processors
for program writing
semi-colon (
)
program syntax
semicolon
semicolon (
)
program syntax
semicolon () 2nd
sending
arguments
to applications 2nd 3rd
parameters
to applets
sendRequest() method
LottoServer class (XML-RPC)
sendResult() method
LottoClient class 2nd 3rd
servers
XML-RPC
creating 2nd 3rd 4th 5th 6th
setBackground() method 2nd
setColor() method 2nd
setDefault() method 2nd
setDefaultCloseOperation() method
setEditable() method 2nd
setEnabled() method
setFont() method 2nd
setForeground() method
setLayout() method 2nd
setSeconds() method
setSize() method
setStroke() method
setText() method
setting
breakpoints
JDK
PATH variable 2nd 3rd
PATH variable (Windows NT/2000/XP) 2nd 3rd
setTitle() method
shapes
arcs 2nd
circles
ellipses
lines 2nd
lines of different widths 2nd
PiePanel application 2nd
PieApplet.java 2nd 3rd 4th
PiePanel.java source code 2nd
PieSlice class 2nd
polygons 2nd
rectangles 2nd
sharing
objects 2nd
short variable type
showDocument() method
showVirusCount() method
ShowWeight applet
HTML markup 2nd
output
source code 2nd 3rd
signatures (digital)
Simple Text
programs
writing source code in 2nd
sin() method
single quotation marks (')
escape code
single-step execution
jdb debugger 2nd 3rd
sizing
applet windows 2nd
skip() method
slashes (//)
program syntax
sleep() method 2nd
sliders 2nd
creating 2nd 3rd 4th
labels
slowing down threads 2nd
software
function of 2nd
windowing software
word processors
choosing
sort() method
sorting
arrays 2nd 3rd 4th 5th 6th
source code
blank spaces
comments
converting (javac compiler) 2nd 3rd 4th
web pages
viewing
Source Code component (JDK)
Source Code of HelloUser.java (Listing A.1) 2nd 3rd
Source command (View menu)
source files
creating 2nd 3rd
sources (casting)
spacing in source code
special characters
escape codes 2nd
specifying
class files
speed
Java programs
square brackets ([ ])
SRC attribute (IMG tag)
sRGB (Standard RBG)
stack frames
stack overflows
stacks
Standard RGB (sRGB)
Start command (Applet menu)
Start menu
commands
Run
start() method 2nd 3rd 4th
calling
starting
applets 2nd
threads 2nd
starting values
(variables)
stateChanged() method
statements 2nd 3rd [See also conditionals]
assert 2nd 3rd 4th
blocks 2nd 3rd 4th 5th 6th
braces ({}) notation
break 2nd 3rd
case
catch
class 2nd 3rd
compared to lines
conditionals
if
continue
default
definition of
expressions 2nd 3rd 4th
advantages 2nd
extends 2nd
float
if 2nd 3rd 4th
blocks 2nd 3rd
equal/not equal comparisons 2nd
less/greater than comparisons 2nd
if-else 2nd
import 2nd 3rd
init()
int
loops
definition of 2nd
do-while 2nd 3rd 4th 5th
exiting 2nd
for 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th
infinite loops
naming 2nd
nesting
while 2nd
new 2nd
paint()
public
role of 2nd
static 2nd
super
class declarations 2nd
switch 2nd
this 2nd 3rd
class declarations
throw
try-catch 2nd
try-catch blocks
catching exceptions 2nd 3rd 4th 5th 6th 7th 8th
try-catch-finally blocks 2nd
void
static statement 2nd
step command (jdb)
stop at command (jdb) 2nd
Stop command (Applet menu)
stop in command (jdb)
stop() method 2nd 3rd 4th 5th
calling
stopping
applets 2nd
threads 2nd
storing
data in variables 2nd 3rd
images 2nd
objects
in Vector class 2nd 3rd
text in strings 2nd 3rd
streams 2nd 3rd
buffered input streams 2nd 3rd 4th
creating
ReadConsole application 2nd
reading
byte streams
closing
defined 2nd
reading data from
read() method
ReadID3 application 2nd 3rd 4th 5th
skip() method
writing to 2nd 3rd
String data type
strings 2nd 3rd
adding to 2nd
arrays
casting
changing case of 2nd 3rd
comparing 2nd 3rd
equal/not equal comparisons 2nd
less/greater than comparisons 2nd
concatenating 2nd
converting to floating-point numbers
definition of 2nd
determining length of 2nd
displaying
println() method 2nd
special characters 2nd
empty
finding within other strings 2nd
text
adding
storing in 2nd 3rd
variables 2nd
declaring
linking 2nd
stringWidth() method
Stroustrop, Bjarne
C++ development
subclasses
creating 2nd 3rd 4th 5th 6th 7th
substring() method
subtraction operator (-)
Sun Microsystem Java website
Sun Microsystems Java website
Java history
JDK downloads 2nd
Sun Microsystems website
Java Users Groups listing
Sun Website 2nd
Sun website
Java documentation page
Java documentation resources
JDK downloads
Sun Website
sample applets
sample programs
super statement
class declarations 2nd
superclasses
creating
multiple
suspend command (jdb)
Swing 2nd 3rd 4th
buttons
creating 2nd 3rd
change listeners
ColorSlide sample application 2nd
registering objects as 2nd
check boxes
creating 2nd
event handling 2nd
combo boxes
creating 2nd 3rd
event handling 2nd
documentation
enabling/disabling components 2nd
event listeners 2nd
ActionListener interface
actionPerformed() method 2nd
adding
LottoMadness application 2nd
image icons 2nd 3rd 4th
creating 2nd 3rd
Tool sample application
JApplet class
labels
creating 2nd
layout managers
BorderLayout 2nd 3rd
BoxLayout 2nd
FlowLayout 2nd 3rd 4th
GridLayout 2nd 3rd
LottoMadness sample application 2nd 3rd 4th 5th 6th
menus
creating 2nd 3rd 4th 5th
JMenu component 2nd 3rd
JMenuBar component 2nd 3rd
JMenuItem component 2nd
panels
creating 2nd
scroll panes
adding components to
creating 2nd
WriteMail sample application 2nd
sliders 2nd
creating 2nd 3rd 4th
labels
text areas
creating
text fields
creating 2nd
write protecting
toolbars 2nd 3rd 4th
creating 2nd 3rd
dockable toolbars
Tool sample application
Swing interface tool (Java)
switch statements 2nd
syntax errors in programming
system properties
editing (JDK) 2nd 3rd 4th
System.out.println() procedure (Elvis program)
System.out.println() statement

Previous Section < Day Day Up >


index_T

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

tabs
escape code
Tag command (Applet menu)
TagCleaner application
web pages
cleaning 2nd 3rd 4th 5th 6th
tags
(angle brackets)
(HTML)
APPLET 2nd
ALIGN attribute
ARCHIVE attribute
CODE attribute
CODEBASE attribute 2nd
HEIGHT attribute
WIDTH attribute
APPLET (HTML)
CENTER
HTML
PARAM 2nd
IMG
SRC attribute
javadoc 2nd 3rd 4th
@author
@deprecated
@exception
@param
@return
@see
@serial
@since
@version
OBJECT
CODEBASE attribute
P
PARAM 2nd 3rd 4th
NAME attribute 2nd
VALUE attribute
web pages
cleaning up (TagCleaner) 2nd 3rd 4th 5th 6th
tags (JNLP)
homepage
information
jnlp
offline-allowed
resources
title
vendor
tauntUser() method
ternary operator (?) 2nd
testing
applets
Points3D class 2nd 3rd
SalutonApplet applet 2nd
text [See also strings]
fonts
displaying 2nd
specifying 2nd 3rd 4th
pasting into strings 2nd 3rd
point sizes
limitations
strings
storing in 2nd 3rd
text areas
creating
text editors
choosing 2nd 3rd 4th 5th
jEdit
programming writing features
programs
writing via 2nd
UltraEdit
Windows Notepad 2nd
Windows WordPad 2nd
text fields
creating 2nd
write-protecting
TextArea() constructor method
this statement 2nd 3rd
class declarations
Thread class
threaded applets 2nd
class declarations 2nd
error handling 2nd
event handling 2nd
initializing 2nd
screen updates 2nd
threads
running 2nd
starting 2nd
stopping 2nd
variables 2nd
threaded classes 2nd 3rd 4th 5th
threads 2nd [See also threaded applets]
animation programs
creating 2nd 3rd 4th 5th
multithreading
Runnable interface
running 2nd
slowing down 2nd
starting 2nd
stopping 2nd
Thread class
threads command (jdb)
throw statements
throwing exceptions 2nd 3rd
PageCatalog sample application 2nd 3rd
throw statements
time, displaying
ClockFrame application 2nd
ClockPanel application 2nd 3rd
TimeZone object
creating
title tag (JNL)
titles
frames
toCharArray() method
Tolksdorf, Robert
toLowerCase() method
Tool application
toolbars 2nd 3rd 4th
creating 2nd 3rd
dockable toolbars
Tool sample application
tools
appletviewer
development
selecting 2nd
functions
modifying (JDK)
totalPicture integer variable
toUpperCase() method 2nd
troubleshooting [See also debugging]
applets
loading errors
JDK configuration errors 2nd
JDK installations
trusted developers
try-catch blocks
catching exceptions 2nd 3rd 4th 5th 6th 7th 8th
DivideNumbers sample application 2nd
SumNumbers sample application 2nd 3rd 4th 5th
try-catch statement 2nd
try-catch-finally blocks 2nd
tuned quicksorts (arrays)
type values (variables)
casting
types
boolean 2nd 3rd
byte
char 2nd 3rd
long 2nd
short

Previous Section < Day Day Up >


index_U

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

U.S. Census Bureau website
UltraEdit text editor
Undernet.org
chat rooms 2nd
underscore (_)
up command (jdb)
updating
screen
paint() method 2nd
repaint() method
updating screens
forced updates
upper limits of arrays
checking
uppercase
changing strings to 2nd 3rd
Usenet newsgroups
Java resources 2nd
utilities
appletviewer (JDK)
AppInfo sample application 2nd 3rd 4th 5th
Applet menu commands 2nd
appletviewer browser (JDK)
command line
options (JDK) 2nd
command line (JDK)
jar (JDK) 2nd 3rd 4th
java interpreter (JDK) 2nd 3rd 4th
javac compiler (JDK) 2nd 3rd 4th
javadoc
AppInfo2 sample application
tags 2nd 3rd 4th
javadoc (JDK) 2nd 3rd 4th 5th 6th
jdb
commands 2nd
jdb debugger
applet debugging 2nd
application debugging
breakpoints 2nd 3rd
commands 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th
jdb debugger (JDK)
application debugging
breakpoints
single-step execution 2nd 3rd

Previous Section < Day Day Up >


index_V

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

valueOf() method
Variable application
code listing
compiling
int statement
variables
characters 2nd
declaring
floating-point 2nd
integers 2nd
strings 2nd
Variable Program (Listing 5.1)
variables
access control
arrays 2nd 3rd
declaring
definition of
elements
initial values 2nd
multidimensional 2nd
ranges
sample application 2nd
sorting 2nd 3rd 4th 5th 6th
assigning values
storing 2nd 3rd
casting 2nd 3rd
CLASSPATH
Windows 98/Me, setting (JDK) 2nd 3rd
Windows NT/2000/XP, setting (JDK) 2nd 3rd
converting to objects 2nd 3rd
counter variables
definition of
initializing
data types
String
declaring 2nd 3rd 4th
class variables 2nd
object variables 2nd
definition of
displaying contents of 2nd
environment
initializing
definition of
length 2nd
naming conventions 2nd 3rd
case-sensitivity
PATH
Windows 9x/Me 2nd 3rd
Windows NT/2000/XP 2nd 3rd
private
protected
public
referencing
this statement 2nd
Revolve applet
Revolve program
scope 2nd
strings 2nd
casting
changing case 2nd 3rd
comparing 2nd
concatenating 2nd
declaring
determining length 2nd
displaying 2nd
empty
escape codes 2nd
linking 2nd
types
assigning 2nd
boolean 2nd 3rd
byte
char 2nd 3rd
floating-point
integers
long 2nd
short
strings 2nd
values
assigning
decrementing 2nd 3rd 4th
incrementing 2nd 3rd 4th
starting values
Vector class
objects
storing 2nd 3rd
vectors
looping through 2nd 3rd 4th
vendor tag (JNL)
verbose option (javac)
VeriSign Website
vertical sliders
creating
vi editor
writing features for programs
vi text editor
programs
writing source code in 2nd
View menu commands
Page Source
Source
viewing
documents
HTML
Virus application
class constructor
methods
getSeconds()
infectFile()
setSeconds()
tauntUser()
showVirusCount()
source code 2nd
Virus class
viruses
Java program transmissions
VirusLook application
output
source code 2nd
testing
Visible Human Project website
Java viewer 2nd
Visual Basic 2nd
void keyPressed() method
void keyReleased() method
void keyTyped() method
void statement

Previous Section < Day Day Up >


index_W

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

WarGames
web browsers
Java interpreters
support for
Java Plug-in
Java plug-in
downloading
Java program execution
web pages
source code
viewing
tags
cleaning up (TagCleaner) 2nd 3rd 4th 5th 6th
web services
Web sites
array sorting technique demo
Gamelan
iBiolio.org
InformIT
JARS (Java Review Service)
Java Plug-in
Java Web Start
JavaWorld Magazine
Workbench
Web Start 2nd
capabilities 2nd
JNLP (Java Network Launching Protocol) files 2nd 3rd 4th 5th
LottoMadness example 2nd 3rd 4th 5th
running applications with 2nd 3rd 4th 5th 6th 7th 8th
security 2nd
Web site
WebServer class (XML_RPC)
Websites
AlphaTrade.com 2nd 3rd
websites
Apache.org
Apple Developer
NetBeans downloads
Babelfish
language translation features
Bart Simpson Chalkboard Punishments
Cafeconleche.org
CareerBuilder.com
CE-Mark.com
chat room resources
Undernet.org 2nd
Websites
Gamelan
Java Applet Ratings Service (JARS) 2nd
websites
Hexadecimal Hues
IANA (Internet Assigned Numbers Authority)
Inflation Calculator
InformIT
International Components for Unicode for Java
Internet Movie Database
Java Applet Ratings Service (JARS)
Java on the Brain
Java.com
Java.net
Java24.com
NetBeans resources
Java24Hours.com
applet resources 2nd
features
troubleshooting resources
XML-RPC resources
Websites
JavaWorld Magazine 2nd 3rd
websites
Liberty BASIC interpreter
NASA J-Track applet 2nd
Piano, The
Population Research Bureau
RSS Advisory Board
Sams Publishing
Websites
Sun 2nd
websites
Sun
Java documentation
Java documentation resources
JDK downloads
Websites
Sun
sample applets
websites
Sun Microsystem Java site
Sun Microsystems Java
Java history
JDK downloads
U.S. Census Bureau
Websites
VeriSign
websites
Visible Humand Project
Java viewer 2nd
Websites
Wurm Online 2nd
websites
XMLRPC.com
well-formed data (XML)
Wheel of Fortune application 2nd
character arrays
integer arrays
letterCount array
nested loops
output
source code 2nd
string arrays
Wheel of Fortune program
while loops 2nd
exiting 2nd
WIDTH attribute (APPLET tag)
windowing software
windows 2nd 3rd 4th 5th 6th 7th 8th 9th
Windows 98/Me
CLASSPATH variable
setting (JDK) 2nd 3rd
Windows 9x/Me
PATH variable
setting (JDK) 2nd 3rd
Windows Notepad
text editor feaures 2nd
Windows NT/2000/XP
CLASSPATH variable
setting (JDK) 2nd 3rd
PATH variable
setting (JDK) 2nd 3rd
Windows OS
Java programs
compiling in 2nd 3rd
running in 2nd 3rd
JDK
configuring on 2nd 3rd 4th
installing on 2nd 3rd
NetBeans
software configuration
Windows WordPad
text editor feaures 2nd
wizards
NetBeans Installation Wizard
running 2nd
word processors [See text editors]
programs
writing in 2nd
selecting for program writing
WordPad
programs
writing source code in 2nd
Workbench Web site
write protecting
text fields
write() method
WriteMail application 2nd
writing
configuration properties
in programs 2nd 3rd
writing to
files
streams 2nd 3rd
streams 2nd 3rd
Wurm Online website 2nd

Previous Section < Day Day Up >


index_X

Index

[SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X]

XML
(Extensible Markup Language)
Builder class
DOCTYPE statement
Element class
methods
libraries
downloading (CafeConLeche.org)
listings
Full Text of Aggregator.java (21.4) 2nd 3rd
RSS syndication feeds
dialect resources
reading 2nd 3rd 4th
XML (Extensible Markup Language)
XML files
creating 2nd 3rd 4th 5th 6th 7th
dialects
Full Text of properties.xml (Listing 21.2) 2nd 3rd 4th
Full Text of PropertyFileCreator.java (Listing 21.1) 2nd
indentation concerns
reading 2nd 3rd 4th 5th 6th
well-formed data
XML Remote Procedure Call [See XML-RPC]
XML-RPC [See also Apache XML-RPC]
(XML Remote Procedure Call)
clients
creating 2nd 3rd
LottoClient class 2nd 3rd
directory of supported platforms
handlers
creating 2nd 3rd 4th 5th 6th
Full Text of lotto.log (Listing 25.2) 2nd
Full Text of LottoCounter.java (Listing 25.1) 2nd 3rd 4th
Java24Hours.com resources
protocol functions
servers
creating 2nd 3rd 4th 5th 6th
LottoServer class 2nd 3rd 4th 5th 6th 7th 8th 9th
WebServer class 2nd
versus RMI (Remote Method Invocation) 2nd
voids as return types
XMLRPC.com
XOM (XML Object Model)
open source licensing

Previous Section < Day Day Up >