Home > Store

Sams Teach Yourself Java in 21 Days (Covering Java 7 and Android), 6th Edition

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

Sams Teach Yourself Java in 21 Days (Covering Java 7 and Android), 6th Edition


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



  • Updated and expanded to cover Java 7 – version 7 of the Java Standard Edition SDK
  • Special emphasis placed on Android programming and NetBeans, the free integrated IDE for Java
  • Previous editions have been acclaimed for clear and personable writing, for high-quality examples, and for logical and complete organization


  • Copyright 2013
  • Edition: 6th
  • Book
  • ISBN-10: 0-672-33574-3
  • ISBN-13: 978-0-672-33574-7

Sams Teach Yourself Java in 21 Days
Covering Java 7 and Android App Development

Sams Teach Yourself Java in 21 Days continues to be one of the most popular, best-selling Java tutorials on the market. Written by an expert technical writer, it has been acclaimed for its clear and personable writing, for its extensive use of examples, and for its logical and complete organization.

The sixth edition of Sams Teach Yourself Java in 21 Days adds coverage of Java 7 and places a special emphasis on Android programming, capitalizing on the fastest-growing area of Java programming. There will be a new chapter on Android development and additional material where appropriate throughout the book. This edition also includes new material on using NetBeans, the free integrated IDE for Java.

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 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.

  • Completely revised, updated, and expanded to cover the latest features of Java 7
  • Learn to develop standalone Java applications, Android apps, 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 4.1 programming with the Java DB database and XML parsing with the open source XOM class library
  • Covers new features of Java 7 such as improved try-catch exception handling, the new switch, and Nimbus look and feel

Sample Content

Online Sample Chapter

Working with Objects in Java

Sample Pages

Download the sample pages (includes Chapter 3 and Index)

Table of Contents

Introduction     1

WEEK 1: The Java Language     7

1 Getting Started with Java     9

The Java Language     10

History of the Language     10

Introduction to Java     11

Selecting a Development Tool      12

Object-Oriented Programming     13

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     23

Organizing Classes and Class Behavior     25


Creating a Class Hierarchy     27

Inheritance in Action     29

Interfaces     31

Packages     32

Summary     32


Quiz     34

Questions     34

Certification Practice     34

Exercises     35

2 The ABCs of Programming     37

Statements and Expressions     38

Variables and Data Types     38

Creating Variables     39

Naming Variables     40

Variable Types     41

Assigning Values to Variables     43

Constants     43

Comments     45

Literals     46

Number Literals     47

Boolean Literals     48

Character Literals     49

String Literals     50

Expressions and Operators     51

Arithmetic     51

More About Assignment     53

Incrementing and Decrementing     54

Comparisons     56

Logical Operators     57

Operator Precedence     58

String Arithmetic     60

Summary     61

Q&A     62

Quiz     62

Questions     62

Certification Practice     63

Exercises     63

3 Working with Objects     65

Creating New Objects     66

Using new     66

How Objects Are Constructed     68

A Note on Memory Management     69

Using Class and Instance Variables     70

Getting Values     70

Setting Values     70

Class Variables     72

Calling Methods     73

Formatting Strings     75

Nesting Method Calls     75

Class Methods     76

References to Objects     77

Casting Objects and Primitive Types     79

Casting Primitive Types     80

Casting Objects     81

Converting Primitive Types to Objects and Vice Versa     83

Comparing Object Values and Classes     84

Comparing Objects     85

Determining the Class of an Object     87

Summary     87

Q&A     88

Quiz     88

Questions     89

Certification Practice     89

Exercises     90

4 Lists, Logic, and Loops     91

Arrays     92

Declaring Array Variables     92

Creating Array Objects     93

Accessing Array Elements     94

Changing Array Elements     95

Multidimensional Arrays    97

Block Statements     98

If Conditionals     99

Switch Conditionals     101

The Ternary Operator     107

For Loops     108

While and Do Loops     111

While Loops     111

Do-While Loops     113

Breaking Out of Loops     114

Labeled Loops     114

Summary     115

Q&A     115

Quiz     116

Questions     116

Certification Practice     117

Exercises     117

5 Creating Classes and Methods     119

Defining Classes     120

Creating Instance and Class Variables     120

Defining Instance Variables     120

Class Variables     121

Creating Methods     121

Defining Methods     122

The this Keyword     124

Variable Scope and Method Definitions     125

Passing Arguments to Methods     126

Class Methods     127

Creating Java Applications     129

Helper Classes     130

Java Applications and Command-Line Arguments     130

Passing Arguments to Java Applications     130

Handling Arguments in Your Java Application     131

Creating Methods with the Same Name     133

Constructors     136

Basic Constructors     137

Calling Another Constructor     138

Overloading Constructors     138

Overriding Methods     140

Creating Methods That Override Existing Methods     140

Calling the Original Method     142

Overriding Constructors     143

Summary     144

Q&A     145

Quiz     146

Questions     146

Certification Practice     146

Exercises     148

6 Packages, Interfaces, and Other Class Features     149

Modifiers     150

Access Control for Methods and Variables     151

Static Variables and Methods     157

Final Classes, Methods, and Variables     159

Variables     159

Methods     160

Classes     160

Abstract Classes and Methods     161

Packages     162

The import Declaration     163

Class Name Conflicts     165

Creating Your Own Packages     165

Picking a Package Name     165

Creating the Folder Structure     166

Adding a Class to a Package     166

Packages and Class Access Control     166

Interfaces     167

The Problem of Single Inheritance     167

Interfaces and Classes     168

Implementing and Using Interfaces     168

Implementing Multiple Interfaces     169

Other Uses of Interfaces     169

Creating and Extending Interfaces     170

New Interfaces     170

Methods Inside Interfaces     171

Extending Interfaces     172

Creating an Online Storefront     172

Inner Classes     179

Summary     181

Q&A     182

Quiz     183

Questions     183

Certification Practice     183

Exercises     185

7 Exceptions and Threads     187

Exceptions     188

Exception Classes     190

Managing Exceptions     191

Exception Consistency Checking     191

Protecting Code and Catching Exceptions     192

The finally Clause     195

Declaring Methods That Might Throw Exceptions     198

The throws Clause     199

Which Exceptions Should You Throw?      200

Passing on Exceptions     201

throws and Inheritance     202

Creating and Throwing Your Own Exceptions     203

Throwing Exceptions     203

Creating Your Own Exceptions     204

Combining throws, try, and throw     204

When and When Not to Use Exceptions     205

When to Use Exceptions     205

When Not to Use Exceptions     206

Bad Style Using Exceptions     206

Threads     207

Writing a Threaded Program     207

A Threaded Application     209

Stopping a Thread     214

Summary     215

Q&A     215

Quiz     217

Questions     217

Certification Practice     217

Exercises     218

WEEK 2: The Java Class Library     219

8 Data Structures     221

Moving Beyond Arrays     222

Java Structures     222

Iterator     224

Bit Sets     225

Array Lists     228

Looping Through Data Structures     231

Stacks     233

Map     235

Hash Maps     236

Generics     241

Summary     245

Q&A     245

Quiz     246

Questions     246

Certification Practice     246

Exercises     247

9 Working with Swing     249

Creating an Application     250

Creating an Interface     251

Developing a Framework     254

Creating a Component     255

Adding Components to a Container     256

Working with Components     258

Image Icons     259

Labels     261

Text Fields     262

Text Areas     263

Scrolling Panes     265

Check Boxes and Radio Buttons     266

Combo Boxes     269

Lists     271

Summary     273

Q&A     273

Quiz     274

Questions     274

Certification Practice     274

Exercises     275

10 Building a Swing Interface     277

Swing Features     278

Standard Dialog Boxes     278

Using Dialog Boxes     283

Sliders     286

Scroll Panes     288

Toolbars     289

Progress Bars     292

Menus     295

Tabbed Panes     299

Summary     301

Q&A     301

Quiz     302

Questions     302

Certification Practice     303

Exercises     304

11 Arranging Components on a User Interface     305

Basic Interface Layout     306

Laying Out an Interface     306

Flow Layout     307

Box Layout     309

Grid Layout     311

Border Layout     314

Mixing Layout Managers     316

Card Layout     317

Using Card Layout in an Application     319

Grid Bag Layout     325

Designing the Grid     327

Creating the Grid     329

Cell Padding and Insets     334

Summary     335

Q&A     335

Quiz     336

Questions     336

Certification Practice     337

Exercises     338

12 Responding to User Input     339

Event Listeners     340

Setting Up Components     341

Event-Handling Methods     342

Working with Methods     345

Action Events     345

Focus Events     346

Item Events     349

Key Events     351

Mouse Events     352

Mouse Motion Events     352

Window Events     357

Using Adapter Classes     357

Using Inner Classes     359

Summary     362

Q&A     362

Quiz     363

Questions     363

Certification Practice     363

Exercises     365

13 Creating Java2D Graphics     367

The Graphics2D Class     368

The Graphics Coordinate System     369

Drawing Text     370

Improving Fonts and Graphics with Antialiasing     372

Finding Information About a Font     372

Color     375

Using Color Objects     375

Testing and Setting the Current Colors     376

Drawing Lines and Polygons     377

User and Device Coordinate Spaces     377

Specifying the Rendering Attributes     378

Creating Objects to Draw     381

Drawing Objects     384

Summary     387

Q&A     387

Quiz     388

Questions     388

Certification Practice     388

Exercises     389

14 Developing Swing Applications     391

Java Web Start     392

Using Java Web Start     395

Creating a JNLP File     396

Supporting Web Start on a Server     405

Additional JNLP Elements     406

Improving Performance with SwingWorker     408

Summary     413

Q&A     414

Quiz     414

Questions     414

Certification Practice     415

Exercises     416

WEEK 3: Java Programming     417

15 Working with Input and Output     419

Introduction to Streams     420

Using a Stream     420

Filtering a Stream     421

Handling Exceptions     421

Byte Streams     422

File Streams     422

Filtering a Stream     426

Byte Filters     427

Character Streams     436

Reading Text Files     436

Writing Text Files     439

Files and Paths     440

Summary     443

Q&A     443

Quiz     444

Questions     444

Certification Practice     445

Exercises     446

16 Serializing and Examining Objects     447

Object Serialization     448

Object Output Streams     449

Object Input Streams     452

Transient Variables     455

Checking an Object’s Serialized Fields     456

Inspecting Classes and Methods with Reflection     457

Inspecting and Creating Classes     457

Working with Each Part of a Class     459

Inspecting a Class     461

Summary     463

Q&A     463

Quiz     464

Questions     464

Certification Practice     465

Exercises     465

17 Communicating Across the Internet     467

Networking in Java     468

Opening a Stream Over the Net     468

Sockets     473

Socket Servers     476

Testing the Server     479

The java.nio Package     481

Buffers     481

Channels     485

Summary     495

Q&A     496

Quiz     496

Questions     496

Certification Practice     497

Exercises     498

18 Accessing Databases with JDBC 4.1 and Derby     499

Java Database Connectivity     500

Database Drivers     501

Examining a Database     501

Reading Records from a Database     503

Writing Records to a Database     509

Moving Through Resultsets     516

Summary     517

Q&A     518

Quiz     518

Questions     518

Certification Practice     519

Exercises     519

19 Reading and Writing RSS Feeds     521

Using XML     522

Designing an XML Dialect     525

Processing XML with Java     526

Processing XML with XOM     526

Creating an XML Document     528

Modifying an XML Document     532

Formatting an XML Document     536

Evaluating XOM     538

Summary     540

Q&A     541

Quiz     542

Questions     542

Certification Practice.      542

Exercises     543

20 XML Web Services     545

Introduction to XML-RPC     546

Communicating with XML-RPC     547

Sending a Request     548

Responding to a Request     549

Choosing an XML-RPC Implementation     550

Using an XML-RPC Web Service     552

Creating an XML-RPC Web Service     555

Summary     560

Q&A     561

Quiz     561

Questions     561

Certification Practice     562

Exercises     563

21 Writing Android Apps for Java     565

The History of Android     566

Writing an Android App     567

Organizing an Android Project     569

Creating the Program     570

Using an Android Emulator     573

Creating a Debug Configuration     574

Running the App     575

Designing an Android App     577

Preparing Resources     578

Configuring a Manifest File     582

Designing the Graphical User Interface     582

Writing Code     585

Summary     591

Q&A     591

Quiz     592

Questions     592

Certification Practice     592

Exercises     592

Appendixes     593

A Using the NetBeans Integrated Development Environment     595

B This Book’s Website     603

C Setting Up an Android Development Environment     605

D Using the Java Development Kit     613

E Programming with the Java Development Kit     635

Quiz Answers     659

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