ebook img

Java for Dummies (6th ed.) PDF

435 Pages·2014·18.75 MB·English
by  
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Java for Dummies (6th ed.)

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! • The Java scoop — get an overview of Java, featuring new tools and enhancements in Java 8, including new libraries, parallel frameworks, and more • Building blocks — find out how to work with Java classes and methods • Get loopy — understand the value of variables and learn to control program flow with loops or decision-making statements • Stay classy — explore classes and objects, constructors, and subclasses, and find out how to reuse code • A click ahead — jump into variables, use arrays and collections, and create programs that respond to mouse clicks Java ® Burd 6th Edition Barry Burd, PhD Author of Beginning Programming with Java For Dummies® Learn to: • 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 Edition Making Everything Easier!™ 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 • Common Instructions • And Other Good Stuff! 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 • Illustrated Articles • Step-by-Step Instructions 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 • Digital Photography • Microsoft Windows & Office • Personal Finance & Investing • Health & Wellness • Computing, iPods & Cell Phones • 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 Time 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 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 with Java...........................................................4 Part II: Writing Your Own Java Program.............................................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 Icons Used in This Book .................................................................................5 Beyond the Book .............................................................................................6 Where to Go from Here...................................................................................6 Part I: Getting Started with Java................................... 7 Chapter 1: All about Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 What You Can Do with Java .........................................................................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 about an object-oriented language? ......................16 Refining your understanding of classes and objects ......................18 What’s Next?...................................................................................................20 Chapter 2: All about Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Quick-Start Instructions................................................................................21 What You Install on Your Computer...........................................................23 What is a compiler? .............................................................................24 What is a Java Virtual Machine? ........................................................26 Developing software............................................................................32 What is an Integrated Development Environment?.........................33 www.it-ebooks.info Java For Dummies, 6th Edition vi Chapter 3: Using the Basic Building Blocks . . . . . . . . . . . . . . . . . . . . . 37 Speaking the Java Language.........................................................................37 The grammar and the common names .............................................38 The words in a Java program.............................................................39 Checking Out Java Code for the First Time................................................41 Understanding a Simple Java Program.......................................................42 The Java class ......................................................................................43 The Java method..................................................................................44 The main method in a program .........................................................46 How you finally tell the computer to do something........................47 Curly braces .........................................................................................50 And Now, a Few Comments..........................................................................52 Adding comments to your code.........................................................53 What’s Barry’s excuse? .......................................................................56 Using comments to experiment with your 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 the Types of Values That Variables May Have ...............64 Displaying Text ..............................................................................................68 Numbers without Decimal 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 the number................................................................................92 She controlled keystrokes from the keyboard.................................93 Creating randomness ..........................................................................96 The if statement ...................................................................................96 The double equal sign.........................................................................97 Brace yourself ......................................................................................98 Indenting if statements in your code.................................................99 Elseless in Ifrica....................................................................................99 www.it-ebooks.info vii Table of Contents Forming Conditions with Comparisons and Logical Operators............101 Comparing numbers; comparing characters .................................101 Comparing objects.............................................................................102 Importing everything in one fell swoop..........................................104 Java’s logical operators ....................................................................105 Vive les nuls!.......................................................................................108 (Conditions in parentheses).............................................................109 Building a Nest.............................................................................................111 Choosing among Many Alternatives (Java switch Statements).............113 Your basic switch statement............................................................113 To break or not to break...................................................................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 of Times (Java for Statements)................125 The anatomy of a for statement.......................................................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 in Java ..........................................................................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 to Be an Account)................................139 Declaring variables and creating objects .......................................141 Initializing a variable .........................................................................144 Using an object’s fields .....................................................................144 One program; several classes ..........................................................145 Public classes.....................................................................................145 Defining a Method within a Class (Displaying an Account)...................146 An account that displays itself.........................................................147 The display method’s header...........................................................148 Sending Values to and from Methods (Calculating Interest).................149 Passing a value to a method.............................................................152 Returning a value from the getInterest method.............................154 Making Numbers Look Good......................................................................156 Hiding Details with Accessor Methods.....................................................159 Good programming............................................................................160 Public lives and private dreams: Making a field inaccessible......162 Enforcing rules with accessor methods..........................................164 www.it-ebooks.info Java For Dummies, 6th Edition viii Chapter 8: Saving Time and Money: Reusing Existing Code . . . . . . 165 Defining a Class (What It Means to Be an Employee).............................166 The last word on employees ............................................................166 Putting your class to good use.........................................................168 Cutting a check...................................................................................169 Working with Disk Files (A Brief Detour) .................................................170 Storing data in a file...........................................................................171 Copying and pasting code ................................................................172 Reading from a file.............................................................................173 Who moved my file? ..........................................................................175 Adding directory names to your filenames....................................176 Reading a line at a time.....................................................................177 Closing the connection to a 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 of the story.............................................................187 Overriding Existing Methods (Changing the Payments for Some Employees)...............................................................................188 A Java annotation ..............................................................................190 Using methods from classes and subclasses.................................190 Chapter 9: Constructing New Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 193 Defining Constructors (What It Means to Be 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 with a temperature..............................................197 Calling new Temperature(32.0): A case study ...............................200 Some things never change................................................................202 More Subclasses (Doing Something about the Weather).......................203 Building better temperatures...........................................................203 Constructors for subclasses.............................................................205 Using all this stuff ..............................................................................206 The default constructor....................................................................207 A Constructor That Does More..................................................................209 Classes and methods from the Java API.........................................212 The SuppressWarnings annotation .................................................213 www.it-ebooks.info ix Table of Contents Part IV: Savvy Java Techniques ................................. 215 Chapter 10: Putting Variables and Methods Where They Belong . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 Defining a Class (What It Means to Be a Baseball Player)......................217 Another way to beautify your numbers..........................................219 Using the Player class .......................................................................219 Nine, count ’em, nine.........................................................................222 Don’t get all GUI on me......................................................................222 Tossing an exception from method to method..............................224 Making Static (Finding the Team Average) ..............................................225 Why is there so much static? ...........................................................226 Meet the static initializer ..................................................................227 Displaying the overall team average ...............................................228 Static is old hat...................................................................................231 Could cause static; handle with care ..............................................231 Experiments with Variables .......................................................................232 Putting a variable in its place...........................................................233 Telling a variable where to go..........................................................236 Passing Parameters.....................................................................................238 Pass by value......................................................................................239 Returning a result ..............................................................................240 Pass by reference...............................................................................241 Returning an object from a method ................................................243 Epilogue...............................................................................................244 Chapter 11: Using Arrays to Juggle Values . . . . . . . . . . . . . . . . . . . . . 245 Getting Your Ducks All in a Row................................................................245 Creating an array in two easy steps ................................................247 Storing values.....................................................................................248 Tab stops and other special things.................................................251 Using an array initializer...................................................................251 Stepping through an array with the enhanced for loop ...............252 Searching ............................................................................................254 Writing to a file...................................................................................256 When to close a file............................................................................257 Arrays of Objects.........................................................................................259 Using the Room class ........................................................................260 Yet another way to beautify your numbers ...................................263 The conditional operator..................................................................264 Command Line Arguments.........................................................................265 Using command line arguments in a Java program ......................266 Checking for the right number of command line arguments.......268 www.it-ebooks.info Java For Dummies, 6th Edition x Chapter 12: Using Collections and Streams (When Arrays Aren’t Good Enough) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 Understanding the Limitations of Arrays.................................................271 Collection Classes to the Rescue...............................................................272 Using an ArrayList .............................................................................273 Using generics ....................................................................................275 Testing for the presence of more data............................................277 Using an iterator ................................................................................278 Java’s many collection classes.........................................................279 New in Java 8: Functional Programming...................................................280 Solving a problem the old-fashioned way.......................................282 Streams................................................................................................284 Lambda expressions..........................................................................285 A taxonomy of lambda expressions ................................................289 Using streams and lambda expressions .........................................289 Why bother? .......................................................................................295 Method references.............................................................................295 Chapter 13: Looking Good When Things Take Unexpected Turns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 Handling Exceptions ...................................................................................300 The parameter in a catch clause......................................................304 Exception types..................................................................................305 Who’s going to catch the exception? ..............................................307 The multi-catch clause......................................................................313 Throwing caution to the wind..........................................................314 Doing useful things ............................................................................315 Our friends, the good exceptions ....................................................316 Handle an Exception or Pass the Buck .....................................................316 Finishing the Job with a finally Clause......................................................322 A try Statement with Resources ................................................................324 Chapter 14: Sharing Names among the Parts of a Java Program . . . . 327 Access Modifiers..........................................................................................328 Classes, Access, and Multipart Programs ................................................329 Members versus classes...................................................................329 Access modifiers for members ........................................................330 Putting a drawing on a frame ...........................................................333 Directory structure............................................................................335 Making a frame...................................................................................337 Sneaking Away from the Original Code ....................................................338 Default access.....................................................................................339 Crawling back into the package.......................................................342 www.it-ebooks.info xi Table of Contents Protected Access.........................................................................................343 Putting non-subclasses in the same package.................................345 Access Modifiers for Java Classes.............................................................346 Public classes.....................................................................................347 Nonpublic classes..............................................................................347 Chapter 15: Responding to Keystrokes and Mouse Clicks . . . . . . . . 349 Go On . . . Click That Button.......................................................................349 Events and event handling ...............................................................352 The Java interface..............................................................................352 Threads of execution.........................................................................354 The keyword this ...............................................................................355 Inside the actionPerformed method ...............................................356 The serialVersionUID ........................................................................357 Responding to Things Other Than Button Clicks....................................358 Creating Inner Classes ................................................................................363 Chapter 16: Writing Java Applets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367 Applets 101...................................................................................................367 Waiting to be called...........................................................................369 A public class .....................................................................................369 The Java API (again)..........................................................................369 Making Things Move ...................................................................................370 The methods in an applet.................................................................372 What to put into all these methods.................................................373 Responding to Events in an Applet ...........................................................374 Chapter 17: Using Java Database Connectivity . . . . . . . . . . . . . . . . . . 377 JDBC and Java DB........................................................................................377 Creating Data................................................................................................378 Using SQL commands........................................................................380 Connecting and disconnecting.........................................................381 Retrieving Data ............................................................................................382 Part V: The Part of Tens ............................................ 385 Chapter 18: Ten Ways to Avoid Mistakes . . . . . . . . . . . . . . . . . . . . . . . 387 Putting Capital Letters Where They Belong.............................................387 Breaking Out of a switch Statement..........................................................388 Comparing Values with a Double Equal Sign ...........................................388 Adding Components to a GUI.....................................................................389 Adding Listeners to Handle Events...........................................................389 Defining the Required Constructors .........................................................389 www.it-ebooks.info Java For Dummies, 6th Edition xii 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 Jobs..................................................................................394 Everyone’s Favorite Sites ...........................................................................394 Index ........................................................................ 395 www.it-ebooks.info Introduction J 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 intim- idating 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 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 let me be honest. If you don’t understand the bigger picture, writing a program 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 the code doesn’t do exactly what you want it to do, you’re just plain stuck. So, in this book, I divide Java programming into manageable chunks. Each chunk is (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 middle of a chapter. I’ve tried to make the examples interesting without making one chapter depend on another. When I use an important idea from another chapter, I include a note to help you find your way around. In general, my advice is as follows: ✓ If you already know something, don’t bother reading about it. ✓ If you’re curious, don’t be afraid to skip ahead. You can always sneak a peek at an earlier chapter if you really need to do so. Conventions Used in This Book Almost every technical 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

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.