Barry Burd, PhD, is a Computer Science professor at Drew University where he has been named to Drew’s “List of Teachers Ranked as Excellent by Students” five times. Barry is the author of numerous For Dummies books and writes frequently for several online publications, including JavaBoutique.com. Cover Image: ©ZoneCreative/iStockphoto.com Visit the companion website at www.dummies.com/go/ javafordummies6e for all the code from the book and additional material Go to Dummies.com ® for videos, step-by-step examples, how-to articles, or to shop! Open the book and find: •Definitions of terms associated with Java •Java syntax and an object-oriented programming overview •How to save time and effort by reusing code •All about if, for, switch, and while statements •The enhanced multimedia capabilities of Java 8 •Updates for Android and other new tools •How to write Java applets •Tips to avoid common mistakes $29.99 USA / $35.99 CAN / £21.99 UK 9 781118 407806 52999 ISBN:978-1-118-40780-6 Computers/Programming Languages/Java Jump into Java! The bestselling Java book for beginners is now fully updated for Java 8 Java is everywhere, runs on almost any computer, and is the engine that drives the coolest applications. If you’ve always wanted to learn Java, Java For Dummies is your ticket to Java success! Featuring updates on Java 8, this hands-on guide is written in an easy-to-read manner and is the perfect resource to get you running with Java in a jiffy! •TheJavascoop—getanoverviewofJava,featuringnewtools andenhancementsinJava8,includingnewlibraries,parallel frameworks,andmore •Buildingblocks—findouthowtoworkwithJavaclasses andmethods •Getloopy—understandthevalueofvariablesandlearnto controlprogramflowwithloopsordecision-makingstatements •Stayclassy—exploreclassesandobjects,constructors, andsubclasses,andfindouthowtoreusecode •Aclickahead—jumpintovariables,usearraysandcollections, andcreateprogramsthatrespondtomouseclicks Java ® Burd 6th Edition Barry Burd, PhD Author of Beginning Programming with Java For Dummies® Learnto: • Combine several smaller programs to create a bigger program • Use new features and tools in Java 8 • Create basic Java objects and reuse code • Handle exceptions and events Java ® 6th Ed ition Making E verything E asier! ™ www.it-ebooks.info www.facebook.com/fordummies www.twitter.com/fordummies From eLearning to e-books, test prep to test banks, language learning to video training, mobile apps, and more, Dummies makes learning easier. At home, at work, or on the go, Dummies is here to help you go digital! Start with FREE Cheat Sheets Cheat Sheets include •Checklists •Charts •CommonInstructions •AndOtherGoodStuff! Get Smart at Dummies.com Dummies.com makes your life easier with 1,000s of answers on everything from removing wallpaper to using the latest version of Windows. Check out our •Videos •IllustratedArticles •Step-by-StepInstructions Plus, each month you can win valuable prizes by entering our Dummies.com sweepstakes. * Want a weekly dose of Dummies? Sign up for Newsletters on •DigitalPhotography •MicrosoftWindows&Office •PersonalFinance&Investing •Health&Wellness •Computing,iPods&CellPhones •eBay •Internet •Food,Home&Garden Find out “HOW” at Dummies.com *Sweepstakes not currently available in all countries; visit Dummies.com for official rules. Get More and Do More at Dummies.com ® To access the Cheat Sheet created specifically for this book, go to www.dummies.com/cheatsheet/java www.it-ebooks.info Java ® 6th Edition by Barry Burd, PhD www.it-ebooks.info Java ® For Dummies ® , 6th Edition Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com Copyright © 2014 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 the prior written permission of the Publisher. 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, For Dummies, the Dummies Man logo, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and may not be used without written permission. Java is a registered trademark of Oracle America, Inc. All other trade- marks 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: 2013954105 ISBN 978-1-118-40780-6 (pbk); ISBN 978-1-118-41764-5 (ebk); ISBN 978-1-118-46103-7 (ebk); 978-1-118-61285-9 (ebk) Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 www.it-ebooks.info Contents at a Glance Introduction 1 Part I: Getting Started with Java 7 Chapter 1: All about Java 9 Chapter 2: All about Software 21 Chapter 3: Using the Basic Building Blocks 37 Part II: Writing Your Own Java Programs 59 Chapter 4: Making the Most of Variables and Their Values 61 Chapter 5: Controlling Program Flow with Decision-Making Statements 91 Chapter 6: Controlling Program Flow with Loops 121 Part III: Working with the Big Picture: Object-Oriented Programming 137 Chapter 7: Thinking in Terms of Classes and Objects 139 Chapter 8: Saving T ime and Money: Reusing Existing Code 165 Chapter 9: Constructing New Objects 193 Part IV: Savvy Java Techniques 215 Chapter 10: Putting Variables and Methods Where They Belong 217 Chapter 11: Using Arrays to Juggle Values 245 Chapter 12: Using Collections and Streams (When Arrays Aren’t Good Enough) 271 Chapter 13: Looking Good When Things Take Unexpected Turns 299 Chapter 14: Sharing Names among the Parts of a Java Program 327 Chapter 15: Responding to Keystrokes and Mouse Clicks 349 Chapter 16: Writing Java Applets 367 Chapter 17: Using Java Database Connectivity 377 Part V: The Part of Tens 385 Chapter 18: Ten Ways to Avoid Mistakes 387 Chapter 19: Ten Websites for Java 393 Index 395 www.it-ebooks.info www.it-ebooks.info Table of Contents Introduction 1 How toUse This Book 1 Conventions Used inThis Book 1 What You Don’t Have toRead 2 Foolish Assumptions 3 How This Book Is Organized 4 Part I: Getting Started withJava 4 Part II: Writing Your Own Java Program 4 Part III: Working withthe Big Picture: Object-Oriented Programming 4 Part IV: Savvy Java Techniques 5 Part V: The Part ofTens 5 Icons Used inThis Book 5 Beyond theBook 6 Where toGo fromHere 6 Part I: Getting Started with Java 7 Chapter 1: All about Java 9 What You Can Do withJava 10 Why You Should Use Java 11 Getting Perspective: Where Java Fits In 11 Object-Oriented Programming (OOP) 13 Object-oriented languages 14 Objects and their classes 14 What’s so good aboutan object-oriented language? 16 Refining your understanding ofclasses and objects 18 What’s Next? 20 Chapter 2: All about Software 21 Quick-Start Instructions 21 What You Install onYour Computer 23 What is a compiler? 24 What is a Java Virtual Machine? 26 Developing software 32 What is anIntegrated Development Environment? 33 www.it-ebooks.info Java For Dummies, 6th Edition vi Chapter 3: Using the Basic Building Blocks 37 Speaking theJava Language 37 The grammar and thecommon names 38 The words ina Java program 39 Checking Out Java Code forthe First Time 41 Understanding a Simple Java Program 42 The Java class 43 The Java method 44 The main method ina program 46 How you finally tell thecomputer todo something 47 Curly braces 50 And Now, a Few Comments 52 Adding comments toyour code 53 What’s Barry’s excuse? 56 Using comments toexperiment withyour code 56 Part II: Writing Your Own Java Programs 59 Chapter 4: Making the Most of Variables and Their Values 61 Varying a Variable 61 Assignment Statements 63 Understanding theTypes ofValues ThatVariables May Have 64 Displaying Text 68 Numbers withoutDecimal Points 68 Combining Declarations and Initializing Variables 70 The Atoms: Java’s Primitive Types 71 The char type 72 The boolean type 74 The Molecules and Compounds: Reference Types 75 An Import Declaration 79 Creating New Values by Applying Operators 81 Initialize once, assign often 84 The increment and decrement operators 84 Assignment operators 88 Chapter 5: Controlling Program Flow with Decision-Making Statements 91 Making Decisions (Java if Statements) 92 Guess thenumber 92 She controlled keystrokes fromthe keyboard 93 Creating randomness 96 The if statement 96 The double equal sign 97 Brace yourself 98 Indenting if statements inyour code 99 Elseless inIfrica 99 www.it-ebooks.info vii Table of Contents Forming Conditions withComparisons and Logical Operators 101 Comparing numbers; comparing characters 101 Comparing objects 102 Importing everything inone fell swoop 104 Java’s logical operators 105 Vive les nuls! 108 (Conditions inparentheses) 109 Building a Nest 111 Choosing amongMany Alternatives (Java switch Statements) 113 Your basic switch statement 113 To break or not tobreak 116 The new and improved switch 118 Chapter 6: Controlling Program Flow with Loops 121 Repeating Instructions Over and Over Again (Java while Statements) 122 Repeating a Certain Number ofTimes (Java forStatements) 125 The anatomy ofa forstatement 127 The world premiere of“Al’s All Wet” 127 Repeating Until You Get What You Want (Java do Statements) 129 Reading a single character 132 File handling inJava 133 Variable declarations and blocks 134 Part III: Working with the Big Picture: Object-Oriented Programming 137 Chapter 7: Thinking in Terms of Classes and Objects 139 Defining a Class (What It Means toBe anAccount) 139 Declaring variables and creating objects 141 Initializing a variable 144 Using anobject’s fields 144 One program; several classes 145 Public classes 145 Defining a Method withina Class (Displaying anAccount) 146 An account that displays itself 147 The display method’s header 148 Sending Values toand fromMethods (Calculating Interest) 149 Passing a value toa method 152 Returning a value fromthe getInterest method 154 Making Numbers Look Good 156 Hiding Details withAccessor Methods 159 Good programming 160 Public lives and private dreams: Making a field inaccessible 162 Enforcing rules withaccessor methods 164 www.it-ebooks.info Java For Dummies, 6th Edition viii Chapter 8: Saving T ime and Money: Reusing Existing Code 165 Defining a Class (What It Means toBe anEmployee) 166 The last word onemployees 166 Putting your class togood use 168 Cutting a check 169 Working withDisk Files (A Brief Detour) 170 Storing data ina file 171 Copying and pasting code 172 Reading froma file 173 Who moved my file? 175 Adding directory names toyour filenames 176 Reading a line ata time 177 Closing theconnection toa disk file 179 Defining Subclasses (What It Means to Be a Full-Time or Part-Time Employee) 179 Creating a subclass 181 Creating subclasses is habit-forming 183 Using Subclasses 184 Making types match 186 The second half ofthe story 187 Overriding Existing Methods (Changing thePayments for Some Employees) 188 A Java annotation 190 Using methods fromclasses and subclasses 190 Chapter 9: Constructing New Objects 193 Defining Constructors (What It Means toBe a Temperature) 194 What is a temperature? 194 What is a temperature scale? (Java’s enum type) 195 Okay, so then what is a temperature? 196 What you can do witha temperature 197 Calling new Temperature(32.0): A case study 200 Some things never change 202 More Subclasses (Doing Something aboutthe Weather) 203 Building better temperatures 203 Constructors forsubclasses 205 Using all this stuff 206 The default constructor 207 A Constructor ThatDoes More 209 Classes and methods fromthe Java API 212 The SuppressWarnings annotation 213 www.it-ebooks.info [...]... book starts with a little typeface legend, and Java For Dummies, 6th Edition, is no exception What follows is a brief explanation of the typefaces used in this book: www.it-ebooks.info 2 Java For Dummies, 6th 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.”... xii Java For Dummies, 6th Edition Fixing Non-Static References 390 Staying within Bounds in an Array 390 Anticipating Null Pointers 390 Helping Java Find Its Files 391 Chapter 19: Ten Websites for Java 393 This Book’s Website 393 The Horse’s Mouth 393 Finding News, Reviews, and Sample Code 394 Looking for Java. .. features come directly from features in Java www.it-ebooks.info Chapter 1: All about Java ✓ June 2004: Sys-Con Media reports that the demand for Java programmers tops the demand for C++ programmers by 50 percent (http:// java. sys-con.com/node/48507) And there’s more! The demand for Java programmers beats the combined demand for C++ and C# programmers by 8 percent Java programmers are more employable... tools you need for developing Java programs ✓ Find out how Java fits into today’s technology scene ✓ See your first complete Java program www.it-ebooks.info Chapter 1 All about Java In This Chapter ▶ What Java is ▶ Where Java came from ▶ Why Java is so cool ▶ How to orient yourself to object-oriented programming S ay what you want about computers As far as I’m concerned, computers are good for just two... programs for a living, start with Chapters 2, 3, and 4 but just skim Chapters 5 and 6 ✓ If you write C++ programs for a living, glance at Chapters 2 and 3, skim Chapters 4 through 6, and start reading seriously in Chapter 7 (Java is a bit different from C++ in the way it handles classes and objects.) ✓ If you write Java programs for a living, come to my house and help me write Java For Dummies, 7th Edition. .. ava is good stuff I’ve been using it for years I like Java because it’s very orderly Almost everything follows simple rules The rules can seem intimidating at times, but this book is here to help you figure them out So, if you want to use Java and want an alternative to the traditional techie, soft-cover book, sit down, relax, and start reading Java For Dummies, 6th Edition How to Use This Book I wish... written in Java: public class PayBarry { public static void main(String args[]) { } } double checkAmount = 1257.63; System.out.print("Pay to the order of "); System.out.print("Dr Barry Burd "); System.out.print("$"); System.out.println(checkAmount); www.it-ebooks.info Chapter 1: All about Java Why You Should Use Java It’s time to celebrate! You’ve just picked up a copy of Java For Dummies, 6th Edition, ... about this book, is JavaForDummies@ allmycode.com If e-mail and chat aren’t your favorites, you can reach me instead on Twitter (@allmycode) and on Facebook (www.facebook.com/ allmycode) And don’t forget — for the latest updates, visit this book’s website The site’s address is www.allmycode.com/JavaForDummies www.it-ebooks.info Part I Getting Started with Java Visit www.dummies.com for more great content... next chapter can’t wait for you to read it www.it-ebooks.info Chapter 2 All about Software In This Chapter ▶ Understanding the roles of the software development tools ▶ Selecting the version of Java that’s right for you ▶ Preparing to write and run Java programs T he best way to get to know Java is to do Java When you’re doing Java, you’re writing, testing, and running your own Java programs This chapter... www.oracle.com/technetwork /java/ javase/ downloads Follow the instructions at that website to download and install the Java SE documentation (also known as the Javadoc pages or the Java SE API Docs) 3 Visit Eclipse.org Follow the instructions at http://eclipse.org/downloads to download and install Eclipse Eclipse’s download page offers several different packages, including Eclipse Classic, Eclipse for Java EE, Eclipse for . typeface legend, and Java For Dummies, 6th Edition, is no exception. What follows is a brief explanation of the typefaces used in this book: www.it-ebooks.info 2 Java For Dummies, 6th Edition ✓ New. 265 Using command line arguments ina Java program 266 Checking for the right number ofcommand line arguments 268 www.it-ebooks.info Java For Dummies, 6th Edition x Chapter 12: Using Collections. 407806 52999 ISBN:978-1-118-40780-6 Computers/Programming Languages /Java Jump into Java! The bestselling Java book for beginners is now fully updated for Java 8 Java is everywhere, runs on almost any computer,