Java ™ 2 FOR DUMmIES ‰ 2ND EDITION by Barry Burd 00a_568582_ffirs.qxd 7/27/04 11:38 PM Page iii Java 2 For Dummies , 2nd Edition Published by Wiley Publishing, Inc. 111 River Street Hoboken, NJ 07030-5774 Copyright © 2004 by Wiley Publishing, Inc., Indianapolis, Indiana Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, e-mail: brandreview@wiley.com. Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United States and other countries, and may not be used without written permission. Java is a trademark or regis- tered trademark of Sun Microsystems, Inc. in the United States and other countries. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. LIMIT OF LIABILITY/DISCLAIMER OF W ARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REP- RESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CRE- ATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CON- TAINED 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 FOR 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 FUR- THER 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 WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Library of Congress Control Number: 2004102602 ISBN: 0-7645-6858-2 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 2O/RY/QY/QU/IN 00a_568582_ffirs.qxd 7/27/04 11:38 PM Page iv About the Author Dr. Barry Burd received an M.S. degree in Computer Science at Rutgers University and a Ph.D. in Mathematics at the University of Illinois. As a teach- ing assistant in Champaign-Urbana, Illinois, he was elected five times to the university-wide List of Teachers Ranked as Excellent by Their Students. Since 1980, Dr. Burd has been a professor in the Department of Mathematics and Computer Science at Drew University in Madison, New Jersey. When he’s not lecturing at Drew University, Dr. Burd leads training courses for profes- sional programmers in business and industry. He has lectured at conferences in the United States, Europe, Australia, and Asia. He is the author of several articles and books, including JSP: JavaServer Pages and Beginning Programming with Java For Dummies, both from Wiley Publishing, Inc. Dr. Burd lives in Madison, New Jersey, with his wife and two children. In his spare time, he enjoys being a workaholic. 00a_568582_ffirs.qxd 7/27/04 11:38 PM Page v Dedication for Jennie, Sam, and Harriet, Ruth and Sam, Jennie and Benjamin, Katie and Abram, and Basheva Author’s Acknowledgments Thanks again! —Barry Burd 00a_568582_ffirs.qxd 7/27/04 11:38 PM Page vii Publisher’s Acknowledgments We’re proud of this book; please send us your comments through our online registration form located at www.dummies.com/register. Some of the people who helped bring this book to market include the following: Acquisitions, Editorial, and Media Development Project Editor: Paul Levesque Acquisitions Editor: Steve Hayes Copy Editor: Virginia Sanders Technical Editor: Wiley-Dreamtech India Pvt Ltd Editorial Manager: Kevin Kirschner Permissions Editor: Laura Moss Media Development Specialist: Angela Denny Media Development Manager: Laura VanWinkle Media Development Supervisor: Richard Graves Editorial Assistant: Amanda Foxworth Cartoons: Rich Tennant ( www.the5thwave.com) Composition Project Coordinator: Nancee Reeves Layout and Graphics: Denny Hager, Joyce Haughey, Michael Kruzil, Stephanie D. Jumper, Jacque Schneider Proofreaders: Andy Hollandbeck, Charles Spencer, TECHBOOKS Production Services Indexer: TECHBOOKS Production Services Publishing and Editorial for Technology Dummies Richard Swadley, Vice President and Executive Group Publisher Andy Cummings, Vice President and Publisher Mary Bednarek, Executive Editorial Director Mary C. Corder, Editorial Director Publishing for Consumer Dummies Diane Graves Steele, Vice President and Publisher Joyce Pepple, Acquisitions Director Composition Services Gerry Fahey, Vice President of Production Services Debbie Stailey, Director of Composition Services 00a_568582_ffirs.qxd 7/27/04 11:38 PM Page viii Contents at a Glance Introduction 1 Part I: Getting Started 9 Chapter 1: All about Java 11 Chapter 2: Running Canned Java Programs 23 Chapter 3: Using the Basic Building Blocks 43 Part II: Writing Your Own Java Programs 69 Chapter 4: Making the Most of Variables and Their Values 71 Chapter 5: Controlling Program Flow with Decision-Making Statements 99 Chapter 6: Controlling Program Flow with Loops 121 Part III: Working with the Big Picture: Object-Oriented Programming 139 Chapter 7: Thinking in Terms of Classes and Objects 141 Chapter 8: Saving Time and Money: Reusing Existing Code 169 Chapter 9: Constructing New Objects 199 Part IV: Savvy Java Techniques 219 Chapter 10: Putting Variables and Methods Where They Belong 221 Chapter 11: Using Arrays and Collections to Juggle Values 249 Chapter 12: Looking Good When Things Take Unexpected Turns 279 Part V: The Part of Tens 305 Chapter 13: Ten Ways to Avoid Mistakes 307 Chapter 14: Ten Sets of Web Resources for Java 313 Part VI: Appendixes 319 Appendix A: Using the CD-ROM 321 Appendix B: When to Use Words Like “public” and “private” 331 Index 341 End-User License Agreement 361 00b_568582_ftoc.qxd 7/28/04 12:37 AM Page ix Table of Contents Introduction 1 How to Use This Book 1 Conventions Used in This Book 1 What You Don’t Have to Read 2 Foolish Assumptions 3 How This Book Is Organized 4 Part I: Getting Started 4 Part II: Writing Your Own Java Programs 4 Part III: Working with the Big Picture: Object-Oriented Programming 4 Part IV: Savvy Java Techniques 5 Part V: The Part of Tens 5 Part VI: Appendixes 5 Bonus Chapters on the CD-ROM! 5 Icons Used in This Book 6 Where to Go from Here 7 Part I: Getting Started 9 Chapter 1: All about Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11 What You Can Do with Java 12 Why You Should Use Java 13 Getting Perspective: Where Java Fits In 14 Object-Oriented Programming (OOP) 15 Object-oriented languages 16 Objects and their classes 17 What’s so good about an object-oriented language? 18 Refining your understanding of classes and objects 20 What’s Next? 22 Chapter 2: Running Canned Java Programs . . . . . . . . . . . . . . . . . . . . .23 Downloading and Installing the Java Software Development Kit (SDK) 23 Downloading Java 25 Installing Java on your computer 27 Preparing to Use an Integrated Development Environment 30 JCreator 31 Running JCreator for the first time 31 00b_568582_ftoc.qxd 7/28/04 12:37 AM Page xi Running Java Programs 34 Running a text-based program 34 Running a GUI on its own 38 Running a GUI on a Web page (a Java applet) 39 Chapter 3: Using the Basic Building Blocks . . . . . . . . . . . . . . . . . . . . .43 Speaking the Java Language 43 The grammar and the common names 44 The words in a Java program 45 Checking Out Java Code for the First Time 48 Understanding the Simple Java Program 49 The Java class 49 The Java method 50 The main method in a program 52 How you finally tell the computer to do something 53 Curly braces 55 And Now, a Few Comments 58 Adding comments to your code 58 What’s Barry’s excuse? 61 Finding javadoc pages 61 Using comments to experiment with your code 62 Typing Your Own Code 64 Part II: Writing Your Own Java Programs 69 Chapter 4: Making the Most of Variables and Their Values . . . . . . . .71 Varying a Variable 71 Assignment Statements 73 Understanding the Types of Values That Variables May Have 74 An Import Declaration 77 Displaying Text 78 Numbers without Decimal Points 78 Combining Declarations and Initializing Variables 80 The Atoms: Java’s Primitive Types 81 The char type 82 The boolean type 84 The Molecules and Compounds: Reference Types 85 Creating New Values by Applying Operators 89 Initialize once, assign often 92 The increment and decrement operators 92 Assignment operators 96 Java 2 For Dummies, 2nd Edition xii 00b_568582_ftoc.qxd 7/28/04 12:37 AM Page xii Chapter 5: Controlling Program Flow with Decision-Making Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .99 Making Decisions (Java if Statements) 100 Guess the number 100 She controlled keystrokes from the keyboard 101 Creating randomness 102 The if statement 103 The double equal sign 104 Brace yourself 105 Indenting if statements in your code 105 Elseless in Ifrica 106 Forming Conditions with Comparisons and Logical Operators 107 Comparing numbers; comparing characters 107 Comparing objects 108 Importing everything in one fell swoop 111 Java’s logical operators 111 Building a Nest 113 Choosing among Many Alternatives (Java switch Statements) 115 Your basic switch statement 116 To break or not to break 119 Chapter 6: Controlling Program Flow with Loops . . . . . . . . . . . . . . . .121 Repeating Instructions Over and Over Again (Java while Statements) 122 Repeating a Certain Number of Times (Java for Statements) 125 The anatomy of a for statement 126 The world premiere of “Al’s All Wet” 128 Repeating Until You Get What You Want (Java do Statements) 129 Reading a single character 132 File handling in Java 133 Variable declarations and blocks 133 Loops Made Painless 134 Don’t need no stinking counters 134 Grouping things together 136 Anatomy of an enhanced for loop 137 Part III: Working with the Big Picture: Object-Oriented Programming 139 Chapter 7: Thinking in Terms of Classes and Objects . . . . . . . . . . . .141 Defining a Class (What It Means to Be an Account) 142 Declaring variables and creating objects 144 Initializing a variable 146 Using variables 146 xiii Table of Contents 00b_568582_ftoc.qxd 7/28/04 12:37 AM Page xiii Compiling and Running More Than One Class 147 Defining a Method within a Class (Displaying an Account) 148 An account that displays itself 150 The display method’s header 151 Sending Values to and from Methods (Calculating Interest) 152 Passing a value to a method 155 Returning a value from the getInterest method 156 Making numbers look good 158 Hiding Details with Accessor Methods (Why You Shouldn’t Micromanage a Bank Teller) 162 Good programming 162 Public lives and private dreams: Making a variable name inaccessible 165 Enforcing rules with accessor methods 167 Chapter 8: Saving Time and Money: Reusing Existing Code . . . . . .169 Defining a Class (What It Means to Be an Employee) 170 The last word on employees 170 Putting your class to good use 172 Cutting a check 173 Working with Disk Files (A Brief Detour) 174 Storing data in a file 175 Copying and pasting code 177 Reading from a file 178 Who moved my file? 180 Adding directory names to your filenames 181 Reading a line at a time 182 Defining Subclasses (What It Means to Be a Full-Time Employee or a Part-Time Employee) 183 Creating a subclass 185 Creating subclasses is habit-forming 188 Using Subclasses 189 A program for the minimalist 189 A program for the maximalist 192 Overriding Existing Methods (Changing the Payments for Some of Your Employees) 195 Chapter 9: Constructing New Objects . . . . . . . . . . . . . . . . . . . . . . . . .199 Defining Constructors (What It Means to Be a Temperature) 200 What is a temperature? 200 What you can do with a temperature 202 Calling new Temperature (32.0): A case study 203 enum types as first-class citizens 206 Some things never change 207 Java 2 For Dummies, 2nd Edition xiv 00b_568582_ftoc.qxd 7/28/04 12:37 AM Page xiv [...]... xvi Java 2 For Dummies, 2nd Edition Command Line Arguments 26 7 Using command line arguments in a Java program 26 7 Checking for the right number of command line arguments .26 9 Setting up JCreator for command line arguments 27 0 Using Java Collections 27 3 Collection classes to the rescue 27 4 Using an ArrayList .27 5 Using generics (hot stuff!) 27 7 Testing for. .. Baseball Player) .22 2 Another way to beautify your numbers 22 3 Using the Player class .22 3 Nine, count ’em, nine 22 5 Don’t get all GUI on me .22 6 Tossing an exception from method to method .22 7 Making Static (Finding the Team Average) 22 8 Why is there so much static? 23 0 Displaying the overall team average .23 1 Static is old hat 23 3 Could cause... which I created just for comments and questions about this book, is Java2 ForDummies@ BurdBrain.com And don’t forget — for the latest updates, visit one of this book’s support Web sites The support sites’ addresses are www.BurdBrain com and www .dummies. com/go /java2 _fd 7 8 Java 2 For Dummies, 2nd Edition Part I Getting Started B In this part ecome acquainted with Java Find out what Java is all about,... appendix summarizes some important rules for writing Java programs To find out which parts of your code spill over automatically into other peoples’ code, read the second appendix Bonus Chapters on the CD-ROM! You’ve read the Java 2 For Dummies book, seen the Java 2 For Dummies movie, worn the Java 2 For Dummies T-shirt, and eaten the Java 2 For Dummies candy What more is there to do? That’s easy Just... 24 9 Creating an array in two easy steps 25 1 Storing values 25 2 Tab stops and other special things 25 5 Using an array initializer 25 5 Stepping through an array with the enhanced for loop .25 6 Searching 25 7 Arrays of Objects 26 1 Using the Room class 26 2 Yet another way to beautify your numbers 26 5 The conditional operator 26 6... technical book starts with a little typeface legend, and Java 2 For Dummies, 2nd Edition, is no exception What follows is a brief explanation of the typefaces used in this book: 2 Java 2 For Dummies, 2nd Edition ߜ New terms are set in italics ߜ If you need to type something that’s mixed in with the regular text, the characters you type appear in bold For example: “Type MyNewProject in the text field.” ߜ... the Weather) 20 8 Building better temperatures 20 8 Constructors for subclasses 21 0 Using all this stuff 21 1 The default constructor 21 2 An invisible constructor call 21 4 A Constructor That Does More 21 5 Part IV: Savvy Java Techniques 21 9 Chapter 10: Putting Variables and Methods Where They Belong 22 1 Defining a... care 23 4 Experiments with Variables .23 5 Putting a variable in its place 23 6 Telling a variable where to go 23 8 Passing Parameters .24 1 Pass by value .24 1 Returning a result 24 3 Pass by reference 24 4 Returning an object from a method 24 6 Epilogue 24 7 Chapter 11: Using Arrays and Collections to Juggle Values 24 9 Getting... when it’s written in Java: import static java. lang.System.out; class PayBarry { public static void main(String args[]) { Chapter 1: All about Java double checkAmount = 125 7.63; out.print(“Pay to the order of “); out.print(“Dr Barry Burd “); out.print(“$”); out.println(checkAmount); } } Why You Should Use Java It’s time to celebrate! You’ve just picked up a copy of Java 2 For Dummies, 2nd Edition, and you’re... This Book 325 Freeware, Shareware, and Just Plain Ware . 326 JCreator 326 Adobe Acrobat Reader . 327 Jindent 327 NetCaptor 328 WinOne . 328 And, If You Run into Any Trouble 328 Appendix B: When to Use Words Like “public” and “private” 331 Members versus Classes 331 Access Modifiers for Members 3 32 Default access . Chapters on the CD-ROM! You’ve read the Java 2 For Dummies book, seen the Java 2 For Dummies movie, worn the Java 2 For Dummies T-shirt, and eaten the Java 2 For Dummies candy. What more is there to. Java ™ 2 FOR DUMmIES ‰ 2ND EDITION by Barry Burd 00a_5685 82_ ffirs.qxd 7 /27 /04 11:38 PM Page iii Java 2 For Dummies , 2nd Edition Published by Wiley Publishing,. the FAQs for Useful Info 315 Opinions and Advocacy 315 Java 2 For Dummies, 2nd Edition xvi 00b_5685 82_ ftoc.qxd 7 /28 /04 12: 37 AM Page xvi Looking for Java Jobs 315 Becoming Certified in Java 316 Developing