Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Java for dummies
Nội dung xem thử
Mô tả chi tiết
Open and find:
• Tips on choosing an IDE for Java
• How to change primitive
types into objects
• Advice on formatting variable
content
• Different types of operators
• What to do with conditional
statements
• Directions for setting up loops
• How to create and use classes
• Secrets of manipulating strings
John Paul Mueller is a veteran technical editor and an expert on computer
industry certifications. He has written books on C#, Java, Windows programming,
and VBA, and is coauthor of the bestselling C++ All-in-One For Dummies.
$39.99 USA / $47.99 CAN / £27.99 UK
Programming Languages / Java Learn this platform-independent
language and create programs that
will run anywhere
Java is the primary language used for Android development
and many web applications, so once you master it, you can
create apps for all sorts of uses. With this eLearning Kit, you learn
Java at your own pace using written, visual, and interactive
lessons. Discover how to obtain and install Java and go from
beginner to programmer extraordinaire!
• Install the newest version — find and install the most up-to-date
Java version for Windows®, Mac®, or Linux®
• Explore variables — learn to use primitive variables to store
information and object variables to perform tasks within your
application
• Get in the loop — repeat tasks with loops, create and use classes,
access data sets, and work with strings
• Banish bugs — detect and solve problems to prevent application
crashes
• XML makes it better — add value to your applications by working
with XML data
Includes
Online Course
See inside for details!
Includes:
• Full color book plus
online training course
• FREE 1 year access to
online self-paced training
via access code
• 10 interactive lessons cover
the essentials of Java
John Paul Mueller
eLEARNING KIT
KIT
LEARNING
Java®
Java®
Cover Images: Front Cover Image ©iStockphoto.com/
olaser; Back and Inside Cover Images Courtesy of
John Paul Mueller
Java®
LEARNING KIT
by John Paul Mueller
Java®
LEARNING KIT
Java® eLearning Kit For Dummies®
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 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:
ISBN 978-1-118-09878-3 (pbk); ISBN 978-1-118-22370-3 (ebk); 978-1-118-23706-9 (ebk);
ISBN 978-1-118-26201-6 (ebk)
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
Contents at a Glance
Introduction ................................................................ 1
Chapter 1: Starting With Java...........................................................................................7
Chapter 2: Using Primitive Variables ............................................................................47
Chapter 3: Using Object Variables.................................................................................75
Chapter 4: Formatting Variable Content.....................................................................111
Chapter 5: Working with Operators ............................................................................129
Chapter 6: Working with Conditional Statements .....................................................165
Chapter 7: Repeating Tasks Using Loops ...................................................................185
Chapter 8: Handling Errors...........................................................................................209
Chapter 9: Creating and Using Classes .......................................................................247
Chapter 10: Accessing Data Sets Using Arrays and Collections ..............................285
Chapter 11: Performing Advanced String Manipulation...........................................337
Chapter 12: Interacting with Files................................................................................359
Chapter 13: Manipulating XML Data............................................................................387
Index ...................................................................... 403
Table of Contents
Introduction ................................................................. 1
About This Kit..................................................................................................1
How This Book Is Organized..........................................................................2
Conventions Used in This Book.....................................................................4
Foolish Assumptions.......................................................................................5
Icons Used in This Kit .....................................................................................5
Accessing the Java eCourse ...........................................................................6
Class Is In..........................................................................................................6
Chapter 1: Starting With Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Considering Why You’d Use Java................................................................10
Using a popular language....................................................................10
Working with a standardized language.............................................11
Creating applications for multiple platforms...................................12
Defining other reasons to use Java....................................................12
Obtaining and Installing the Java 8 JDK......................................................13
Downloading Java 8 .............................................................................13
Performing the Windows installation................................................14
Performing the Linux installation ......................................................15
Performing the Mac installation.........................................................16
Accessing the Java executables.........................................................16
Choosing an IDE for Java ..............................................................................21
Working with a text editor..................................................................21
Finding an IDE.......................................................................................22
Determining when to use a particular development
environment......................................................................................23
Creating a Simple Application......................................................................24
Writing the application code..............................................................24
Identifying the parts of the application ............................................26
Compiling the Simple Application...............................................................27
Opening the command prompt..........................................................28
Creating the compiled .class file........................................................29
Executing the Simple Application................................................................30
Using the Java command ....................................................................30
Understanding the JavaW command difference..............................31
Adding Comments to Your Java Code ........................................................32
Grasping the importance of comments ............................................32
Creating single-line comments...........................................................33
Creating multiline comments .............................................................34
viii
Java eLearning Kit For Dummies
Importing Other Classes...............................................................................34
Introducing the Java API.....................................................................35
Importing single classes......................................................................36
Importing an entire package...............................................................37
Obtaining Help for Java ................................................................................39
Getting local help.................................................................................40
Getting local utility help......................................................................41
Locating Java information online.......................................................42
Summing Up ...................................................................................................42
Try-it-yourself lab ................................................................................44
Know this tech talk..............................................................................44
Chapter 2: Using Primitive Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Working with the Primitive Types...............................................................50
byte........................................................................................................51
short ......................................................................................................55
int...........................................................................................................57
long ........................................................................................................59
float........................................................................................................61
double....................................................................................................63
boolean..................................................................................................65
char........................................................................................................67
Creating and Using Constants......................................................................69
Summing Up ...................................................................................................71
Try-it-yourself lab ................................................................................72
Know this tech talk..............................................................................72
Chapter 3: Using Object Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Working with Common Objects...................................................................78
String .....................................................................................................78
Calendar ................................................................................................80
BigDecimal............................................................................................81
BigInteger..............................................................................................84
Changing Primitive Types into Objects ......................................................86
Automatic boxing and unboxing........................................................87
Byte versus byte ..................................................................................87
Short versus short...............................................................................90
Integer versus int.................................................................................92
Long versus long..................................................................................94
Float versus float..................................................................................97
Double versus double .......................................................................100
Boolean versus boolean....................................................................101
Character versus char.......................................................................101
ix
Table of Contents
Using the New Date and Time API.............................................................103
Viewing the date and time API .........................................................103
Creating and using dates and times ................................................105
Working with Enumerations.......................................................................106
Summing Up .................................................................................................108
Try-it-yourself lab ..............................................................................109
Know this tech talk............................................................................110
Chapter 4: Formatting Variable Content . . . . . . . . . . . . . . . . . . . . . . . . 111
Displaying Percentages...............................................................................113
Using Escape Sequences.............................................................................115
Displaying Date and Time...........................................................................118
Using the Calendar object.................................................................118
Using the date and time API .............................................................121
Displaying Currency Values .......................................................................124
Summing Up .................................................................................................126
Try-it-yourself lab ..............................................................................126
Know this tech talk............................................................................127
Chapter 5: Working with Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Storing Data Using Assignment Operators...............................................132
Performing a simple assignment......................................................132
Performing a combined assignment................................................134
Performing Math Tasks with Arithmetic Operators ...............................137
Performing simple math tasks .........................................................137
Executing complex math tasks.........................................................140
Modifying Variable Content Using Unary Operators ..............................143
Incrementing and decrementing numbers .....................................144
Understanding negation, bitwise Not, and Boolean Not...............145
Creating objects .................................................................................148
Casting one type to another .............................................................148
Using Relational and Conditional Operators ...........................................151
Checking value equality....................................................................152
Performing a type comparison.........................................................154
Performing a conditional evaluation...............................................156
Understanding Operator Precedence .......................................................157
Summing Up .................................................................................................161
Try-it-yourself lab ..............................................................................162
Know this tech talk............................................................................163
Chapter 6: Working with Conditional Statements . . . . . . . . . . . . . . . 165
Using a Simple If Statement........................................................................167
Performing One of Two Tasks with If. . .Else............................................169
Nesting If Statements ..................................................................................171
Selecting from Multiple Conditions Using Switch ...................................174
x
Java eLearning Kit For Dummies
Executing a Default Task ............................................................................177
Displaying Boolean Values .........................................................................180
Summing Up .................................................................................................182
Try-it-yourself lab ..............................................................................182
Know this tech talk............................................................................183
Chapter 7: Repeating Tasks Using Loops . . . . . . . . . . . . . . . . . . . . . . . 185
Performing Tasks a Set Number of Times ................................................187
Using the standard for loop..............................................................187
Using the break statement................................................................189
Using the continue statement ..........................................................191
Nesting for loops................................................................................193
Executing Tasks Until Complete................................................................196
Using the while loop..........................................................................197
Checking after the first execution with the do . . .while loop ......199
Interacting with Objects .............................................................................201
Creating a basic for-each loop..........................................................202
Using the for-each loop with enumerations ...................................203
Summing Up .................................................................................................206
Try-it-yourself lab ..............................................................................206
Know this tech talk............................................................................207
Chapter 8: Handling Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Understanding Error Sources ....................................................................212
Classifying when errors occur .........................................................212
Distinguishing error types................................................................215
Catching Errors............................................................................................222
Optional error handling ....................................................................222
Handling more-specific to less-specific errors...............................225
Using Optional objects to avoid exceptions...................................229
Throwing Errors ..........................................................................................234
Throwing errors during exceptional conditions............................234
Passing errors to the caller ..............................................................237
Required error handling ...................................................................238
Summing Up .................................................................................................243
Try-it-yourself lab ..............................................................................244
Know this tech talk............................................................................245
Chapter 9: Creating and Using Classes . . . . . . . . . . . . . . . . . . . . . . . . 247
Understanding the Structure of Classes...................................................250
Calling methods .................................................................................250
Allocating properties.........................................................................252
Considering inheritance....................................................................253
xi
Table of Contents
Defining Variable Scope..............................................................................257
Considering default scope ................................................................257
Observing scope within a block.......................................................265
Defining a Class with Event Support.........................................................266
Defining an event ...............................................................................266
Creating an event listener interface ................................................268
Implementing the event as part of a class definition ....................269
Demonstrating use of the event in a class......................................272
Using the Class with Events .......................................................................275
Working with Anonymous Inner Classes..................................................277
Working with Lambda Expressions...........................................................279
Summing Up .................................................................................................281
Try-it-yourself lab ..............................................................................282
Know this tech talk............................................................................283
Chapter 10: Accessing Data Sets Using Arrays and Collections . . 285
Performing Basic Array Tasks ...................................................................288
Defining an array................................................................................288
Initializing an array............................................................................289
Using the for-each loop with arrays ................................................289
Determining the array characteristics............................................291
Changing the array size.....................................................................293
Sorting array data ..............................................................................296
Creating Multidimensional Arrays ............................................................298
Defining a two-dimensional array ....................................................298
Obtaining the number of dimensions in an array..........................300
Developing variable-length arrays of arrays ..................................304
Interacting with Array-Like Structures .....................................................310
Using stacks........................................................................................310
Working with queues.........................................................................314
Employing deques .............................................................................318
Iterating arrays by using List elements and
lambda expressions .......................................................................322
Using Maps to Create Collections .............................................................323
Defining the map................................................................................324
Creating a map example....................................................................325
Working with Java Annotations.................................................................328
Understanding annotations..............................................................328
Using annotations ..............................................................................331
Summing Up .................................................................................................332
Try-it-yourself lab ..............................................................................333
Know this tech talk............................................................................334
xii
Java eLearning Kit For Dummies
Chapter 11: Performing Advanced String Manipulation . . . . . . . . . . 337
Converting Data to and from Strings ........................................................340
Finding Information in Strings ...................................................................344
Looking at the beginning or end of the string................................344
Working with substrings...................................................................346
Modifying String Content............................................................................348
Extracting characters........................................................................348
Splitting strings ..................................................................................351
Formatting String Output ...........................................................................352
Summing Up .................................................................................................357
Try-it-yourself lab ..............................................................................357
Know this tech talk............................................................................358
Chapter 12: Interacting with Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
Interacting with the File System ................................................................361
Managing directory information......................................................363
Interacting with files..........................................................................365
Defining file and directory attributes ..............................................368
Manipulating path data .....................................................................371
Opening Files for Reading...........................................................................373
Writing to Files.............................................................................................376
Creating and Using Temporary Files.........................................................379
Summing Up .................................................................................................385
Try-it-yourself lab ..............................................................................385
Know this tech talk............................................................................386
Chapter 13: Manipulating XML Data . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
Understanding How XML and Java Interact.............................................389
Reading XML Data from Files .....................................................................390
Writing XML Data to Disk ...........................................................................396
Summing Up .................................................................................................400
Try-it-yourself lab ..............................................................................401
Know this tech talk............................................................................401
Index ....................................................................... 403
Introduction
I
f you’ve been thinking about taking a class online (it’s all the rage
these days), but you’re concerned about getting lost in the electronic
fray, worry no longer. Java eLearning Kit For Dummies is here to help
you, providing you with an integrated learning experience that includes
not only the book you hold in your hands but also an online version of the
course at http://learn.dummies.com. Consider this introduction
your primer.
About This Kit
Each piece of this eLearning Kit works in conjunction with the others,
although you don’t need them all to gain valuable understanding of the key
concepts covered here. Whether you follow along with the book, go online
to see the course, or some combination of the two, Java eLearning Kit For
Dummies teaches you how to:
✓ Install a copy of Java on your particular platform. (Windows, Linux, and
Macintosh instructions are all provided.)
✓ Obtain an Integrated Development Environment (IDE) for your copy of
Java, should you wish to use one.
✓ Write a basic Java program.
✓ Obtain help using Java to write applications for your machine.
✓ Use variables to store information for use in your application.
✓ Create and use objects that model real-world information.
✓ Employ the new date and time API for Java in your applications.
✓ Perform mathematical tasks using Java.
✓ Make decisions based on input that the application receives.
✓ Perform repetitive tasks.