Beginning Programming with Java® FOR DUMmIES ‰ 3RD EDITION Beginning Programming with Java® FOR DUMmIES ‰ 3RD EDITION by Barry Burd Author of Java For Dummies Beginning Programming with Java® For Dummies®, 3rd Edition Published by John Wiley & Sons, Inc 111 River Street Hoboken, NJ 07030-5774 www.wiley.com Copyright © 2012 by John Wiley & Sons, Inc., Hoboken, New Jersey Published by John Wiley & Sons, Inc., Hoboken, New Jersey 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 Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http:// www.wiley.com/go/permissions Trademarks: Wiley, the Wiley 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, Making Everything Easier, 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 registered trademark of Oracle America, Inc All other trademarks are the property of their respective owners John Wiley & Sons, Inc is not associated with any product or vendor mentioned in this book LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS 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 CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE 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 FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ For general information on our other products and services, please contact our Customer Care Department within the U.S at 877-762-2974, outside the U.S at 317-572-3993, or fax 317-572-4002 For technical support, please visit www.wiley.com/techsupport Wiley publishes in a variety of print and electronic formats and by print-on-demand Some material included with standard print versions of this book may not be included in e-books or in print-on-demand If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com For more information about Wiley products, visit www.wiley.com Library of Congress Control Number: 2012934909 ISBN 978-0-470-37174-9 (pbk); ISBN 978-1-118-22014-6 (ePDF); ISBN 978-1-118-23384-9 (ePub); ISBN 978-1-118-25852-1 (eMobi) Manufactured in the United States of America 10 About the Author Dr Barry Burd has an M.S in Computer Science from Rutgers University and a Ph.D in Mathematics from the University of Illinois As a teaching assistant in Champaign-Urbana, Illinois, he was elected five times to the universitywide 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 professional 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 Java For Dummies and Android Application Development All-in-One For Dummies, both published by John Wiley & Sons, Inc Dr Burd lives in Madison, New Jersey with his wife and two kids (both in their twenties, and mostly on their own) As an avid indoor enthusiast, Dr Burd enjoys sleeping, talking, and eating Dedication For Harriet, Sam and Jennie, Sam and Ruth, Abram and Katie, Benjamin and Jennie Author’s Acknowledgments Author’s To-Do List, February 13, 2012: Item: Send chocolate to Kelly Ewing — the book’s project editor and copy editor As anyone who reads Chapter learns, chocolate is one of the most precious commodities on earth So when I give chocolate, I give it thoughtfully and intentionally Item: Have a plaque erected in honor of Katie Feltman, your acquisitions editor at Wiley While you worked on other projects, Katie kept on insisting that you write this book’s third edition (Sure, you wanted a long vacation instead of another book project, but who cares? She was right; you were wrong.) Item: Send a thank-you note to tech editor John Mueller who helped polish your original work and, miraculously, didn’t make a lot of extra work for you Item: Recommend your agent Neil Salkind to other computer book authors If it weren’t for Neil, you’d still be roaming the book exhibits and looking needy at the technology conferences Item: Visit Frank Thornton, Bonnie Averbach, and Herbert Putz at Temple University Thank them for steering you to a career as a professor In any other career, you’d have no time left to write (And by the way, while you’re in Philly, don’t forget to stop for a cheesesteak.) Item: Send e-mail to Gaisi Takeuti at the University of Illinois, and to William Wisdom and Hughes LeBlanc at Temple University Thank them for teaching you about Symbolic Logic It’s made your life as a computer scientist and mathematician much richer Item: Spend more time with your family (Remind them that you’re the guy who wandered around the house before you started writing books.) Renew your pledge to clean up after yourself Don’t be so high-strung and finish each sentence that you start Remember that you can never fully return the love they’ve given you, but you should always keep trying Publisher’s Acknowledgments We’re proud of this book; please send us your comments at http://dummies.custhelp.com For other comments, please contact our Customer Care Department within the U.S at 877-762-2974, outside the U.S at 317-572-3993, or fax 317-572-4002 Some of the people who helped bring this book to market include the following: Acquisitions and Editorial Composition Services Project Editor: Kelly Ewing Project Coordinator: Sheree Montgomery Senior Acquisitions Editor: Katie Feltman Layout and Graphics: Carrie A Cesavice, Corrie Niehaus, Lavonne Roberts Technical Editor: John Mueller Editorial Manager: Jodi Jensen Editorial Assistant: Amanda Graham Sr Editorial Assistant: Cherie Case Proofreaders: ConText Editorial Services, Inc., Rebecca Denoncour Indexer: Infodex Indexing Services, Inc Cover Photo: © Javier Pierini / Jupiter Images Cartoons: Rich Tennant (www.the5thwave.com) Publishing and Editorial for Technology Dummies Richard Swadley, Vice President and Executive Group Publisher Andy Cummings, Vice President and Publisher Mary Bednarek, Executive Acquisitions Director Mary C Corder, Editorial Director Publishing for Consumer Dummies Kathleen Nebenhaus, Vice President and Executive Publisher Composition Services Debbie Stailey, Director of Composition Services Index description, 359–360 example, 371–372 Herst, David, 113 HIDE_ON_CLOSE parameter, 384 •I• IBM developerWorks, web link, 408 icons used in this book, 5–6 identifiers versus keywords, 112 predetermined, 76–78 user defined, 112–113 IDEs (integrated development environments), 19 See also Eclipse IDE if clauses, 175 if statements See also switch statements; while statements blocks, 185 boolean variables, 194–195 cascading, 202–204 compound statements, 174 conditions, combining, 189–191, 193–194 conditions, grouping, 197–199 description, 173–177 else clauses, 174, 181–184 enumerating outcomes, 205–208 error messages, 176 if clauses, 174 indenting, 179, 181 initializing variables, 191–192 logical operators, 188–189, 196–197 nesting, 199–202 sample code, 173 sample programs, 177–179, 183–185 versus while statements, 230 ImageIcon objects, 381–382 import declarations, 183–184, 186 increment operators, 138–141 incrementing numbers, 138–141 indenting code, 89, 113 if statements, 179, 181 nested if statements, 200–201 indexes of arrays, 312 infinite loops, 235–236 initializing variable values, 124–125 input, reading See reading input, searching, 98, 155–156 installing Java-related software Eclipse IDE, 37–38 Eclipse WindowBuilder, 385–386 juggling multiple versions, 33–35 online versus offline, 27 over existing software, avoiding, 29–33 prioritizing versions, 34–35 starting automatically, 27–28 uninstalling old versions, 33–35 instantiating classes, 393–394 int type minimum/maximum values, finding, 414 range of values, 145 versus String, 341–342 int type, converting to binary, 414 from character, 346–348, 414 to hexadecimal, 414 Integer class MAX_VALUE parameter, 414 MIN_VALUE parameter, 414 parseInt method, 346–348, 414 toBinaryString method, 414 toHexString method, 414 integrated development environments (IDEs), 19 See also Eclipse IDE iterations, 227 •J• Java Beginner Tutorial, web link, 408 The Java Boutique, web link, 408 Java Development Kit (JDK) downloading, 22, 26 versus JRE (Java Runtime Environment), 26 Java documentation See API documentation java file, 16 425 426 Beginning Programming with Java For Dummies, 3rd Edition Java language, portability, 17 Java program elements ; (semicolon), ending statements, 86 classes, 88 comments, 80–81 identifiers, 76–78 instructions to the computer, 85–88 keywords, 74–76 literals, 78–79 methods, 82–88 punctuation, 79–80 sample code, 72–73 statements, 86 variables, 115–119 Java programming toolset See tools Java Runtime Environment (JRE) configuring in Eclipse IDE, 42 downloading, 22, 26 Home field, configuring, 42 versus JDK (Java Development Kit), 26 Java Shareware, web link, 408 Java virtual machine (JVM) definition, 16 on your hard drive, checking for, 20 The java.blogs community, web link, 409 javac file, 13 javac.exe file, 13 Javadoc comments, converting to web pages, 81 Javadocs See API documentation java.exe file, 16 java.lang package, 351 The JavaRanch, web link, 408 java.util package, 350–351 JDK (Java Development Kit) downloading, 22, 26 versus JRE (Java Runtime Environment), 26 JFrame class definition, 381 description, 383–384 DISPOSE_ON_CLOSE parameter, 384 DO_NOTHING_ON_CLOSE parameter, 384 EXIT_ON_CLOSE parameter, 383 HIDE_ON_CLOSE parameter, 384 pack method, 384 setDefaultCloseOperation method, 383–384 setVisible method, 384 JLabel class, 382 job opportunities, web links, 409–410 JRE (Java Runtime Environment) configuring in Eclipse IDE, 42 downloading, 22, 26 Home field, configuring, 42 versus JDK (Java Development Kit), 26 JRoller, web link, 409 JVM (Java virtual machine) definition, 16 on your hard drive, checking for, 20 •K• keyboard input See reading, from the keyboard keyboard input, echoing See EchoLine program keywords case sensitivity, 75 definition, 74 versus identifiers, 112 list of, 75 predetermined meanings, 75–76 reserved words, 75 •L• Landscaping For Dummies, 355 The Language List, web link, 410 layout, Eclipse IDE, 67 layout, frames, 397 less than ([...]... Improving Your Code with Tutorials 408 Finding Help on Newsgroups 408 Reading Documentation with Commentary 408 Listen! 409 Opinions and Advocacy 409 Looking for Java Jobs 409 Finding Out More about Other Programming Languages 410 Everyone’s Favorite Sites 410 xvii xviii Beginning Programming with Java For Dummies, 3rd Edition Chapter 22:... visit www .dummies. com/go/beginningprogrammingwithjavafd Occasionally, we have updates to our technology books If this book does have technical updates, they will be posted at www .dummies. com/go/ beginningprogrammingwithjavafdupdates and at http://all mycode.com/BeginProg3 Part I Revving Up Y In this part ou have to eat before you can cook You have to wear before you can sew You have to ride before you... every technical book starts with a little typeface legend, and Beginning Programming with Java For Dummies, 3rd Edition is no exception What follows is a brief explanation of the typefaces used in this book: ✓ New terms are set in italics ✓ When I want you to type something short or perform a step, I use bold ✓ You’ll also see this computerese font I use the computerese font for Java code, filenames, web... Java s do statement 291 A closer look at the do statement 291 Repeating with Predetermined Values (Java s Enhanced for Statement) 293 Creating an enhanced for loop 293 Nesting the enhanced for loops 295 xv xvi Beginning Programming with Java For Dummies, 3rd Edition Part IV: Using Program Units 301 Chapter 16: Using Loops and Arrays 303... create solutions on your own I even get to tell a few funny stories 2 Beginning Programming with Java For Dummies, 3rd Edition How to Use This Book I wish I could say, “Open to a random page of this book and start writing Java code Just fill in the blanks and don’t look back.” In a sense, this is true You can’t break anything by writing Java code, so you’re always free to experiment But I have to be honest... Development Environment 35 Downloading Eclipse 35 Installing Eclipse 37 Running Eclipse for the first time 38 What’s Next? 46 xii Beginning Programming with Java For Dummies, 3rd Edition Chapter 3: Running Programs 47 Running a Canned Java Program 47 Typing and Running Your Own Code 52 Separating your programs from mine... momentary tangent 5 6 Beginning Programming with Java For Dummies, 3rd Edition Of course, in print, you can’t see me twisting my head I need some other way of setting a side thought in a corner by itself I do it with icons When you see a Tip icon or a Remember icon, you know that I’m taking a quick detour Here’s a list of icons that I use in this book: A tip is an extra piece of information — something... Comparing numbers; comparing characters 159 The Remaining Primitive Types 166 xiii xiv Beginning Programming with Java For Dummies, 3rd Edition Part III: Controlling the Flow 169 Chapter 9: Forks in the Road 171 Decisions, Decisions! 171 Making Decisions (Java if Statements) 173 Looking carefully at if statements 173 A complete program... and clicking your mouse 3 4 Beginning Programming with Java For Dummies, 3rd Edition On those rare occasions when you need to drag and drop, cut and paste, or plug and play, I guide you carefully through the steps But your computer may be configured in any of several billion ways, and my instructions may not quite fit your special situation So when you reach one of these platform-specific tasks, try following... Part of Tens is a little beginning programmer’s candy store In the Part of Tens, you can find lists — lists of tips, resources, and all kinds of interesting goodies I added an appendix on this book’s website to help you feel comfortable with Java s documentation I can’t write programs without my Java programming documentation In fact, no Java programmer can write programs without those all-important