SAMS Teach YourselfProgramming with Java in 24Hours, FOURTH EDITIONTable of Contents Copyright About the Author Acknowledgments Reader Acknowledgements... What You Need to WriteProgramsC
Trang 2SAMS Teach Yourself
Programming with Java in 24Hours, FOURTH EDITIONTable of Contents
Copyright
About the Author
Acknowledgments
Reader Acknowledgements
Trang 3We Want to Hear from You!Reader Services
Trang 4How Programs Don't WorkNext Stop: Java
Workshop: Installing a JavaDevelopment Tool
Trang 5What You Need to WritePrograms
Creating the Saluton ProgramStoring Information in aVariable
Saving the Finished ProductCompiling the Program into aClass File
Fixing Errors
Workshop: Running a Java
Trang 6Watching the Skies at NASA
Trang 7Getting Down to BusinessStopping by Gamelan to AskDirections
Workshop: Venturing intoAnother World
Trang 8Java Programs Work
Summary
Q&A
Trang 9Naming Your Variables
Storing Information in Variables
Trang 10Workshop: Using ExpressionsAll about Operators
Storing Text in Strings
Displaying Strings in Programs
Trang 11Using Special Characters inStrings
Pasting Strings TogetherUsing Other Variables withStrings
Advanced String HandlingWorkshop: Presenting CreditsSummary
Q&A
Quiz
Trang 12The Conditional Operator
Workshop: Watching the ClockSummary
Trang 14Workshop: Teaching YourComputer a Lesson
Hour 9 Storing Information
Trang 15with Arrays
Creating Arrays
Using Arrays
Multidimensional ArraysSorting an Array
Workshop: Array of Prizes,Indeed
Summary
Q&A
Quiz
Trang 16Hierarchy
Trang 17Converting Objects and SimpleVariables
Workshop: Creating an ObjectSummary
Trang 18Creating Class VariablesCreating Behavior withMethods
Putting One Class insideAnother
Using the this KeywordWorkshop: Using ClassMethods and VariablesSummary
Q&A
Trang 19Workshop: Creating a Subclass
Trang 20Swing and the AbstractWindowing Toolkit
Trang 22Workshop: Laying Out anApplication
Trang 23Setting Up Components to BeHeard
Handling User Events
Workshop: A Little LottoMadness
Trang 25A Sample Applet
The Java Plug-in
Trang 26Sending Parameters from aWeb Page
Receiving Parameters in theApplet
Workshop: Handling
Parameters in an AppletJava Web Start
Using Java Web Start
Summary
Q&A
Trang 28Working with Threads
Starting with init()
Catching Errors as You Set UpURLs
Handling Screen Updates in the
Trang 29paint() Method
Starting the Thread
Handling Mouse Clicks
Workshop: Revolving LinksSummary
Trang 30Writing Data to a Stream
Reading and Writing
Trang 31Part VI: Creating MultimediaPrograms
Hour 21 Reading and WritingXML Data
Creating an XML File
Reading an XML File
Workshop: Reading RSSSyndication Feeds
Summary
Q&A
Trang 32Activities
Hour 22 Using Fonts and ColorUsing the Font Class
Using the Color Class
Other Ways to Choose ColorsWorkshop: Displaying a DangerMessage
Summary
Q&A
Trang 33Quiz
Trang 34Hour 24 Creating AnimationAnimating a Sequence ofImages
Sending Parameters to theApplet
Workshop: Follow the
Bouncing Ball
Summary
Q&A
Trang 35Activities
Part VII: Bonus
Hour 25 Creating Web
Services with XML-RPC
Working with Apache RPC
XML-Creating an XML-RPC HandlerCreating an XML-RPC ServerCreating an XML-RPC Client
Trang 36Workshop: Enhancing theLottoMadness ApplicationSummary
Q&A
Quiz
Activities
Part VIII: Appendixes
Appendix A Using the JavaDevelopment Kit
Choosing a Java Development
Trang 37Configuring the Java
Development Kit
Using a Text Editor
Creating a Sample ProgramSetting Up the CLASSPATHVariable
Appendix B Programming withthe Java Development Kit
An Overview of the JDK
Trang 38The java Interpreter
The javac Compiler
The appletviewer BrowserThe javadoc DocumentationTool
The jar Java File Archival ToolThe jdb Debugger
Using System Properties
Summary
Q&A
Trang 39Appendix C Using the
NetBeans Integrated
Development EnvironmentChoosing a Java DevelopmentTool
Creating a Sample ProgramAppendix D Where to Go fromHere: Java Resources
Other Books to Consider
Sun's Official Java Site
Trang 40Other Java Websites
Trang 41PARSER.JAR ARCHIVEFILES FROM JAVA API FORXML PARSING, VERSION1.0 SUPPLEMENTAL
LICENSE TERMS
JAVAHELP VERSION 2.0SUPPLEMENTAL LICENSETERMS
JAVA DEVELOPMENT
TOOLS JAVAC COMPILER
Trang 42SUPPLEMENTAL LICENSETERMS
JAVA INTERFACE CLASSESJ2EE DEPLOYMENT
SPECIFICATION
INTERFACE CLASSES 1.1SUPPLEMENTAL LICENSETERMS
JAVA 2, ENTERPRISE
EDITION (J2EE)
Trang 43MANAGEMENT, VERSION1.0 JAVA INTERFACE
CLASSES SUPPLEMENTALLICENSE TERMS
JAVA INTERFACE CLASSESENTERPRISE JAVABEANS,VERSION 2.0, INTERFACECLASSES SUPPLEMENTALLICENSE TERMS
JAVA OPTIONAL PACKAGE
Trang 44JMX, VERSION 1.2
SUPPLEMENTAL LICENSETERMS
J2EEeditor.jar
SUPPLEMENTAL LICENSETERMS
resolver-1_1_nb.jar Based onSun's XML Resolver 1.0Software License AgreementWhat's on the CD-ROM
Trang 45Windows InstallationInstructions
UNIX and UNIX-likeInstallation InstructionsIndex
Trang 46index_Eindex_Findex_Gindex_Hindex_Iindex_Jindex_Kindex_Lindex_Mindex_N
Trang 47index_Oindex_Pindex_Qindex_Rindex_Sindex_Tindex_Uindex_Vindex_Windex_X
Trang 48SAMS Teach Yourself Programming with Java™ in 24
Hours, FOURTH EDITION
Trang 49ISBN: 0-672-32844-5
Pages: 576
Table of Contents | Index
If you have been wanting to learn Java,check out the newly
Teach Yourself Programming with Java
in 24 Hours This step-by-step tutorial
create simple Java programs and applets.Comprised of 24 one-hour lessons, thisnew edition focuses on key programmingconcepts and essential Java basics, hasbeen improved
and is reorganized to better cover thelatest developments in Java The book's
Trang 50coverage of core Java programming topicshas also been expanded A great startingpoint
great primer to reading sams Teach
Yourself Java in 21 Days
SAMS Teach Yourself Programming with Java™ in 24
Hours, FOURTH EDITION
By Rogers Cadenhead
Trang 51Publisher: Sams
Pub Date: September 30, 2005
Trang 52We Want to Hear from You!Reader Services
Introduction
Part I Getting Started
Hour 1 Becoming a ProgrammerChoosing a Language
Telling the Computer What to DoHow Programs Work
How Programs Don't WorkNext Stop: Java
Trang 53Workshop: Installing a Java DevelopmentTool
Creating the Saluton Program
Storing Information in a Variable
Saving the Finished Product
Trang 54Compiling the Program into a Class FileFixing Errors
Workshop: Running a Java ProgramSummary
Q&A
Quiz
Activities
Hour 3 Vacationing in Java
First Stop: Sun Microsystems
Going to School with Java
Trang 55Lunch in JavaWorld
Watching the Skies at NASA
Getting Down to Business
Stopping by Gamelan to Ask DirectionsWorkshop: Venturing into Another WorldSummary
Trang 56Creating an Application
Sending Arguments to Applications
Applet Basics
Sending Parameters to Applets
Workshop: Viewing the Code Used to RunApplets
Summary
Q&A
Quiz
Trang 57Statements and Expressions
Assigning Variable Types
Naming Your Variables
Storing Information in Variables
Workshop: Using Expressions
Trang 58All about Operators
Displaying Strings in Programs
Using Special Characters in StringsPasting Strings Together
Trang 59Using Other Variables with Strings
Advanced String Handling
Workshop: Presenting Credits
Trang 60if Statements
if-else Statements
switch Statements
The Conditional Operator
Workshop: Watching the Clock
Trang 62Part III WORKING WITH
Trang 63Activities
Hour 10 Creating Your First Object
How Object-Oriented ProgrammingWorks
Objects in Action
What Objects Are
Understanding Inheritance
Building an Inheritance Hierarchy
Converting Objects and Simple VariablesWorkshop: Creating an Object
Trang 64Creating Class Variables
Creating Behavior with Methods
Putting One Class inside Another
Using the this Keyword
Trang 65Workshop: Using Class Methods andVariables
Trang 66Storing Objects of the Same Class inVectors
Workshop: Creating a Subclass
Trang 68Workshop: A Little Lotto MadnessSummary
Q&A
Trang 70Quiz
Activities
Part V Creating Multimedia Programs
Hour 17 Creating Interactive WebPrograms
Standard Applet Methods
Putting an Applet on a Web Page
A Sample Applet
The Java Plug-in
Sending Parameters from a Web Page
Trang 71Receiving Parameters in the Applet
Workshop: Handling Parameters in anApplet
Java Web Start
Using Java Web Start
Trang 72Working with Threads
Starting with init()
Trang 73Catching Errors as You Set Up URLsHandling Screen Updates in the paint()Method
Starting the Thread
Handling Mouse Clicks
Workshop: Revolving Links
Summary
Q&A
Quiz
Activities
Trang 74Hour 20 Reading and Writing FilesStreams
Writing Data to a Stream
Reading and Writing Configuration
Trang 75Hour 21 Reading and Writing XML DataCreating an XML File
Hour 22 Using Fonts and Color
Using the Font Class
Trang 76Using the Color Class
Other Ways to Choose Colors
Workshop: Displaying a Danger MessageSummary
Trang 77Workshop: Baking a Pie Graph
Summary
Q&A
Quiz
Activities
Hour 24 Creating Animation
Animating a Sequence of ImagesSending Parameters to the AppletWorkshop: Follow the Bouncing BallSummary
Trang 78Quiz
Activities
Part VII Bonus…
Hour 25 Creating Web Services withXML-RPC
Working with Apache XML-RPC
Trang 79Part VIII Appendixes
Appendix A Using the Java DevelopmentKit
Choosing a Java Development Tool
Configuring the Java Development KitUsing a Text Editor
Trang 80Creating a Sample Program
Setting Up the CLASSPATH VariableAppendix B Programming with the JavaDevelopment 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
Trang 82Other 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 CodeLicense
Agreement
Trang 83JAVA™ DEVELOPMENT TOOLS
Trang 85JAVA™ INTERFACE CLASSES
Trang 861.0 Software License Agreement
What's on the CD-ROM
Windows Installation Instructions
UNIX and UNIX-like Installation
Trang 87electronic, mechanical, photocopying,recording, or otherwise, without writtenpermission from the publisher No patentliability 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
Trang 88resulting from the use of the informationcontained herein.
Library of Congress Catalog Card
Trang 89have been appropriately capitalized SamsPublishing cannot attest to the accuracy ofthis information Use of a term in this bookshould not be regarded as affecting thevalidity of any trademark or service mark.
Warning and Disclaimer
Every effort has been made to make thisbook as complete and as accurate as
possible, but no warranty or fitness isimplied The information provided is on
Trang 90an "as is" basis The author and the
publisher shall have neither liability norresponsibility to any person or entity withrespect to any loss or damages arisingfrom the information contained in thisbook 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
Trang 91bulk purchases or special sales For moreinformation, please contact
U.S Corporate and Government Sales 1-800-382-3419
Trang 94Nonie 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,
Trang 95but 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
Trang 96as weird looking as you originally suspected Rogers
About the Author
Rogers Cadenhead is a writer, webapplication developer, and the mostvaluable player in an NBA playoffgame[*] He has written 20 books on
Internet-related topics, including Sams Teach Yourself Java 2 in 21 Days, Fourth Edition, Sams Teach Yourself
Trang 97Microsoft FrontPage 2003 in 24 Hours, and Radio UserLand Kick Start He
maintains this book's official website athttp://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
Trang 98seventh 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.
Trang 99Cadenhead's statistics in the game:
PLAYER MIN FGM-FGA FTM-FTAOFF-DEF-TOT AST PF ST TO PTSBEERS AVG DECIBEL LEVEL TRIPS
Trang 100To the folks at Samsespecially MarkTaber, Scott Meyers, John Purdum, andAndy Beaster No author can produce abook like this on his own, regardless ofwhat my agent told Sams during contractnegotiations Their excellent work willgive 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
Trang 101To my wife, Mary, and my sons, Max, Eli,and Sam Although our family has notfulfilled 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 havesent helpful comments about corrections,
Trang 102typos, and suggested improvements to thebook 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, MikeSavage, Peter Schrier, Gene Wines, JimYates, and others who shall remain
nameless because they helped me improvethe book before I started this list
Trang 103We 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 knowwhat we're doing right, what we could dobetter, what areas you'd like to see uspublish in, and any other words of
wisdom you're willing to pass our way.You can email or write me directly to let
Trang 104me know what you did or didn't like aboutthis bookas well as what we can do tomake 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 includethis book's title and author as well as your
Trang 105name and phone or email address I willcarefully review your comments and sharethem with the author and editors whoworked on the book.
Trang 106Introduction
Trang 107As the author of computer books, I spend alot of time lurking in the computer section
of bookstores, observing the behavior ofshoppers browsing through the books as ifthey were hominid jawbones and I was apaleontologist
Because of my research, I've learned that
if you have picked up this book and turned
to the introduction, I only have about 12more seconds before you put it down and
Trang 108head to the coffee bar for a double talllatte decaf skim with two shots of vanillahold 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 Javaskills to get high-paying jobs in softwaredevelopment, web application
Trang 109programming, and e-commerce The lastthing any of them want is for their bosses
to know that anyone who has persistenceand a little free time can learn this
language, the most popular programminglanguage in use today By working yourway 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