Home > Store

Sams Teach Yourself Java 6 in 21 Days, 5th Edition

Register your product to gain access to bonus material or receive a coupon.

Sams Teach Yourself Java 6 in 21 Days, 5th Edition


  • Sorry, this book is no longer in print.
Not for Sale


  • Copyright 2007
  • Dimensions: 7" x 9-1/8"
  • Pages: 720
  • Edition: 5th
  • Book
  • ISBN-10: 0-672-32943-3
  • ISBN-13: 978-0-672-32943-2

“If you get only one Java book, it should be Sams Teach Yourself Java in 21 Days”   —PC Magazine

In just 21 days, you can acquire the knowledge and skills necessary to develop three kinds of programs with Java: applications on your computer, servlets on a web server, and browser-launched Java Web Start applications.

No previous programming experience required. By following the 21 carefully organized lessons in this book, anyone can learn the basics of Java programming.

Learn at your own pace. You can work through each chapter sequentially to make sure you thoroughly understand all of the concepts and methodologies, or you can focus on specific lessons to learn the techniques that interest you most.

Test your knowledge. Each chapter ends with a Workshop section filled with questions, answers, and exercises for further study. There are even certification practice questions.

“Sams Teach Yourself Java is one of the best introductions to hands-on Java programming. If you buy one book on Java, this is the one to buy!”  —Independent Web Review

  • Completely revised, updated, and expanded to cover the latest features of Java 6
  • Learn to develop standalone Java applications, web servlets, JavaServer Pages, and Java Web Start applications
  • Easy-to-understand, practical examples clearly illustrate the fundamentals of Java programming
  • Discover how Swing can help you quickly develop programs with a graphical user interface
  • Find out about JDBC database programming, Internet client/server programming, and XML parsing with the open source XOM class library
  • Covers new features of version 6 such as Java DB, the new relational database that is now a built-in
  • part of Java

Rogers Cadenhead is a web application developer who has written 22 books on Internet-related topics, including Sams Teach Yourself Java 2 in 24 Hours. He maintains this book’s official website at http://www.java21days.com.

Laura Lemay is one of the world’s most popular authors on Web development topics. She is the author of the bestselling Sams Teach Yourself Web Publishing with HTML, as well as Sams Teach Yourself Perl in 21 Days.

CD-ROM includes:

  • Source code for the examples developed in the book
  • Java™ SE Development Kit 6
  • NetBeans™ IDE 5.5
  • Bonus materials

Category:  Java Programming

Covers:  Java 6 Platform Standard Edition

User Level:  Beginning–Intermediate 

Sample Content

Online Sample Chapters

How to Read and Write RSS Feeds

Reading and Writing RSS Feeds

Downloadable Sample Chapter

Download the sample chapter

Table of Contents

Introduction                                                                                                 1

    How This Book Is Organized... 2

    Who Should Read This Book... 4

    Conventions Used in This Book... 5

Week I: The Java Language                                                        

Day 1: Getting Started with Java                                                9

    The Java Language.... 10

        History of the Language... 10

        Introduction to Java... 11

        Selecting a Development Tool.. 11

    Object-Oriented Programming... 12

    Objects and Classes.... 14

    Attributes and Behavior... 17

        Attributes of a Class of Objects.. 17

        Behavior of a Class of Objects.. 18

        Creating a Class... 19

        Running the Program... 21

    Organizing Classes and Class Behavior.. 24

        Inheritance.... 24

        Creating a Class Hierarchy.. 26

        Inheritance in Action... 28

        Single and Multiple Inheritance.. 29

        Interfaces.... 30

        Packages.... 30

    Summary..... 31

    Q&A...... 31

    Quiz...... 32

        Questions.... 32

        Answers.... 32

        Certification Practice... 32

    Exercises..... 33

Day 2: The ABCs of Programming                                          35

    Statements and Expressions... 36

    Variables and Data Types... 36

        Creating Variables... 37

        Naming Variables... 39

        Variable Types.... 39

        Assigning Values to Variables.. 41

        Constants.... 41

    Comments..... 43

    Literals..... 44

        Number Literals... 45

        Boolean Literals... 46

        Character Literals... 46

        String Literals.... 47

    Expressions and Operators... 48

        Arithmetic.... 49

        More About Assignment.. 51

        Incrementing and Decrementing.. 52

        Comparisons.... 53

        Logical Operators... 54

        Operator Precedence... 55

    String Arithmetic.... 57

    Summary..... 58

    Q&A...... 59

    Quiz...... 60

        Questions.... 60

        Answers.... 60

        Certification Practice... 60

    Exercises..... 61

Day 3: Working with Objects                                                   63

    Creating New Objects.... 64

        Using new.... 64

        What new Does.... 66

        A Note on Memory Management. 66

    Accessing and Setting Class and Instance Variables 67

        Getting Values.... 67

        Changing Values... 68

        Class Variables.... 69

    Calling Methods.... 70

        Nesting Method Calls... 72

        Class Methods.... 73

    References to Objects.... 74

    Casting and Converting Objects and Primitive Types 76

        Casting Primitive Types... 77

        Casting Objects.... 78

        Converting Primitive Types to Objects and Vice Versa 80

    Comparing Object Values and Classes.. 82

        Comparing Objects... 82

        Determining the Class of an Object. 84

    Summary..... 84

    Q&A...... 85

    Quiz...... 86

        Questions.... 86

        Answers.... 86

        Certification Practice... 86

    Exercises..... 87

Day 4: Lists, Logic, and Loops                                                89

    Arrays..... 90

        Declaring Array Variables.. 90

        Creating Array Objects... 91

        Accessing Array Elements.. 92

        Changing Array Elements.. 93

        Multidimensional Arrays.. 95

    Block Statements.... 96

    if Conditionals.... 97

    switch Conditionals.... 98

    for Loops..... 104

    while and do Loops.... 107

        while Loops.... 107

        do-while Loops... 109

    Breaking Out of Loops... 109

        Labeled Loops... 110

        The Conditional Operator.. 110

    Summary..... 112

    Q&A..... 112

    Quiz...... 112

        Questions.... 112

        Answers.... 113

        Certification Practice... 113

    Exercises..... 114

Day 5: Creating Classes and Methods                                   115

    Defining Classes.... 116

    Creating Instance and Class Variables.. 116

        Defining Instance Variables.. 116

        Class Variables... 117

    Creating Methods.... 117

        Defining Methods... 118

        The this Keyword... 120

        Variable Scope and Method Definitions. 121

        Passing Arguments to Methods.. 122

        Class Methods... 123

    Creating Java Applications... 124

        Helper Classes... 125

    Java Applications and Command-line Arguments 126

        Passing Arguments to Java Applications. 126

        Handling Arguments in Your Java Application 127

    Creating Methods with the Same Name, Different Arguments 128

    Constructor Methods.... 132

        Basic Constructor Methods.. 133

        Calling Another Constructor Method. 133

        Overloading Constructor Methods. 134

    Overriding Methods.... 136

        Creating Methods That Override Existing Methods 136

        Calling the Original Method.. 137

        Overriding Constructors.. 138

    Finalizer Methods.... 140

    Summary..... 141

    Q&A..... 141

    Quiz...... 142

        Questions.... 142

        Answers.... 143

        Certification Practice... 143

    Exercises..... 144

Day 6: Packages, Interfaces, and Other Class Features       145

    Modifiers..... 146

        Access Control for Methods and Variables 146

    Static Variables and Methods... 152

    Final Classes, Methods, and Variables.. 154

        Variables.... 155

        Methods.... 155

        Classes.... 156

    Abstract Classes and Methods... 156

    Packages..... 157

    Using Packages.... 157

        Full Package and Class Names.. 158

        The import Declaration.. 159

        Class Name Conflicts... 160

        A Note About Classpath and Where Classes Are Located 161

    Creating Your Own Packages... 162

        Picking a Package Name.. 162

        Creating the Folder Structure.. 162

        Adding a Class to a Package.. 163

        Packages and Class Access Control. 163

    Interfaces..... 164

        The Problem of Single Inheritance. 164

        Interfaces and Classes... 164

        Implementing and Using Interfaces. 165

        Implementing Multiple Interfaces. 165

        Other Uses of Interfaces.. 166

    Creating and Extending Interfaces.. 166

        New Interfaces... 166

        Methods Inside Interfaces.. 167

        Extending Interfaces... 168

        Creating an Online Storefront.. 169

    Inner Classes..... 175

    Summary..... 177

    Q&A..... 178

    Quiz...... 179

        Questions.... 179

        Answers.... 179

        Certification Practice... 179

    Exercises..... 181

Day 7: Exceptions, Assertions, and Threads                         183

    Exceptions..... 184

        Exception Classes... 186

    Managing Exceptions.... 187

        Exception Consistency Checking. 188

        Protecting Code and Catching Exceptions 188

        The finally Clause... 190

    Declaring Methods That Might Throw Exceptions 193

        The throws Clause... 193

        Which Exceptions Should You Throw?. 194

        Passing On Exceptions... 195

        throws and Inheritance... 196

    Creating and Throwing Your Own Exceptions. 197

        Throwing Exceptions... 197

        Creating Your Own Exceptions.. 198

        Combining throws, try, and throw. 199

    When and When Not to Use Exceptions. 200

        When to Use Exceptions.. 200

        When Not to Use Exceptions.. 200

        Bad Style Using Exceptions.. 201

    Assertions..... 202

    Threads..... 205

        Writing a Threaded Program.. 206

        A Threaded Application.. 207

        Stopping a Thread... 211

    Summary..... 212

    Q&A..... 213

    Quiz...... 214

        Questions.... 214

        Answers.... 215

        Certification Practice... 215

    Exercises..... 216

Week II: The Java Class Library                                             

Day 8: Data Structures                                                            219

    Moving Beyond Arrays... 220

    Java Structures.... 220

        Iterator.... 222

        Bit Sets.... 223

        Vectors.... 226

        Looping Through Data Structures. 229

        Stacks.... 232

        Map..... 233

        Hash Tables.... 235

    Generics..... 240

    Summary..... 243

    Q&A..... 244

    Quiz...... 244

    Questions.... 244

    Answers..... 245

    Certification Practice... 245

    Exercises..... 246

Day 9: Working with Swing                                                   247

    Creating an Application... 248

        Creating an Interface... 249

        Developing a Framework.. 251

        Displaying a Splash Page.. 253

        Creating a Component... 253

        Adding Components to a Container. 254

    Working with Components... 256

        Image Icons.... 257

        Labels.... 259

        Text Fields.... 259

        Text Areas.... 260

        Scrolling Panes... 262

        Check Boxes and Radio Buttons. 263

        Combo Boxes.... 266

    Lists...... 267

    Summary..... 269

    Q&A..... 270

    Quiz...... 270

        Questions.... 270

        Answers.... 271

        Certification Practice... 271

    Exercises..... 272

Day 10: Building a Swing Interface                                     273

    Swing Features.... 274

        Setting the Look and Feel.. 274

        Standard Dialog Boxes... 277

        Using Dialog Boxes... 282

        Sliders.... 285

        Scroll Panes.... 287

        Toolbars.... 288

        Progress Bars.... 291

        Menus.... 293

        Tabbed Panes.... 297

    Summary..... 298

    Q&A..... 299

    Quiz...... 299

        Questions.... 299

        Answers.... 300

        Certification Practice... 300

    Exercises..... 301

Day 11: Arranging Components on a User Interface         303

    Basic Interface Layout... 304

        Laying Out an Interface.. 304

        Flow Layout.... 305

        Box Layout.... 307

        Grid Layout.... 309

        Border Layout.... 311

    Mixing Layout Managers... 312

    Card Layout..... 313

        Using Card Layout in an Application. 315

    Grid Bag Layout.... 321

        Designing the Grid... 323

        Creating the Grid... 324

        Cell Padding and Insets.. 329

    Summary..... 329

    Q&A..... 330

    Quiz...... 331

        Questions.... 331

        Answers.... 331

        Certification Practice... 331

    Exercises..... 332

Day 12: Responding to User Input                                      333

    Event Listeners.... 334

        Setting Up Components.. 335

        Event-Handling Methods.. 336

    Working with Methods... 338

        Action Events.... 339

        Focus Events.... 340

        Item Events.... 342

        Key Events.... 344

        Mouse Events.... 345

        Mouse Motion Events... 345

        Window Events... 349

        Using Adapter Classes... 350

    Summary..... 351

    Q&A..... 352

    Quiz...... 353

        Questions.... 353

        Answers.... 353

        Certification Practice... 353

    Exercises..... 355

Day 13: Using Color, Fonts, and Graphics                         357

    The Graphics2D Class... 358

        The Graphics Coordinate System. 359

    Drawing Text..... 360

        Improving Fonts and Graphics with Antialiasing 362

        Finding Information About a Font. 363

    Color..... 365

        Using Color Objects... 366

        Testing and Setting the Current Colors. 366

    Drawing Lines and Polygons... 368

        User and Device Coordinate Spaces. 368

        Specifying the Rendering Attributes. 368

        Creating Objects to Draw.. 371

        Drawing Objects... 375

    Summary..... 378

    Q&A..... 378

    Quiz...... 379

        Questions.... 379

        Answers.... 379

        Certification Practice... 379

    Exercises..... 380

Day 14: Developing Swing Applications                            381

    Java Web Start.... 382

    Using Java Web Start.... 385

        Creating a JNLP File... 386

        Supporting Web Start on a Server. 391

        Additional JNLP Elements.. 392

    Improving Performance with SwingWorker. 394

    Summary..... 399

    Q&A..... 400

    Quiz...... 400

        Questions.... 400

        Answers.... 401

        Certification Practice... 401

    Exercises..... 402

Week III: Java Programming                                                 

Day 15: Working with Input and Output                             405

    Introduction to Streams... 406

        Using a Stream... 406

        Filtering a Stream... 407

        Handling Exceptions... 408

    Byte Streams..... 408

        File Streams.... 408

    Filtering a Stream.... 413

        Byte Filters.... 413

    Character Streams.... 422

        Reading Text Files... 422

        Writing Text Files... 425

    Files and Filename Filters... 426

    Summary..... 429

    Q&A..... 430

    Quiz...... 431

        Questions.... 431

        Answers.... 431

        Certification Practice... 432

    Exercises..... 432

Day 16: Serializing and Examining Objects                       433

    Object Serialization.... 434

        Object Output Streams... 435

        Object Input Streams... 438

        Transient Variables... 441

        Checking an Object’s Serialized Fields. 442

    Inspecting Classes and Methods with Reflection 443

        Inspecting and Creating Classes. 443

        Working with Each Part of a Class. 445

        Inspecting a Class... 447

    Summary..... 449

    Q&A..... 449

    Quiz...... 450

        Questions.... 451

        Answers.... 450

        Certification Practice... 451

    Exercises..... 452

Day 17: Communicating Across the Internet                     453

    Networking in Java.... 454

        Opening a Stream over the Net.. 454

        Sockets.... 459

        Socket Servers... 463

        Testing the Server... 466

    The java.nio Package.... 467

        Buffers.... 467

        Channels.... 471

    Summary..... 481

    Q&A..... 481

    Quiz...... 482

        Questions.... 482

        Answers.... 482

        Certification Practice... 483

    Exercises..... 483

Day 18: Accessing Databases with JDBC                          485

    Java Database Connectivity... 486

        Database Drivers... 487

    The JDBC-ODBC Bridge... 487

        Connecting to an ODBC Data Source. 489

        JDBC Drivers.... 502

    Summary..... 507

    Q&A..... 508

    Quiz...... 508

        Questions.... 508

        Answers.... 509

        Certification Practice... 509

    Exercises..... 510

Day 19: Reading and Writing RSS Feeds                           511

    Using XML..... 512

    Designing an XML Dialect... 515

    Processing XML with Java... 516

    Processing XML with XOM... 516

        Creating an XML Document.. 518

        Modifying an XML Document.. 521

        Formatting an XML Document.. 525

        Evaluating XOM... 528

    Summary..... 530

    Q&A..... 531

    Quiz...... 531

        Questions.... 531

        Answers.... 532

        Certification Practice... 532

    Exercises..... 533

Day 20: XML Web Services                                                535

    Introduction to XML-RPC... 536

    Communicating with XML-RPC.. 537

        Sending a Request... 538

        Responding to a Request.. 539

    Choosing an XML-RPC Implementation. 540

    Using an XML-RPC Web Service.. 542

    Creating an XML-RPC Web Service.. 546

    Summary..... 551

    Q&A..... 551

    Quiz...... 552

        Questions.... 552

        Answers.... 552

        Certification Practice... 552

    Exercises..... 553

Day 21: Writing Java Servlets and Java Server Pages        555

    Using Servlets.... 556

    Developing Servlets.... 559

        Using Cookies... 565

        Using Sessions... 568

    JSP...... 572

        Writing a JSP Page... 574

        Creating a Web Application.. 581

    JSP Standard Tag Library... 587

    Summary..... 594

    Q&A..... 595

    Quiz...... 596

        Questions.... 596

        Answers.... 596

        Certification Practice... 597

    Exercises..... 597


Appendix A: Using the Java Development Kit     601

Appendix B: Programming with the Java Development Kit   625

Appendix C: This Book’s Website                        649

Index                                                                                                        651

Bonus Material on the Companion CD-ROM

CD1  Choosing Java

CD2  Writing Java Applets

CD3  Regular Expressions

CD4  Where to Go from Here: Java Resources

0672329433, TOC, 5/4/2007


Download the Index


Download the Introduction

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020