Book II: Programming Basics Chapter 1: Java Programming Basics Dealing with Keywords Working with Statements Working with Blocks Creating Identifiers Crafting Comments Introducing Ob
Trang 1Table of Contents
Back Cover
Java All-In-One Desk
Reference for Dummies, 2nd Edition
Introduction
About This Book
How to Use This Book
How This Book Is Organized Icons Used in This Book
Where to Go from Here
Book I: Java Basics
Chapter 1: Welcome to Java
Trang 2Comparing Java to Other
Trang 4Book II: Programming Basics Chapter 1: Java Programming Basics
Dealing with Keywords
Working with Statements Working with Blocks
Creating Identifiers
Crafting Comments
Introducing Object-Oriented Programming
Importing Java API Classes Chapter 2: Working with
Variables and Data Types Initializing Variables
Trang 5Using Final Variables
(Constants)
Working with Primitive Data Types
Using Reference Types
Working with Strings
Converting and Casting
Trang 6Getting Input with the
JOptionPane Class
Chapter 3: Working with
Numbers and Expressions
Using the Math Class
Trang 7Formatting Numbers
Weird Things about Java Math Chapter 4: Making Choices Using if Statements
Mr Spock's Favorite Operators (the Logical Ones, of Course) Using the Conditional Operator Comparing Strings
Chapter 5: Going Around in Circles (Or, Using Loops)
Your Basic while Loop
Breaking Out of a Loop
Looping Forever
Using the continue Statement
Trang 8Validating Input from the User The Famous for Loop
Nesting Your Loops
Chapter 6: Pulling a Switcheroo
A Better Version of the Voting Machine Error Decoder
Program
Using the switch Statement
A Boring Business Example Complete with Flowchart
Putting if Statements Inside
switch Statements
Creating Character Cases
Falling through the Cracks
Trang 9Chapter 7: Adding Some
Methods to Your Madness
The Basics of Making Methods Methods That Return Values Using Methods That Take
Trang 10Using a finally Block
Handling Checked Exceptions Throwing Your Own
The Life Cycle of an Object Designing a Program with
Objects
Diagramming Classes with UML
Trang 11Chapter 2: Making Your Own Classes
Working with Members
Getters and Setters
Trang 12Chapter 4: Using Subclasses and Inheritance
Creating Subclasses
Overriding Methods
Protecting Your Members Using this and super in Your Subclasses
Inheritance and Constructors Using final
Casting Up and Down
Determining an Object's Type Poly What?
Creating Custom Exceptions Chapter 5: Using Abstract
Trang 13Classes and Interfaces
The toString Method
The equals Method
The clone Method
The Class Class
Chapter 7: Using Inner Classes Using Static Inner Classes
Using Anonymous Inner
Classes
Trang 14Chapter 8: Packaging and
Documenting Your Classes Putting Your Classes in a JAR File
Using JavaDoc to Document Your Classes
Book IV: Strings, Arrays, and Collections
Chapter 1: Working with Strings Using the String Class
Using the StringBuilder and
StringBuffer Classes
Using the CharSequence
Interface
Trang 15Chapter 2: Using Arrays
Creating Arrays
Initializing an Array
Using for Loops with Arrays Solving Homework Problems with Arrays
Using the Enhanced for Loop Using Arrays with Methods Using Two-Dimensional Arrays
A Fun but Complicated
Example: A Chessboard
Using the Arrays Class
Chapter 3: Using the ArrayList Class
Trang 16The ArrayList Class
Creating an ArrayList Object Adding Elements
Trang 17Updating LinkedList Items Removing LinkedList Items Chapter 5: Creating Generic Collection Classes
Creating a Generic Class
A Generic Stack Class
Understanding Threads
Trang 19Chapter 4: Using Recursion Displaying Directories
Writing Your Own Sorting Routine
Book VI: Swing
Trang 20Chapter 1: Swinging into Swing I've Been Framed!
Hello, World! in Swing
Positioning the Frame
The ClickMe Program
Using Inner Classes to Listen
Trang 21for Events
Adding an Exit Button
Catching the WindowClosing Event
The ClickMe Program Revisited Chapter 3: Getting Input from the User
Using Text Areas
Using Check Boxes
Using Radio Buttons
Using Borders
Designing a Pizza-Ordering Program
Using Sliders
Trang 22Chapter 4: Choosing from a List Using Lists
Using Spinners
Using Trees
Chapter 5: Using Layout
Managers
Using Flow Layout
Using Border Layout
Using Box Layout
Using Grid Layout
Using GridBag Layout
Using Group Layout
Book VII: Web Programming Chapter 1: Creating Applets
Trang 23The JApplet Class
Looking at a Sample Applet Creating an HTML Page for an Applet
Trang 24Book VIII: Files and Databases Chapter 1: Working with Files Using Command-Line
Parameters
Trang 25Choosing Files in a Swing
Writing Binary Streams
Chapter 3: Database for $100, Please
What Is SQL, and How Do You Pronounce It?
SQL Statements
Creating a SQL Database
Trang 27Putting It All Together: A
Program That Lists Movies Book IX: Fun and Games Chapter 1: Fun with Fonts and Colors
Working with Color
Chapter 2: Drawing Shapes Drawing Shapes
Trang 28Chapter 3: Using Images and Sound
Using the ImageIcon Class Using the Image Class
Playing Sounds and Making Music
Chapter 4: Animation and
Trang 31List of Listings List of Sidebars
Trang 32Java All-In-One Desk
Reference For Dummies, 2nd Edition
byDoug LoweandBarry BurdJohn Wiley & Sons 2007(914 pages)
ISBN:9780470124512
Covering everything fromJava and XML to Swing,Server-side Java, and
Eclipse, this one-stop guidewill show you how to doobject-oriented programming,create applets for the Web,read and write XML data,and much more
Trang 33Table of Contents
Java All-In-One Desk Reference forDummies, 2nd Edition
Introduction
Book I - Java Basics
Chapter 1- Welcome to Java
Chapter 2-Installing and Using Java
Tools
Chapter 3- Working with TextPad
Chapter 4- Using Eclipse
Book II - Programming Basics
Chapter 1- Java Programming Basics
Chapter 2-Working with Variables and
Data Types
Chapter 3-Working with Numbers and
Expressions
Trang 34Chapter 4- Making Choices
Chapter 5-Going Around in Circles (Or,
Using Loops)
Chapter 6- Pulling a Switcheroo
Chapter 7-Adding Some Methods to
Your Madness
Chapter 8- Handling Exceptions
Book III - Object-Oriented
Programming
Chapter 1-Understanding
Object-Oriented Programming
Chapter 2- Making Your Own Classes
Chapter 3- Working with Statics
Chapter 4-Using Subclasses and
Inheritance
Chapter 5-Using Abstract Classes and
Interfaces
Trang 35Chapter 6-Using the Object and Class
Classes
Chapter 7- Using Inner Classes
Chapter 8-Packaging and Documenting
Your Classes
Book IV - Strings, Arrays, and
Collections
Chapter 1- Working with Strings
Chapter 2- Using Arrays
Chapter 3- Using the ArrayList Class
Chapter 4- Using the LinkedList Class
Chapter 5-Creating Generic Collection
Classes
Book V - Programming Techniques
Chapter 1- Programming Threads
Chapter 2- Network Programming
Trang 36Chapter 3- Using Regular Expressions
Chapter 4- Using Recursion
Book VI - Swing
Chapter 1- Swinging into Swing
Chapter 2- Handling Events
Chapter 3- Getting Input from the User
Chapter 4- Choosing from a List
Chapter 5- Using Layout Managers
Book VII - Web Programming
Chapter 1- Creating Applets
Chapter 2- Creating Servlets
Chapter 3- Using Java Server Pages
Chapter 4- Using JavaBeans
Book VIII - Files and Databases
Chapter 1- Working with Files
Chapter 2- Using File Streams
Trang 37Chapter 3- Database for $100, Please
Chapter 4-Using JDBC to Connect to aDatabase
Chapter 5- Working with XML
Book IX - Fun and Games
Chapter 1- Fun with Fonts and Colors
Chapter 2- Drawing Shapes
Chapter 3- Using Images and Sound
Chapter 4-Animation and Game
Trang 38to Swing, Server-side Java, and Eclipse.You'll do object-oriented programming,create applets for the Web, read andwrite XML data, and much more!
Install and use Java tools
Trang 39Work with variables and datatypes
Program for a network
Build graphical user interfaces
Create servlets and Java ServerPages
Develop animations and simplegames
Trang 40Java All-In-One Desk
Reference for Dummies, 2nd Edition
Trang 41Published by Wiley Publishing, Inc.,
Indianapolis, Indiana
Published simultaneously in Canada
No part of this publication may be
reproduced, stored in a retrieval system ortransmitted in any form or by any means,electronic, mechanical, photocopying,recording, scanning or otherwise, except
as permitted under Sections 107 or 108 ofthe 1976 United States Copyright Act,without either the prior written permission
of the Publisher, or authorization throughpayment of the appropriate per-copy fee tothe Copyright Clearance Center, 222
Rosewood Drive, Danvers, MA 01923,(978) 750-8400, fax (978) 646-8600.Requests to the Publisher for permission
Trang 42should be addressed to the Legal
Department, Wiley Publishing, Inc., 10475Crosspoint Blvd., Indianapolis, IN 46256,(317) 572-3447, fax (317) 572-4355, oronline at
http://www.wiley.com/go/permissions
Trademarks: Wiley, the Wiley
Publishing logo, For Dummies, the
Dummies Man logo, A Reference for theRest of Us!, The Dummies Way, DummiesDaily, The Fun and Easy Way,
http://www.Dummies.com, and relatedtrade dress are trademarks or registeredtrademarks of John Wiley & Sons, Inc.and/or its affiliates in the United Statesand other countries, and may not be usedwithout written permission Java is aregistered trademark of Sun
Trang 43Microsystems, Inc All other trademarksare the property of their respective
owners Wiley Publishing, Inc., is notassociated with any product or vendormentioned in this book
WITHOUT LIMITATION
WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE NO
Trang 44WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR
PROMOTIONAL MATERIALS THE ADVICE AND STRATEGIES
CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE
PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL,
ACCOUNTING, OR OTHER
PROFESSIONAL SERVICES IF
PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL
PERSON SHOULD BE SOUGHT NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE
Trang 45FOR DAMAGES ARISING
HEREFROM THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER
INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE
PUBLISHER ENDORSES THE
INFORMATION THE
ORGANIZATION OR WEBSITE MAY PROVIDE OR
RECOMMENDATIONS IT MAY
MAKE FURTHER, READERS
SHOULD BE AWARE THAT
INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED
OR DISAPPEARED BETWEEN
Trang 46WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other
products and services, please contact ourCustomer Care Department within the U.S
at 800-762-2974, outside the U.S at 572-3993, or fax 317-572-4002
317-For technical support, please visit
http://www.wiley.com/techsupport
Wiley also publishes its books in a variety
of electronic formats Some content thatappears in print may not be available inelectronic books
Library of Congress Control Number:2007926004
978-0-470-12451-2
Trang 47Manufactured in the United States ofAmerica
Acquisitions, Editorial, and Media Development
Senior Project Editor: Mark Enochs
Trang 48(Previous Edition: Kim Darosett)
Senior Acquisitions Editor: Katie
Feltman
Senior Copy Editor: Barry Childs-Helton
Technical Editor: Doug Lowe
Editorial Manager: Leah Cameron
Media Development and Quality
Assurance: Angela Denny, Kate Jenkins,Steven Kudirka, Kit Malone
Media Development Coordinator: JennySwisher
Media Project Supervisor: Laura Hollister
Trang 49Moss-Editorial Assistant: Amanda Foxworth
Sr Editorial Assistant: Cherie Case
Cartoons: Rich Tennant
(http://www.the5thwave.com)
Composition Services
Project Coordinator: Adrienne Martinez
Layout and Graphics: Claudia Bell,Denny Hager, Stephanie D Jumper,
Barbara Moore, Heather Ryan, RonaldTerry
Proofreaders: Aptara, Christy Pingleton
Indexer: Aptara
Trang 50Anniversary Logo Design: RichardPacifico
Special Help: Christine Williams
Publishing and Editorial for Technology Dummies
Richard Swadley, Vice President andExecutive Group Publisher
Andy Cummings, Vice President andPublisher
Mary Bednarek, Executive AcquisitionsDirector
Mary C Corder, Editorial Director
Publishing for Consumer Dummies
Trang 51Diane Graves Steele, Vice President andPublisher
Joyce Pepple, Acquisitions Director
Doug dedicates his part of the book
to Debbie, Rebecca, Sarah, and
Bethany
Barry dedicates his part of the book
Trang 52to Harriet and Jennie, Sam and
Jennie, Sam and Ruth
About the Authors
Doug Lowe has been writing computerprogramming books since the guys whoinvented Java were still in high school.He's written books on COBOL, Fortran,Visual Basic, IBM mainframe computers,mid-range systems, PCs, Web
programming, and probably a few he'sforgotten about He's the author of more
than 30 For Dummies books, such as Networking For Dummies, 7th Edition, Networking For Dummies All-in-One Desk Reference, 2nd Edition , ASP.NET Everyday Applications For Dummies, and Word 2007 All-in-One Desk Reference
Trang 53For Dummies He lives with his wife and
the youngest of his three daughters in thatsunny All-American City Fresno,
California, where the motto is, "It's asunny, All-American City." He's also one
of those obsessive-compulsive decoratingnuts who puts up tens of thousands oflights at Christmas and creates computer-controlled Halloween decorations thatrival Disney's Haunted Mansion Maybe
his next book should be Tacky Holiday Decorations For Dummies.
Barry Burd received an M.S degree inComputer Science at Rutgers Universityand a Ph.D in Mathematics at the
University of Illinois As a teaching
assistant in Champaign-Urbana, Illinois,
he was elected five times to the
Trang 54university-wide List of Teachers Ranked
as Excellent by their Students
Since 1980, Dr Burd has been a professor
in the Department of Mathematics andComputer Science at Drew University inMadison, New Jersey When he's notlecturing at Drew University, Dr Burdleads training courses for professionalprogrammers in business and industry Hehas lectured at conferences in the UnitedStates, Europe, Australia, and Asia He isthe author of several articles and books,
including Java For Dummies and Ruby on Rails For Dummies, both from Wiley
Publishing, Inc
Dr Burd lives in Madison, New Jersey,with his wife and two children In his
Trang 55spare time, he enjoys being a workaholic.
Authors' Acknowledgments
We'd like to thank project editor MarkEnochs, who did a great job of managingall the editorial work that was required toput this book together in spite of a shortschedule and oft-missed deadlines, andacquisitions editor Katie Feltman whomade the whole project possible We'dalso like to thank copy editor Barry
Childs-Helton who made sure the i's werecrossed and the t's were dotted (oops,reverse that!) And, as always, thanks toall the behind-the-scenes people whochipped in with help we're not even awareof
Trang 56Introduction
Trang 57Welcome to Java All-In-One Desk
Reference For Dummies, Second
Edition-the one Java book that's designed to
replace an entire shelf full of the dull andtedious Java books you'd otherwise have
to buy This book contains all the basic(and not-so-basic) information you need toknow to get going with Java programming-starting with writing statements and usingvariables, and ending with techniques forwriting programs that use animation andplay games Along the way, you find
information about programming user
interfaces, working with classes and
objects, creating Web applications, anddealing with files and databases
Trang 58You can (and probably should, eventually)buy separate books on each o these topics.
It won't take long before your bookshelf isbulging with 10,000 or more pages ofdetailed information about every
imaginable nuance of Java programming.But before you're ready to tackle each ofthose topics in depth, you need to get abird's-eye picture That's what this book isabout
And if you already own 10,000 pages or
more of Java information, you may beoverwhelmed by the amount of detail and
wonder, "Do I really need to read 1,200
pages about JSP just to create a simple
Web page? And do I really need a
six-pound book on Swing?" Truth is, most1,200-page programming books have