g nd win es DAY 7Exceptions,Assertions,aThreads DAY 14Developing SApplications DAY 21Writing JavaServlets andJava ServerPages Where to Gofrom Here: Java Resourc d n DAY 6Packages,Interfaces,aOther ClassFeatures DAY 13Using Color,Fonts,andGraphics DAY 20XML WebServices RegularExpressions s e s o DAY 5Creating Clasand Methods DAY 12Responding tUser Input DAY 19Reading andWriting RSSFeeds CD Writing JavaApplets n o 21 Days DAY 4Lists,Logic,andLoops DAY 11ArrangingComponents ona User Interface DAY 18AccessingDatabases withJDBC Bonus Lessons Choosing Java n i g n g ava6 DAY 3Working withObjects DAY 10Building a SwiInterface DAY 17CommunicatinAcross theInternet APPENDIX CThis Book's Web Site J hYourself a Language DAY 2The ABCs ofProgramming a Class Library DAY 9Working withSwing ogramming DAY 16Serializing andExaminingObjects APPENDIX BProgrammingwith the JavaDevelopment Kit c v v r TeaSams The JaWEEK 1: DAY 1Getting Started with Java The JaWEEK 2: DAY 8Data Structures Java PWEEK 3: DAY 15Working withInput and Output Appendixes APPENDIX AUsing the JavaDevelopment Kit Rogers Cadenhead Laura Lemay SamsTeachYourself Java 6 ™ in 21 Days 800 East 96th Street,Indianapolis,Indiana 46240 Sams Teach Yourself Java™ 6 in 21 Days Acquisitions Editor Mark Taber Copyright © 2007 by Sams Publishing Development Editor All rights reserved. No part of this book shall be reproduced,stored in a retrieval system,or transmit- Songlin Qiu ted by any means,electronic,mechanical,photocopying,recording,or otherwise,without written per- mission from the publisher. No patent liability is assumed with respect to the use of the information Managing Editor contained herein. Although every precaution has been taken in the preparation of this book,the pub- Patrick Kanouse lisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for Project Editor damages resulting from the use of the information contained herein. Mandie Frank International Standard Book Number-10:0-672-32943-3 Copy Editor International Standard Book Number-13:978-0-672-32943-2 Karen Annett Printed in the United States of America Indexer Fifth Printing:February 2009 WordWise Publishing Services,LLC Trademarks Proofreader All terms mentioned in this book that are known to be trademarks or service marks have been appro- Language Logistics, priately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term LLC in this book should not be regarded as affecting the validity of any trademark or service mark. Technical Editor Warning and Disclaimer Adam DeFields Every effort has been made to make this book as complete and as accurate as possible,but no war- Publishing ranty or fitness is implied. The information provided is on an “as is”basis. The author(s) and the pub- Coordinator lisher shall have neither liability nor responsibility to any person or entity with respect to any loss or Vanessa Evans damages arising from the information contained in this book or from the use of the CD or programs Multimedia accompanying it. Developer Bulk Sales Dan Scherf Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases Designer or special sales. For more information,please contact Gary Adair U.S. Corporate and Government Sales Page Layout 1-800-382-3419 Bronkella Publishing, [email protected] LLC For sales outside of the U.S.,please contact International Sales [email protected] This Book Is Safari Enabled The Safari®Enabled icon on the cover of your favorite technology book means the book is available through Safari Bookshelf. When you buy this book,you get free access to the online edition for 45 days. Safari Bookshelf is an electronic reference library that lets you easily search thousands of technical books,find code samples,download chapters,and access technical information whenever and wher- ever you need it. To gain 45-day Safari Enabled access to this book: • Go to http://www.samspublishing.com/safarienabled • Complete the brief registration form • Enter the coupon code A5JY-68DK-VC48-EBKX-NERB If you have difficulty registering on Safari Bookshelf or accessing the online edition,please e-mail [email protected]. Library of Congress Cataloging-in-Publication Data Cadenhead,Rogers. Sams teach yourself Java 6 in 21 days / Rogers Cadenhead,Laura Lemay. p. cm. Includes index. ISBN 978-0-672-32943-2 (pbk. w/cd) 1. Java (Computer program language) I. Lemay,Laura. II. Title. QA76.73.J38C333 2007 005.13'3--dc22 2007014568 Contents at a Glance Introduction 1 WEEK I: The Java Language 1 Getting Started with Java 9 2 The ABCs of Programming 35 3 Working with Objects 63 4 Lists,Logic,and Loops 89 5 Creating Classes and Methods 115 6 Packages,Interfaces,and Other Class Features 145 7 Exceptions,Assertions,and Threads 183 WEEK II: The Java Class Library 8 Data Structures 219 9 Working with Swing 247 10 Building a Swing Interface 273 11 Arranging Components on a User Interface 303 12 Responding to User Input 333 13 Using Color,Fonts,and Graphics 357 14 Developing Swing Applications 381 WEEK III: Java Programming 15 Working with Input and Output 405 16 Serializing and Examining Objects 433 17 Communicating Across the Internet 453 18 Accessing Databases with JDBC 485 19 Reading and Writing RSS Feeds 511 20 XML Web Services 535 21 Writing Java Servlets and Java Server Pages 555 Appendixes A Using the Java Development Kit 601 B Programming with the Java Development Kit 625 C This Book’s Web Site 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 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 Usingnew..................................................................................................64 WhatnewDoes ..........................................................................................66 A Note on Memory Management ..................................................................66 vi Sams Teach Yourself Java 6 in 21 Days 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 ifConditionals ..................................................................................................97 switchConditionals ............................................................................................98 forLoops ........................................................................................................104 Contents vii whileanddoLoops ..........................................................................................107 whileLoops............................................................................................107 do-whileLoops ......................................................................................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 ThethisKeyword....................................................................................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 viii Sams Teach Yourself Java 6 in 21 Days 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 TheimportDeclaration ............................................................................159 Class Name Conflicts ................................................................................160 A Note About Classpathand 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