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

Java eLearning Kit For Dummies®

Table of Contents

Introduction

About This Kit

How This Book Is Organized

Conventions Used in This Book

Foolish Assumptions

Icons Used in This Kit

Accessing the Java eCourse

Class Is In

Chapter 1: Starting With Java

Considering Why You’d Use Java

Using a popular language

Working with a standardized language

Creating applications for multiple platforms

Defining other reasons to use Java

Obtaining and Installing the Java 8 JDK

Downloading Java 8

Performing the Windows installation

Performing the Linux installation

Performing the Mac installation

Accessing the Java executables

Choosing an IDE for Java

Working with a text editor

Finding an IDE

Determining when to use a particular development environment

Creating a Simple Application

Writing the application code

Identifying the parts of the application

Compiling the Simple Application

Opening the command prompt

Creating the compiled .class file

Executing the Simple Application

Using the Java command

Understanding the JavaW command difference

Adding Comments to Your Java Code

Grasping the importance of comments

Creating single-line comments

Creating multiline comments

Importing Other Classes

Introducing the Java API

Importing single classes

Importing an entire package

Obtaining Help for Java

Getting local help

Getting local utility help

Locating Java information online

Summing Up

Try-it-yourself lab

Know this tech talk

Chapter 2: Using Primitive Variables

Working with the Primitive Types

byte

short

int

long

float

double

boolean

char

Creating and Using Constants

Summing Up

Try-it-yourself lab

Know this tech talk

Chapter 3: Using Object Variables

Working with Common Objects

String

Calendar

BigDecimal

BigInteger

Changing Primitive Types into Objects

Automatic boxing and unboxing

Byte versus byte

Short versus short

Integer versus int

Long versus long

Float versus float

Double versus double

Boolean versus boolean

Character versus char

Using the New Date and Time API

Viewing the date and time API

Creating and using dates and times

Working with Enumerations

Summing Up

Try-it-yourself lab

Know this tech talk

Chapter 4: Formatting Variable Content

Displaying Percentages

Using Escape Sequences

Displaying Date and Time

Using the Calendar object

Using the date and time API

Displaying Currency Values

Summing Up

Try-it-yourself lab

Know this tech talk

Chapter 5: Working with Operators

Storing Data Using Assignment Operators

Performing a simple assignment

Performing a combined assignment

Performing Math Tasks with Arithmetic Operators

Performing simple math tasks

Executing complex math tasks

Modifying Variable Content Using Unary Operators

Incrementing and decrementing numbers

Understanding negation, bitwise Not, and Boolean Not

Creating objects

Casting one type to another

Using Relational and Conditional Operators

Checking value equality

Performing a type comparison

Performing a conditional evaluation

Understanding Operator Precedence

Summing Up

Try-it-yourself lab

Know this tech talk

Chapter 6: Working with Conditional Statements

Using a Simple If Statement

Performing One of Two Tasks with If…Else

Nesting If Statements

Selecting from Multiple Conditions Using Switch

Executing a Default Task

Displaying Boolean Values

Summing Up

Try-it-yourself lab

Know this tech talk

Chapter 7: Repeating Tasks Using Loops

Performing Tasks a Set Number of Times

Using the standard for loop

Using the break statement

Using the continue statement

Nesting for loops

Executing Tasks Until Complete

Using the while loop

Checking after the first execution with the do …while loop

Interacting with Objects

Creating a basic for-each loop

Using the for-each loop with enumerations

Summing Up

Try-it-yourself lab

Know this tech talk

Chapter 8: Handling Errors

Understanding Error Sources

Classifying when errors occur

Distinguishing error types

Catching Errors

Optional error handling

Handling more-specific to less-specific errors

Using Optional objects to avoid exceptions

Throwing Errors

Throwing errors during exceptional conditions

Passing errors to the caller

Required error handling

Summing Up

Try-it-yourself lab

Know this tech talk

Chapter 9: Creating and Using Classes

Understanding the Structure of Classes

Calling methods

Allocating properties

Considering inheritance

Defining Variable Scope

Considering default scope

Observing scope within a block

Defining a Class with Event Support

Defining an event

Creating an event listener interface

Implementing the event as part of a class definition

Demonstrating use of the event in a class

Using the Class with Events

Working with Anonymous Inner Classes

Working with Lambda Expressions

Summing Up

Try-it-yourself lab

Know this tech talk

Chapter 10: Accessing Data Sets Using Arrays and Collections

Performing Basic Array Tasks

Defining an array

Initializing an array

Using the for-each loop with arrays

Determining the array characteristics

Changing the array size

Sorting array data

Creating Multidimensional Arrays

Defining a two-dimensional array

Obtaining the number of dimensions in an array

Developing variable-length arrays of arrays

Interacting with Array-Like Structures

Using stacks

Working with queues

Employing deques

Iterating arrays by using List elements and lambda expressions

Using Maps to Create Collections

Defining the map

Creating a map example

Working with Java Annotations

Understanding annotations

Using annotations

Summing Up

Try-it-yourself lab

Know this tech talk

Chapter 11: Performing Advanced String Manipulation

Converting Data to and from Strings

Finding Information in Strings

Looking at the beginning or end of the string

Working with substrings

Modifying String Content

Extracting characters

Splitting strings

Formatting String Output

Summing Up

Try-it-yourself lab

Know this tech talk

Chapter 12: Interacting with Files

Interacting with the File System

Managing directory information

Interacting with files

Defining file and directory attributes

Manipulating path data

Opening Files for Reading

Writing to Files

Creating and Using Temporary Files

Summing Up

Try-it-yourself lab

Know this tech talk

Chapter 13: Manipulating XML Data

Understanding How XML and Java Interact

Reading XML Data from Files

Writing XML Data to Disk

Summing Up

Try-it-yourself lab

Know this tech talk

About the Author

More Dummies Products

Guide

Table of Contents

Begin Reading

Pages

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

47

48

49

50

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

161

162

163

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

429

430

431

Introduction

If 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.

Decide what to do when an error occurs in your application.

Use lambda expressions to make your code simpler and smaller.

Work with collections of information.

Make the output of your application look nice.

Work with data that appears on your hard drive.

Interact with the XML data that appears in so many different places (both on your local hard drive and online).

How This Book Is Organized

This book is split into the 13 chapters that are described in this section. You can find more information about using all the pieces of the multimedia kit together in the “Accessing the Java eCourse” section of this introduction.

Chapter 1: Starting with Java: Before you can begin doing anything with Java, you need a copy of Java on your system. More importantly, you need a copy of Java with all the current features. This chapter helps you obtain a current version of Java and install it on your Windows, Macintosh, or Linux system. You’ll also learn how to obtain an Integrated Development Environment (IDE, for short) should you wish to use one with the book. (You can use any text editor that you like.) Of course, when you have Java installed, you’ll want to create at least a basic program with it, so this chapter introduces you to Java programming techniques as well. Java is a rich language, so it’s important to know how to obtain help when you need it (even the professionals use help) — this chapter ends by showing you how.

Chapter 2: Using Primitive Variables: Variables provide a kind of storage box that you use to hold information while your application works with it. This chapter introduces you to basic variables that Java developers call primitives because they don’t require anything fancy to use them.

Chapter 3: Using Object Variables: Primitive variables have limitations. Yes, they’re simple to use, fast, and don’t require much memory, but they lack many of the features that developers want. This chapter introduces you to feature-rich object variables. The basic idea is the same as using primitive variables — variables are meant to hold data, after all — but object variables make it so much easier to perform special tasks that you’ll wonder how you got along without them. This chapter also introduces you to the new date and time API that makes working with both date and time significantly easier.

Chapter 4: Formatting Variable Content: The output from your application is important. Sure, you can output that number in any old way, but your user may not understand what it means. Formatting is an essential part of writing applications. To an extent, creating a nice output simply makes your application easier on the eyes, but formatting also contributes to understanding what the output means.

Chapter 5: Working with Operators: Many applications are used to perform math-related tasks. Operators provide a means of telling Java what math tasks to perform and the order in which you want them performed. There are also operators that help the application make decisions, such as whether one number is greater than another. In fact, you’ll use lots of operators in your application to tell Java how to view a particular variable, how to interact with it, or simply what task to perform with one or more variables.

Chapter 6: Working with Conditional Statements: Most applications have to make decisions based on the data they receive. For example, if a number is higher than the one you expected, then you need to tell the application what to do about it. Just as you make thousands of decisions every day, the applications you write must also make decisions to model the real world. This chapter helps you understand the methods that Java provides for making decisions.

Chapter 7: Repeating Tasks Using Loops: Writing an application that performs a task only one time doesn’t make too much sense. The time required to write the application is almost always greater than the time required for you to perform the task once. This chapter helps you create applications that can perform tasks more than once. Repetition is one of the fortes of computer systems. A computer will perform the same task as many times as you want precisely the same way every time.

Chapter 8: Handling Errors: Everyone makes mistakes. Even if a human isn’t involved, mistakes happen. A program can experience an error simply due to a hardware glitch or as the result of something that another application is doing on the host system. This chapter emphasizes the benefits of detecting errors and then doing something about them, rather than letting your application crash. If you’ve ever been upset because an application lost your data after a seemingly needless crash, then you’ll definitely want to read this chapter to avoid those problems in your own application.

Chapter 9: Creating and Using Classes: You’ll have seen objects used quite a bit by this point in the book. Java relies on classes to create objects. If you haven’t seen the class of your dreams, Java may not provide it. Never fear! You can create your own classes that meet any need that you can imagine. This chapter shows how to create classes that you can then use as objects in your applications to perform amazing tasks. It also demonstrates the use of lambda expressions, which is a new Java feature that will make your code smaller, faster, and less prone to errors.

Chapter 10: Accessing Data Sets Using Arrays and Collections: You see collections of things all around you. If you have a bookshelf, then you have a collection of books. When you go to the closet, you see a collection of clothing. A collection is an assortment of like items that are placed in a single storage container. This chapter helps you understand what collections (and the related arrays) are and how using them can make your application work better.

Chapter 11: Performing Advanced String Manipulation: The string is the most common variable used in Java because a string models how humans think about information. Every sentence you’ve read so far in this Introduction is a string. When you read any other book, you read strings. Look at an advertisement with writing and you see strings. In short, strings are everywhere. This chapter helps you perform some advanced tasks using strings that you’ll find helpful as your applications become more complex.

Chapter 12: Interacting with Files: Variables represent temporary storage of data in an application. When the application ends, the variables are destroyed and the data they contain is gone. Of course, you may want to store that information in some permanent form for later use. This chapter shows how to use files, which provide permanent storage for your data on the hard drive of your machine.

Chapter 13: Manipulating XML Data: Your machine contains a wealth of file types. Chapter 12 introduces you to text files, which provide a means of storing basic information as strings. Unfortunately, basic text files don’t have any intelligence — meaning they can’t communicate what the data they contain means. You can’t save the context of the information so that the information is easy to understand later. The eXtensible Markup Language (XML) makes it possible to add intelligence to data storage so that it’s possible to tell the difference between a name and a color later. This chapter provides a brief overview of working with XML in a Java application.

Conventions Used in This Book

A few style conventions will help you navigate the book part of this kit efficiently:

Terms or words that I truly want to emphasize are defined in Lingo sections.

Website addresses, or URLs, are shown like this: http://www.dummies.com.

Numbered steps that you need to follow and characters you need to type (such as a user ID or password) are set in bold.

Foolish Assumptions

For starters, I assume you know what eLearning is, you need to find out how to build Java applications (and fast!), and you want to get a piece of this academic action the fun and easy way with Java eLearning Kit For Dummies.

I’m also assuming that you know the basics of working with your computer and the operating system installed on that computer. You need to know how to work with the input devices for your computer, perform basic tasks that require you to start applications, and how to perform tasks with those applications, such as using your browser to access information online. The first chapter provides instructions on how to install Java on your system, but it’s a plus if you’ve installed applications on your system before.

There are a number of places in the book where you’ll need to go online to perform tasks. For example, accessing basic Java help requires that you get online for the latest information. The Go Online icon (see the “Icons Used in This Kit” section) will also direct you to online resources that you’ll want to access.

Icons Used in This Kit

The familiar and helpful For Dummies icons point you in the direction of really great information that’s sure to help you as you work your way through assignments. Look for these icons throughout Java eLearning Kit For Dummies, in the book and in the electronic lessons.

The Tip icon points out helpful information that’s likely to make your job easier.

This icon marks an interesting and useful fact — something you probably want to remember for later use.

The Warning icon highlights lurking danger. When you see this icon, pay attention and proceed with caution.

Some programming concepts are a little harder to understand than others are. This icon points out ways in which you can improve your knowledge of these harder areas by practicing with the examples provided in that section of the chapter.

In addition to the icons, the book includes these friendly study aids that bring your attention to certain pieces of information:

Lingo: When you see the Lingo box, look for a definition of a key term or concept.

Go Online: Serving as your call to action, this box sends you online to view web resources, complete activities, or find examples.

Extra Info: This box highlights something to pay close attention to in a figure or points out other useful information related to the discussion at hand.

Accessing the Java eCourse

Your purchase of this For Dummies eLearning Kit includes access to the course online at the For Dummies eLearning Center. If you have purchased an electronic version of this book, please visit http://www.dummies.com/go/getelearningcode to gain your access code to the online course. If you purchased the paperback book, you find your access code inside the front cover of this book.

Dummies eCourses require an HTML5-capable browser. If you use the Firefox or Chrome browser, make sure you have the latest version. Internet Explorer 10 is also HTML5-capable.

Class Is In

Now that you’re primed and ready, it’s time to begin. Most readers will want to start with Chapter 1. This chapter provides essential information for getting Java installed, obtaining and installing an IDE, creating a simple first application, and obtaining help about Java features. If you’re absolutely certain that you already know all of this information, then you can probably start with Chapter 2. If you feel like downloading the book’s sample Java code, head on over to http://www.dummies.com/go/javaelearning, where you’ll find the code nicely organized by chapter.

Chapter 1

Starting With Java

Java’s increasing popularity makes it the most common language used to develop cross-platform applications.

Developers rely on the fact that Java is a standards-based language.

Each platform that Java supports has its own version of the Java Software Development Kit (SDK) and Java Runtime Engine (JRE), yet uses precisely the same language.

All Java applications share common components.

Java applications rely on a special application called a compiler to change Java source code that the developer understands to an executable form that the JRE understands.

Use comments to make it easier to remember what tasks your application performs.

Java applications rely on the Java Application Programming Interface (API) to perform many tasks.

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!