Transcription of Java® For Dummies®, 7th Edition
1 Java For Dummies , 7th EditionPublished by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ07030-5774, 2017 by John Wiley & Sons, Inc., Hoboken, New JerseyPublished simultaneously in CanadaNo part of this publication may be reproduced, stored in a retrieval system ortransmitted in any form or by any means, electronic, mechanical,photocopying, recording, scanning or otherwise, except as permitted underSections 107 or 108 of the 1976 United States Copyright Act, without theprior written permission of the Publisher. Requests to the Publisher forpermission 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 : Wiley, For Dummies, the Dummies Man logo, ,Making Everything Easier, and related trade dress are trademarks orregistered trademarks of John Wiley & Sons, Inc. and may not be usedwithout written permission. Java is a registered trademark of Oracle America,Inc.
2 Android is a registered trademark of Google, Inc. All other trademarksare the property of their respective owners. John Wiley & Sons, Inc. is notassociated with any product or vendor mentioned in this OF LIABILITY/DISCLAIMER OF WARRANTY: THEPUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS ORWARRANTIES WITH RESPECT TO THE ACCURACY ORCOMPLETENESS OF THE CONTENTS OF THIS WORK ANDSPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDINGWITHOUT LIMITATION WARRANTIES OF FITNESS FOR APARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OREXTENDED BY SALES OR PROMOTIONAL MATERIALS. THEADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BESUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITHTHE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGEDIN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONALSERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THESERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BESOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BELIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT ANORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK ASA CITATION AND/OR A POTENTIAL SOURCE OF FURTHERINFORMATION DOES NOT MEAN THAT THE AUTHOR OR THEPUBLISHER ENDORSES THE INFORMATION THE ORGANIZATIONOR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAYMAKE.
3 FURTHER, READERS SHOULD BE AWARE THAT INTERNETWEBSITES LISTED IN THIS WORK MAY HAVE CHANGED ORDISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN ANDWHEN IT IS general information on our other products and services, please contactour Customer Care Department within the at 877-762-2974, outside at 317-572-3993, or fax 317-572-4002. For technical support, pleasevisit publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this bookmay not be included in e-books or in print-on-demand. If this book refers tomedia such as a CD or DVD that is not included in the version youpurchased, you may download this material For more information about Wileyproducts, visit of Congress Control Number: 2017932837 ISBN: 978-1-119-23555-2; 978-1-119-23558-3 (ebk); 978-1-119-23557-6(ebk)Java For Dummies To view this book's Cheat Sheet, simply go and search for Java ForDummies Cheat Sheet in the Search of ContentsCoverIntroductionHow to Use This BookConventions Used in This BookWhat You Don t Have to ReadFoolish AssumptionsHow This Book Is OrganizedIcons Used in This BookBeyond the BookWhere to Go from HerePart 1: Getting Started with JavaChapter 1: All about JavaWhat You Can Do with JavaWhy You Should Use JavaGetting Perspective: Where Java Fits InObject-Oriented Programming (OOP)What s Next?
4 Chapter 2: All about SoftwareQuick-Start InstructionsWhat You Install on Your ComputerChapter 3: Using the Basic Building BlocksSpeaking the Java LanguageChecking Out Java Code for the First TimeUnderstanding a Simple Java ProgramAnd Now, a Few CommentsPart 2: Writing Your Own Java ProgramsChapter 4: Making the Most of Variables and TheirValuesVarying a VariableExperimenting with JShellWhat Happened to All the Cool Visual Effects?The Atoms: Java s Primitive TypesThe Molecules and Compounds: Reference TypesAn Import DeclarationCreating New Values by Applying OperatorsChapter 5: Controlling Program Flow with Decision-Making StatementsMaking Decisions (Java if Statements)Using Blocks in JShellForming Conditions with Comparisons and Logical OperatorsBuilding a NestChoosing among Many Alternatives (Java switch Statements)Chapter 6: Controlling Program Flow with LoopsRepeating Instructions Over and Over Again (Java while Statements)Repeating a Certain Number of Times (Java for Statements)Repeating until You Get What You Want (Java do Statements)Part 3: Working with the Big Picture: object -OrientedProgrammingChapter 7.
5 Thinking in Terms of Classes and ObjectsDefining a Class (What It Means to Be an Account)Defining a Method within a Class (Displaying an Account)Sending Values to and from Methods (Calculating Interest)Making Numbers Look GoodHiding Details with Accessor MethodsBarry s Own GUI ClassChapter 8: Saving Time and Money: Reusing ExistingCodeDefining a Class (What It Means to Be an Employee)Working with Disk Files (a Brief Detour)Defining Subclasses (What It Means to Be a Full-Time or Part-TimeEmployee)Using SubclassesOverriding Existing Methods (Changing the Payments for SomeEmployees)Chapter 9: Constructing New ObjectsDefining Constructors (What It Means to Be a Temperature)More Subclasses (Doing Something about the Weather)A Constructor That Does MorePart 4: Smart Java TechniquesChapter 10: Putting Variables and Methods Where TheyBelongDefining a Class (What It Means to Be a Baseball Player)Making Static (Finding the Team Average)Experiments with VariablesPassing ParametersChapter 11: Using Arrays to Juggle ValuesGetting Your Ducks All in a RowArrays of ObjectsCommand Line ArgumentsChapter 12: Using Collections and Streams (WhenArrays Aren t Good Enough)Understanding the Limitations of ArraysCollection Classes to the RescueFunctional ProgrammingChapter 13: Looking Good When Things TakeUnexpected TurnsHandling ExceptionsHandle an Exception or Pass the BuckFinishing the Job with a finally ClauseA try Statement with ResourcesChapter 14: Sharing Names among the Parts of a JavaProgramAccess ModifiersClasses, Access, and Multipart ProgramsSneaking Away from the Original CodeProtected AccessAccess Modifiers for Java ClassesChapter 15: Fancy Reference TypesJava s TypesThe Java InterfaceAbstract ClassesRelax!
6 You re Not Seeing Double!Chapter 16: Responding to Keystrokes and MouseClicksGo On .. Click That ButtonResponding to Things Other Than Button ClicksCreating Inner ClassesChapter 17: Using Java Database ConnectivityCreating a Database and a TablePutting Data in the TableRetrieving DataDestroying DataPart 5: The Part of TensChapter 18: Ten Ways to Avoid MistakesPutting Capital Letters Where They BelongBreaking Out of a switch StatementComparing Values with a Double Equal SignAdding Components to a GUIA dding Listeners to Handle EventsDefining the Required ConstructorsFixing Non-Static ReferencesStaying within Bounds in an ArrayAnticipating Null PointersHelping Java Find Its FilesChapter 19: Ten Websites for JavaThis Book s WebsiteThe Horse s MouthFinding News, Reviews, and Sample CodeGot a Technical Question?About the AuthorConnect with DummiesEnd User License AgreementIntroductionJava is good stuff. I ve been using it for years. I like Java because it s everything follows simple rules.
7 The rules can seem intimidating attimes, but this book is here to help you figure them out. So, if you want to useJava and you want an alternative to the traditional techie, soft-cover book, sitdown, relax, and start reading Java For Dummies, 7th to Use This BookI wish I could say, Open to a random page of this book and start writing Javacode. Just fill in the blanks and don t look back. In a sense, this is true. Youcan t break anything by writing Java code, so you re always free let me be honest. If you don t understand the bigger picture, writing aprogram is difficult. That s true with any computer programming language not just Java. If you re typing code without knowing what it s about and thecode doesn t do exactly what you want it to do, you re just plain this book, I divide Java programming into manageable chunks. Each chunkis (more or less) a chapter. You can jump in anywhere you want Chapter 5,Chapter 10, or wherever. You can even start by poking around in the middleof a chapter.
8 I ve tried to make the examples interesting without making onechapter depend on another. When I use an important idea from anotherchapter, I include a note to help you find your way general, my advice is as follows:If you already know something, don t bother reading about you re curious, don t be afraid to skip ahead. You can always sneak apeek at an earlier chapter, if you really need to do Used in This BookAlmost every technical book starts with a little typeface legend, and Java ForDummies, 7th Edition , is no exception. What follows is a brief explanation ofthe typefaces used in this book:New terms are set in you need to type something that s mixed in with the regular text, thecharacters you type appear in bold. For example: Type MyNewProjectin the text field. You also see this computerese font. I use computerese for Java code,filenames, web page addresses (URLs), onscreen messages, and othersuch things. Also, if something you need to type is really long, it appearsin computerese font on its own line (or lines).
9 You need to change certain things when you type them on your owncomputer keyboard. For instance, I may ask you to typepublic class Anynamewhich means that you type public class and then some name that youmake up on your own. Words that you need to replace with your ownwords are set in italicized You Don t Have to ReadPick the first chapter or section that has material you don t already know andstart reading there. Of course, you may hate making decisions as much as Ido. If so, here are some guidelines that you can follow:If you already know what kind of an animal Java is and know that youwant to use Java, skip Chapter 1 and go straight to Chapter 2. Believe me,I won t you already know how to get a Java program running, and you don tcare what happens behind the scenes when a Java program runs, skipChapter 2 and start with Chapter you write programs for a living but use any language other than C orC++, start with Chapter 2 or 3. When you reach Chapters 5 and 6, you llprobably find them to be easy reading.
10 When you get to Chapter 7, it ll betime to dive you write C (not C++) programs for a living, start with Chapters 2, 3,and 4 and just skim Chapters 5 and you write C++ programs for a living, glance at Chapters 2 and 3, skimChapters 4 through 6, and start reading seriously in Chapter 7. (Java is abit 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 mewrite Java For Dummies, 8th you want to skip the sidebars and the Technical Stuff icons, please do. Infact, if you want to skip anything at all, feel AssumptionsIn this book, I make a few assumptions about you, the reader. If one of theseassumptions is incorrect, you re probably okay. If all these assumptions areincorrect .. well, buy the book anyway:I assume that you have access to a computer. Here s the good news:You can run most of the code in this book on almost any computer. Theonly computers that you can t use to run this code are ancient things thatare more than ten years old (give or take a few years).