Beginning Programming with Java For Dummies - Barry Burd - E-Book

Beginning Programming with Java For Dummies E-Book

Barry Burd

0,0
20,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Learn to speak the Java language like the pros Are you new to programming and have decided that Java is your language of choice? Are you a wanna-be programmer looking to learn the hottest lingo around? Look no further! Beginning Programming with Java For Dummies, 5th Edition is the easy-to-follow guide you'll want to keep in your back pocket as you work your way toward Java mastery! In plain English, it quickly and easily shows you what goes into creating a program, how to put the pieces together, ways to deal with standard programming challenges, and so much more. Whether you're just tooling around or embarking on a career, this is the ideal resource you'll turn to again and again as you perfect your understanding of the nuances of this popular programming language. Packed with tons of step-by-step instruction, this is the only guide you need to start programming with Java like a pro. * Updated for Java 9, learn the language with samples and the Java toolkit * Familiarize yourself with decisions, conditions, statements, and information overload * Differentiate between loops and arrays, objects and classes, methods, and variables * Find links to additional resources Once you discover the joys of Java programming, you might just find you're hooked. Sound like fun? Here's the place to start.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 597

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Beginning Programming with Java®For Dummies®, 5th Edition

Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com

Copyright © 2017 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 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 https://hub.wiley.com/community/support/dummies.

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: 2017944007

ISBN: 978-1-119-23553-8 (pbk); 978-1-119-23556-9 (ebk); 978-1-119-23554-5 (ebk)

Beginning Programming with Java® For Dummies®

To view this book's Cheat Sheet, simply go to www.dummies.com and search for “Beginning Programming with Java For Dummies Cheat Sheet” in the Search box.

Table of Contents

Cover

Introduction

About This Book

How to Use This Book

Conventions Used in This Book

What You Don’t Have to Read

Foolish Assumptions

How This Book Is Organized

Icons Used in This Book

Beyond the Book

Where to Go from Here

Part 1: Getting Started with Java Programming

Chapter 1: Getting Started

What’s It All About?

From Your Mind to the Computer’s Processor

Your Java Programming Toolset

Chapter 2: Setting Up Your Computer

If You Don’t Like Reading Instructions …

Getting This Book’s Sample Programs

Setting Up Java

Setting Up the Eclipse Integrated Development Environment

Importing This Book’s Sample Programs

What’s Next?

Chapter 3: Running Programs

Running a Canned Java Program

Typing and Running Your Own Code

What’s All That Stuff in Eclipse’s Window?

Part 2: Writing Your Own Java Programs

Chapter 4: Exploring the Parts of a Program

Checking Out Java Code for the First Time

The Elements in a Java Program

Understanding a Simple Java Program

Chapter 5: Composing a Program

Computers Are Stupid

A Program to Echo Keyboard Input

Expecting the Unexpected

Chapter 6: Using the Building Blocks: Variables, Values, and Types

Using Variables

What Do All Those Zeros and Ones Mean?

Reading Decimal Numbers from the Keyboard

Variations on a Theme

Experimenting with JShell

Chapter 7: Numbers and Types

Using Whole Numbers

Creating New Values by Applying Operators

Size Matters

Chapter 8: Numbers? Who Needs Numbers?

Characters

The boolean Type

The Remaining Primitive Types

Part 3: Controlling the Flow

Chapter 9: Forks in the Road

Decisions, Decisions!

Making Decisions (Java if Statements)

Variations on the Theme

Chapter 10: Which Way Did He Go?

Forming Bigger and Better Conditions

Building a Nest

Enumerating the Possibilities

Chapter 11: How to Flick a Virtual Switch

Meet the switch Statement

Using Fall-Through to Your Advantage

Using a Conditional Operator

Chapter 12: Around and Around It Goes

Repeating Instructions over and over Again (Java while Statements)

Thinking about Loops (What Statements Go Where)

Thinking about Loops (Priming)

Chapter 13: Piles of Files: Dealing with Information Overload

Running a Disk-Oriented Program

Writing a Disk-Oriented Program

Writing, Rewriting, and Rerewriting

Chapter 14: Creating Loops within Loops

Paying Your Old Code a Little Visit

Creating Useful Code

Chapter 15: The Old Runaround

Repeating Statements a Certain Number of Times ( Java for Statements)

Using Nested for Loops

Repeating Until You Get What You Need (Java do Statements)

Repeating with Predetermined Values (Java’s Enhanced for Statement)

Chapter 16: Using Loops and Arrays

Some Loops in Action

Reader, Meet Arrays; Arrays, Meet the Reader

Working with Arrays

Looping in Style

Deleting Several Files

Part 4: Using Program Units

Chapter 17: Programming with Objects and Classes

Creating a Class

From Classes Come Objects

Another Way to Think about Classes

What’s Next?

Chapter 18: Using Methods and Fields from a Java Class

The String Class

Using an Object’s Methods

Static Methods

Understanding the Big Picture

Chapter 19: Creating New Java Methods

Defining a Method within a Class

Let the Objects Do the Work

Passing Values to Methods

Getting a Value from a Method

Chapter 20: Oooey GUI Was a Worm

The Java Swing Classes

The Swing Classes: Round 2

Code Soup: Mixing XML with Java

Adding Stuff to Your JavaFX Project

Taking Action

Part 5: The Part of Tens

Chapter 21: Ten Websites for Java

This Book’s Website

The Horse’s Mouth

Finding News, Reviews, and Sample Code

Looking for Java Jobs

Got a Question?

Chapter 22: Ten Useful Classes in the Java API

ArrayList

File

Integer

JFrame

JOptionPane

Math

NumberFormat

Scanner

String

System

About the Author

Advertisement Page

Connect with Dummies

End User License Agreement

Guide

Cover

Table of Contents

Begin Reading

Pages

iii

iv

vii

viii

ix

x

xi

xii

xiii

xiv

1

2

3

4

5

6

7

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

46

47

48

49

50

51

52

53

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

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

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

199

200

201

202

203

204

205

206

207

208

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

325

326

327

328

329

330

331

332

333

334

335

336

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

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

525

527

529

531

533

534

535

536

537

538

Introduction

What’s your story?

Are you a working stiff, interested in knowing more about the way your company’s computers work?

Are you a student who needs some extra reading in order to survive a beginning computer course?

Are you a typical computer user — you’ve done lots of word processing and you want to do something more interesting with your computer?

Are you a job seeker with an interest in entering the fast-paced, glamorous, high-profile world of computer programming (or, at least, the decent-paying world of computer programming)?

Well, if you want to write computer programs, this book is for you. This book avoids the snobby “of-course-you-already-know” assumptions and describes computer programming from scratch.

About This Book

The book uses Java — a powerful, general-purpose computer programming language. But Java’s subtleties and eccentricities aren’t the book’s main focus. Instead, this book emphasizes a process — the process of creating instructions for a computer to follow. Many highfalutin books describe the mechanics of this process — the rules, the conventions, and the formalisms. But those other books aren’t written for real people. Those books don’t take you from where you are to where you want to be.

In this book, I assume very little about your experience with computers. As you read each section, you get to see inside my head. You see the problems that I face, the things that I think, and the solutions that I find. Some problems are the kind that I remember facing when I was a novice; other problems are the kind that I face as an expert. I help you understand, I help you visualize, and I help you create solutions on your own. I even get to tell a few funny stories.

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 I have to 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.

In this book, I divide 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 Beginning Programming with Java For Dummies, 5th Edition, is no exception. What follows is a brief explanation of the typefaces used in this book:

New terms are set in

italics.

When I want you to type something short or perform a step, I use

bold.

You’ll also see this

computerese

font. I use the computerese font for Java code, filenames, web page addresses (URLs), onscreen messages, and other such things. Also, if something you need to type is really long, it appears in computerese font on its own line (or lines).

You need to change certain things when you type them on your own computer keyboard. For example, I may ask you to type

class Anyname

which means you should type class and then a name that you make up on your own. Words that you need to replace with your own words are set in italicized computerese.

What You Don’t Have to Read

Pick the first chapter or section that has material you don’t already know and start reading there. Of course, you may hate making decisions as much as I do. If so, here are some guidelines you can follow:

If you already know what computer programming is all about, skip the first half of

Chapter 1

. Believe me, I won’t mind.

If you’re required to use a development environment other than Eclipse, you can skip Chapter 2. This applies if you plan to use NetBeans, IntelliJ IDEA, or a number of other development environments.

Most of this book’s examples require Java 5.0 or later, and some of the examples require Java 7 or later. So make sure that your system uses Java 7 or later. If you’re not sure about your computer’s Java version or if you have leeway in choosing a development environment, your safest move is to read Chapter 3.

If you’ve already done a little computer programming, be prepared to skim

Chapters 6

,

7

, and

8

. Dive fully into

Chapter 9

and see whether it feels comfortable. (If so, read on. If not, skim

Chapters 6

,

7

, and

8

again.)

If you feel comfortable writing programs in a language other than Java, this book isn’t for you. Keep this book as a memento and buy my

Java For Dummies,

7th Edition (also published by Wiley).

If you want to skip the sidebars and the material highlighted by a Technical Stuff icon, please do. In fact, if you want to skip anything at all, feel free.

Foolish Assumptions

In this book, I make a few assumptions about you, the reader. If one of these assumptions is incorrect, you’re probably okay. If all these assumptions are incorrect … well, buy the book anyway.

I assume that you have access to a computer.

Here’s good news. You can run the code in this book on almost any computer. The only computers you can’t use to run this code are ancient things that are more than eight years old (give or take a few years). You can run the latest version of Java on Windows, Macintosh, and Linux computers.

I assume that you can navigate your computer’s common menus and dialog boxes. You don’t have to be a Windows, Linux, or Macintosh power user, but you should be able to start a program, find a file, put a file into a certain directory — that sort of thing. Most of the time, when you practice the stuff in this book, you’re typing code on your keyboard, not pointing and clicking the mouse.

On those rare occasions when you need to drag and drop, cut and paste, or plug and play, I guide you carefully through the steps. But your computer may be configured in any of several billion ways, and my instructions may not quite fit your special situation. So when you reach one of these platform-specific tasks, try following the steps in this book. If the steps don’t quite fit, send me an email message or consult a book with instructions tailored to your system.

I assume that you can think logically.

That’s all there is to computer programming — thinking logically. If you can think logically, you’ve got it made. If you don’t believe that you can think logically, read on. You may be pleasantly surprised.

I assume that you know little or nothing about computer programming.

This isn’t one of those “all things to all people” books. I don’t please the novice while I tease the expert. I aim this book specifically toward the novice — the person who has never programmed a computer or has never felt comfortable programming a computer. If you’re one of these people, you’re reading the right book.

How This Book Is Organized

This book is divided into subsections, which are grouped into sections, which come together to make chapters, which are lumped finally into five parts. (When you write a book, you get to know your book’s structure pretty well. After months of writing, you find yourself dreaming in sections and chapters when you go to bed at night.) The parts of the book are listed here.

Part 1: Getting Started with Java Programming

The chapters in Part 1 prepare you for the overall programming experience. In these chapters, you find out what programming is all about and get your computer ready for writing and testing programs.

Part 2: Writing Your Own Java Programs

This part covers the basic building blocks — the elements in any Java program and in any program written using a Java-like language. In this part, you discover how to represent data and how to get new values from existing values. The program examples are short, but cute.

Part 3: Controlling the Flow

Part 3 has some of my favorite chapters. In these chapters, you make the computer navigate from one part of your program to another. Think of your program as a big mansion, with the computer moving from room to room. Sometimes the computer chooses between two or more hallways, and sometimes the computer revisits rooms. As a programmer, your job is to plan the computer’s rounds through the mansion. It’s great fun.

Part 4: Using Program Units

Have you ever solved a big problem by breaking it into smaller, more manageable pieces? That’s exactly what you do in Part 4 of this book. You discover the best ways to break programming problems into pieces and to create solutions for the newly found pieces. You also find out how to use other peoples’ solutions. It feels like stealing, but it’s not.

This part also contains a chapter about programming with windows, buttons, and other graphical items. If your mouse feels ignored by the examples in this book, read Chapter 20.

Part 5: The Part of Tens

The Part of Tens is a little beginning-programmer’s candy store. In The Part of Tens, you can find lists — lists of tips, resources, and all kinds of interesting goodies.

I added an article at www.dummies.com to help you feel comfortable with Java’s documentation (www.dummies.com/programming/java/making-sense-of-javas-api-documentation, to be precise). I can’t write programs without my Java programming documentation. In fact, no Java programmer can write programs without those all-important docs. These docs are in web page format, so they’re easy to find and easy to navigate. But if you’re not used to all the terminology, the documentation can be overwhelming.

Icons Used in This Book

If you could watch me write this book, you’d see me sitting at my computer, talking to myself. I say each sentence several times in my head. When I have an extra thought, a side comment, or something that doesn’t belong in the regular stream, I twist my head a little bit. That way, whoever’s listening to me (usually nobody) knows that I’m off on a momentary tangent.

Of course, in print, you can’t see me twisting my head. I need some other way of setting a side thought in a corner by itself. I do it with icons. When you see a Tip icon or a Remember icon, you know that I’m taking a quick detour.

Here’s a list of icons that I use in this book:

A tip is an extra piece of information — something helpful that the other books may forget to tell you.

Everyone makes mistakes. Heaven knows that I’ve made a few in my time. Anyway, when I think of a mistake that people are especially prone to make, I write about the mistake in a Warning icon.

Sometimes I want to hire a skywriting airplane crew. “Barry,” says the white smoky cloud, “if you want to compare two numbers, use the double equal sign. Please don’t forget to do this.” Because I can’t afford skywriting, I have to settle for something more modest. I create a Remember icon.

Writing computer code is an activity, and the best way to learn an activity is to practice it. That’s why I’ve created things for you to try in order to reinforce your knowledge. Many of these are confidence-builders, but some are a bit more challenging. When you first start putting things into practice, you’ll discover all kinds of issues, quandaries, and roadblocks that didn’t occur to you when you started reading about the material. But that’s a good thing. Keep at it! Don’t become frustrated. Or, if you do become frustrated, visit this book’s website (www.allmycode.com/BeginProg) for hints and solutions.

Occasionally, I run across a technical tidbit. The tidbit may help you understand what the people behind the scenes (the people who developed Java) were thinking. You don’t have to read it, but you may find it useful. You may also find the tidbit helpful if you plan to read other (more geeky) books about Java.

This icon calls attention to useful material that you can find online. (You don’t have to wait long to see one of these icons. I use one at the end of this introduction!)

“If you don’t remember what such-and-such means, see blah-blah-blah,” or “For more information, read blahbity-blah-blah.”

Beyond the Book

In addition to what you’re reading right now, this book comes with a free access-anywhere Cheat Sheet containing code that you can copy and paste into your own Java program. To get this Cheat Sheet, simply go to www.dummies.com and type Beginning Programming with Java For Dummies Cheat Sheet in the Search box.

Where to Go from Here

If you’ve gotten this far, you’re ready to start reading about computer programming. Think of me (the author) as your guide, your host, your personal assistant. I do everything I can to keep things interesting and, most importantly, help you understand.

If you like what you read, send me an email, post on my Facebook wall, or give me a tweet. My email address, which I created just for comments and questions about this book, is [email protected]. My Facebook page is /allmycode, and my Twitter handle is @allmycode. And don’t forget: To get the latest information, visit this book’s support website — http://allmycode.com/BeginProg.

Part 1

Getting Started with Java Programming

IN THIS PART …

Getting psyched up to be a Java developer

Installing the software

Running some sample programs

Chapter 1

Getting Started

IN THIS CHAPTER

Realizing what computer programming is all about

Understanding the software that enables you to write programs

Revving up to use an integrated development environment

Computer programming? What’s that? Is it technical? Does it hurt? Is it politically correct? Does Google control it? Why would anyone want to do it? And what about me? Can I learn to do it?

What’s It All About?

You’ve probably used a computer to do word processing. Type a letter, print it, and then send the printout to someone you love. If you have easy access to a computer, you’ve probably surfed the web. Visit a page, click a link, and see another page. It’s easy, right?

Well, it’s easy only because someone told the computer exactly what to do. If you take a computer directly from the factory and give no instructions to this computer, the computer can’t do word processing, it can’t surf the web, and it can’t do anything. All a computer can do is follow the instructions that people give to it.

Now imagine that you’re using Microsoft Word to write the great American novel, and you come to the end of a line. (You’re not at the end of a sentence; just the end of a line.) As you type the next word, the computer’s cursor jumps automatically to the next line of type. What’s going on here?

Well, someone wrote a computer program — a set of instructions telling the computer what to do. Another name for a program (or part of a program) is code.Listing 1-1 shows you what some of Microsoft Word’s code may look like.

LISTING 1-1 A Few Lines in a Computer Program

if (columnNumber > 60) { wrapToNextLine();} else { continueSameLine();}

If you translate Listing 1-1 into plain English, you get something like this:

If the column number is greater than 60,then go to the next line.Otherwise (if the column number isn’t greater than 60),then stay on the same line.

Somebody has to write code of the kind shown in Listing 1-1. This code, along with millions of other lines of code, makes up the program called Microsoft Word.

And what about web surfing? You click a link that’s supposed to take you directly to Facebook. Behind the scenes, someone has written code of the following kind:

Go to <a href="http://www.facebook.com">Facebook</a>.

One way or another, someone has to write a program. That someone is called a programmer.

Telling a computer what to do

Everything you do with a computer involves gobs and gobs of code. For example, every computer game is really a big (make that “very big”!) bunch of computer code. At some point, someone had to write the game program:

if (person.touches(goldenRing)) { person.getPoints(10);}

Without a doubt, the people who write programs have valuable skills. These people have two important qualities:

They know how to break big problems into smaller, step-by-step procedures.

They can express these steps in a very precise language.

A language for writing steps is called a programming language, and Java is just one of several thousand useful programming languages. The stuff in Listing 1-1 is written in the Java programming language.

Pick your poison

This book isn’t about the differences among programming languages, but you should see code in some other languages so you understand the bigger picture. For example, there’s another language, Visual Basic, whose code looks a bit different from code written in Java. An excerpt from a Visual Basic program may look like this:

If columnNumber > 60 Then Call wrapToNextLineElse Call continueSameLineEnd If

The Visual Basic code looks more like ordinary English than the Java code in Listing 1-1. But, if you think that Visual Basic is like English, then just look at some code written in COBOL:

IF COLUMN-NUMBER IS GREATER THAN 60 THEN PERFORM WRAP-TO-NEXT-LINEELSE PERFORM CONTINUE-SAME-LINEEND-IF.

At the other end of the spectrum, you find languages like Forth. Here’s a snippet of code written in Forth:

: WRAP? 60 > IF WRAP_TO_NEXT_LINE? ELSE CONTINUE_SAME_LINE? THEN ;

Computer languages can be very different from one another, but in some ways, they’re all the same. When you get used to writing IF COLUMN-NUMBER IS GREATER THAN 60, you can also become comfortable writing if (columnNumber > 60). It’s just a mental substitution of one set of symbols for another. Eventually, writing things like if (columnNumber > 60) becomes second nature.

From Your Mind to the Computer’s Processor

When you create a new computer program, you go through a multistep process. The process involves three important tools:

Compiler:

A compiler translates your code into computer-friendly (human-unfriendly) instructions.

Virtual machine:

A virtual machine steps through the computer-friendly instructions.

Application programming interface:

An application programming interface contains useful prewritten code.

The next three sections describe each of the three tools.

Translating your code

You may have heard that computers deal with zeros and ones. That’s certainly true, but what does it mean? Well, for starters, computer circuits don’t deal directly with letters of the alphabet. When you see the word Start on your computer screen, the computer stores the word internally as 01010011 01110100 01100001 01110010 01110100. That feeling you get of seeing a friendly looking five-letter word is your interpretation of the computer screen’s pixels, and nothing more. Computers break everything down into very low-level, unfriendly sequences of zeros and ones and then put things back together so that humans can deal with the results.

So what happens when you write a computer program? Well, the program has to get translated into zeros and ones. The official name for the translation process is compilation. Without compilation, the computer can’t run your program.

I compiled the code in Listing 1-1. Then I did some harmless hacking to help me see the resulting zeros and ones. What I saw was the mishmash in Figure 1-1.

FIGURE 1-1: My computer understands these zeros and ones, but I don’t.

The compiled mumbo jumbo in Figure 1-1 goes by many different names:

Most Java programmers call it

bytecode.

I often call it a

.class file.

That’s because, in Java, the bytecode gets stored in files named

SomethingOrOther

.class.

To emphasize the difference, Java programmers call

Listing 1-1

the

source code

and refer to the zeros and ones in

Figure 1-1

as

object code.

To visualize the relationship between source code and object code, see Figure 1-2. You can write source code and then get the computer to create object code from your source code. To create object code, the computer uses a special software tool called a compiler.

FIGURE 1-2: The computer compiles source code to create object code.

Your computer’s hard drive may have a file named javac or javac.exe. This file contains that special software tool — the compiler. (Hey, how about that? The word javac stands for “Java compiler!”) As a Java programmer, you often tell your computer to build some new object code. Your computer fulfills this wish by going behind the scenes and running the instructions in the javac file.

WHAT IS BYTECODE, ANYWAY?

Look at Listing 1-1 and at the listing’s translation into bytecode in Figure 1-1. You may be tempted to think that a bytecode file is just a cryptogram — substituting zeros and ones for the letters in words like if and else. But it doesn’t work that way at all. In fact, the most important part of a bytecode file is the encoding of a program’s logic.

The zeros and ones in Figure 1-1 describe the flow of data from one part of your computer to another. I illustrate this flow in the following figure. But remember: This figure is just an illustration. Your computer doesn’t look at this particular figure, or at anything like it. Instead, your computer reads a bunch of zeros and ones to decide what to do next.

Don’t bother to absorb the details in my attempt at graphical representation in the figure. It’s not worth your time. The thing you should glean from my mix of text, boxes, and arrows is that bytecode (the stuff in a .class file) contains a complete description of the operations that the computer is to perform. When you write a computer program, your source code describes an overall strategy — a big picture. The compiled bytecode turns the overall strategy into hundreds of tiny, step-by-step details. When the computer “runs your program,” the computer examines this bytecode and carries out each of the little step-by-step details.

Running code

Several years ago, I spent a week in Copenhagen. I hung out with a friend who spoke both Danish and English fluently. As we chatted in the public park, I vaguely noticed some kids orbiting around us. I don’t speak a word of Danish, so I assumed that the kids were talking about ordinary kid stuff.

Then my friend told me that the kids weren’t speaking Danish. “What language are they speaking?” I asked.

“They’re talking gibberish,” she said. “It’s just nonsense syllables. They don’t understand English, so they’re imitating you.”

Now to return to present-day matters. I look at the stuff in Figure 1-1, and I’m tempted to make fun of the way my computer talks. But then I’d be just like the kids in Copenhagen. What’s meaningless to me can make perfect sense to my computer. When the zeros and ones in Figure 1-1 percolate through my computer’s circuits, the computer “thinks” the thoughts shown in Figure 1-3.

FIGURE 1-3: What the computer gleans from a bytecode file.

Everyone knows that computers don’t think, but a computer can carry out the instructions depicted in Figure 1-3. With many programming languages (languages like C++ and COBOL, for example), a computer does exactly what I’m describing. A computer gobbles up some object code and does whatever the object code says to do.

That’s how it works in many programming languages, but that’s not how it works in Java. With Java, the computer executes a different set of instructions. The computer executes instructions like the ones in Figure 1-4.

FIGURE 1-4: How a computer runs a Java program.

The instructions in Figure 1-4 tell the computer how to follow other instructions. Instead of starting with Get columnNumber from memory, the computer’s first instruction is, “Do what it says to do in the bytecode file.” (Of course, in the bytecode file, the first instruction happens to be Get columnNumber from memory.)

There’s a special piece of software that carries out the instructions in Figure 1-4. That special piece of software is called the Java Virtual Machine (JVM). The JVM walks your computer through the execution of some bytecode instructions. When you run a Java program, your computer is really running the JVM. That JVM examines your bytecode, zero by zero, one by one, and carries out the instructions described in the bytecode.

Many good metaphors can describe the JVM. Think of the JVM as a proxy, an errand boy, a go-between. One way or another, you have the situation shown in Figure 1-5. On the (a) side is the story you get with most programming languages — the computer runs some object code. On the (b) side is the story with Java — the computer runs the JVM, and the JVM follows the bytecode’s instructions.

FIGURE 1-5: Two ways to run a computer program.

Your computer’s hard drive may have files named javac and java (or javac.exe and java.exe). A java (or java.exe) file contains the instructions illustrated previously in Figure 1-4 — the instructions in the JVM. As a Java programmer, you often tell your computer to run a Java program. Your computer fulfills this wish by going behind the scenes and running the instructions in the java file.

WRITE ONCE, RUN ANYWHERE

When Java first hit the tech scene in 1995, the language became popular almost immediately. This happened in part because of the JVM. The JVM is like a foreign language interpreter, turning Java bytecode into whatever native language a particular computer understands. So if you hand my Windows computer a Java bytecode file, the computer’s JVM interprets the file for the Windows environment. If you hand the same Java bytecode file to my colleague’s Macintosh, the Macintosh JVM interprets that same bytecode for the Mac environment.

Look again at Figure 1-5. Without a virtual machine, you need a different kind of object code for each operating system. But with the JVM, just one piece of bytecode works on Windows machines, Unix boxes, Macs, or whatever. This is called portability, and in the computer-programming world, portability is a precious commodity. Think about all the people using computers to browse the Internet. These people don’t all run Microsoft Windows, but each person’s computer can have its own bytecode interpreter — its own JVM.

The marketing folks at Oracle call it the Write Once, Run Anywhere model of computing. I call it a great way to create software.

Code you can use

During the early 1980s, my cousin-in-law Chris worked for a computer software firm. The firm wrote code for word processing machines. (At the time, if you wanted to compose documents without a typewriter, you bought a “computer” that did nothing but word processing.) Chris complained about being asked to write the same old code over and over again. “First, I write a search-and-replace program. Then I write a spell checker. Then I write another search-and-replace program. Then, a different kind of spell checker. And then, a better search-and-replace.”

How did Chris manage to stay interested in his work? And how did Chris’s employer manage to stay in business? Every few months, Chris had to reinvent the wheel. Toss out the old search-and-replace program and write a new program from scratch. That’s inefficient. What’s worse, it’s boring.

For years, computer professionals were seeking the Holy Grail — a way to write software so that it’s easy to reuse. Don’t write and rewrite your search-and-replace code. Just break the task into tiny pieces. One piece searches for a single character, another piece looks for blank spaces, and a third piece substitutes one letter for another. When you have all the pieces, just assemble these pieces to form a search-and-replace program. Later on, when you think of a new feature for your word-processing software, you reassemble the pieces in a slightly different way. It’s sensible, it’s cost efficient, and it’s much more fun.

The late 1980s saw several advances in software development, and by the early 1990s, many large programming projects were being written from prefab components. Java came along in 1995, so it was natural for the language’s founders to create a library of reusable code. The library included about 250 programs, including code for dealing with disk files, code for creating windows, and code for passing information over the Internet. Since 1995, this library has grown to include more than 4,000 programs. This library is called the Application Programming Interface (API).

Every Java program, even the simplest one, calls on code in the Java API. This Java API is both useful and formidable. It’s useful because of all the things you can do with the API’s programs. It’s formidable because the API is extensive. No one memorizes all the features made available by the Java API. Programmers remember the features that they use often and look up the features that they need in a pinch. They look up these features in an online document called the API Specification (known affectionately to most Java programmers as the API documentation, or the Javadocs).

The API documentation (see http://docs.oracle.com/javase/8/docs/api) describes the thousands of features in the Java API. As a Java programmer, you consult this API documentation on a daily basis. You can bookmark the documentation at the Oracle website and revisit the site whenever you need to look up something, or you can save time by downloading your own copy of the API docs using the links found at www.oracle.com/technetwork/java/javase/downloads/index.html.

Your Java Programming Toolset

To write Java programs, you need the tools described previously in this chapter:

You need a Java compiler.

(Refer to the section “

Translating your code

.”)

You need a JVM.

(Refer to the section “

Running code

.”)

You need the Java API.

(Refer to the section “

Code you can use

.”)

You need access to the Java API documentation.

(Again, refer to the “

Code you can use

” section.)

You also need some less exotic tools:

You need an editor to compose your Java programs.Listing 1-1 contains part of a computer program. When you come right down to it, a computer program is a big bunch of text. So, to write a computer program, you need an editor — a tool for creating text documents.

An editor is a lot like Microsoft Word, or like any other word processing program. The big difference is that an editor adds no formatting to your text — no bold, italic, or distinctions among fonts. Computer programs have no formatting whatsoever. They have nothing except plain old letters, numbers, and other familiar keyboard characters.

When you edit a program, you may see bold text, italic text, and text in several colors. But your program contains none of this formatting. If you see stuff that looks like formatting, it’s because the editor that you’re using does syntax highlighting. With syntax highlighting, an editor makes the text appear to be formatted in order to help you understand the structure of your program. Believe me, syntax highlighting is very helpful.

You need a way to issue commands.

You need a way to say things like “compile this program” and “run the JVM.” Every computer provides ways of issuing commands. (You can double-click icons or type verbose commands in a Run dialog box.) But when you use your computer’s facilities, you jump from one window to another. You open one window to read Java documentation, another window to edit a Java program, and a third window to start up the Java compiler. The process can be

tedious.

A tool for creating code

In the best of all possible worlds, you do all your program editing, documentation reading, and command issuing through one nice interface. This interface is called an integrated development environment(IDE).

A typical IDE divides your screen’s work area into several panes — one pane for editing programs, another pane for listing the names of programs, a third pane for issuing commands, and other panes to help you compose and test programs. You can arrange the panes for quick access. Better yet, if you change the information in one pane, the IDE automatically updates the information in all the other panes.

An IDE helps you move seamlessly from one part of the programming endeavor to another. With an IDE, you don’t have to worry about the mechanics of editing, compiling, and running a JVM. Instead, you can worry about the logic of writing programs. (Wouldn’t you know it? One way or another, you always have something to worry about!)

In the chapters that follow, I describe basic features of the Eclipse IDE. Eclipse has many bells and whistles, but you can ignore most of them and learn to repeat a few routine sequences of steps. After using Eclipse a few times, your brain automatically performs the routine steps. From then on, you can stop worrying about Eclipse and concentrate on Java programming.

As you read my paragraphs about Eclipse, remember that Java and Eclipse aren’t wedded to one another. The programs in this book work with any IDE that can run Java. Instead of using Eclipse, you can use IntelliJ IDEA, NetBeans, BlueJ, or any other Java IDE. In fact, if you enjoy roughing it, you can write and run this book’s programs without an IDE. You can use Notepad, TextEdit or vi, along with your operating system’s command prompt or Terminal. It’s all up to you.

What’s already on your hard drive?

You may already have some of the tools you need for creating Java programs. But, on an older computer, your tools may be obsolete. Most of this book’s examples run on all versions of Java. But some examples don’t run on versions earlier than Java 5.0. Other examples run only on Java 6, Java 7, Java 8, or later.

The safest bet is to download tools afresh. To get detailed instructions on doing the downloads, see Chapter 2.

Chapter 2

Setting Up Your Computer

IN THIS CHAPTER

Installing Java

Downloading and installing the Eclipse integrated development environment

Checking your Eclipse configuration

Getting the code in this book’s examples

This chapter goes into much more detail than you normally need. If you’re like most readers, you’ll follow the steps in the “If You Don’t Like Reading Instructions …” section. Then you’ll jump to the “Importing This Book’s Sample Programs” section, near the end of this chapter. With about 20 percent of this chapter’s contents, you’ll have 100 percent of the required software.

Of course, there are always glitches. One person has an older computer. Another person has some conflicting software. Joe has a PC and Jane has a Mac. Joe’s PC runs Windows 10 but Janis runs Windows 8. Joe misreads one of my instructions and, as a result, nothing on his screen matches the steps that I describe. Eighty percent of this chapter describes the things you do in those rare situations in which you must diagnose a problem.

If you find yourself in a real jam, there’s always an alternative. You can send an email to me at [email protected]. You can also find me on Facebook at /allmycode or on Twitter at @allmycode. I’m happy to answer questions and help you figure out what’s wrong.

So, by all means, skip anything in this chapter that you don’t need to read. You won’t break anything by following your instincts. And if you do break anything, there’s always a way to fix it.

If You Don’t Like Reading Instructions …

To start writing Java programs, you need the software that I describe in Chapter 1: a Java compiler and a Java Virtual Machine (JVM, for short). You can also use a good integrated development environment (IDE) and some sample code to get you started.

All the software you need for writing Java programs is free. The software comes as three downloads: one from this book’s website, another from Oracle, and a third from eclipse.org.

Here’s how you get the software for creating Java programs:

Visit

www.allmycode.com/BeginProg

and download a file containing all program examples in this book.

Visitwww.oracle.com/technetwork/java/javase/downloadsand get the latest available version of the JDK.

At the top of the page, you might see links and buttons for Java 8. That’s okay, but to get the most from this book’s content, I recommend Java 9. With Java 9, you can run JShell, a new interactive environment for testing Java features. If Oracle’s web page highlights Java 8, scroll down to find an early access preview of Java 9. Follow the links and buttons to get the cutting edge technology.

Choose a version of the software that matches your operating system (Windows, Macintosh, or whatever). If you have trouble choosing between the JRE and the JDK, pick the JDK.

If you run Windows and you have trouble choosing between 32-bit software and 64-bit software, flip a coin and make a note of your choice. (If you make the wrong choice, you’ll get an error message when you try to install Java or when you try to launch the Eclipse IDE.)

Most people who have trouble with this chapter’s instructions have installed either 32-bit Java with 64-bit Eclipse or 64-bit Java with 32-bit Eclipse. If you experience pain when you get to Step 6, download and install alternative versions of Java or Eclipse.

Find the icon representing the Java software that you downloaded in Step 2. Double-click the icon to begin installing Java.

If you’re in a hurry (and who isn’t?), you may benefit from a quick visit to http://java.com. The http://java.com website offers a hassle-free, 1-click Java installer. (Simply click the big Java Download button. You can’t miss it.) The Java Download button doesn’t work on all computers. But if it works for you, with a wave of a virtual magic wand, you’re finished with this step. You can bypass the complexities of the java.oracle.com website and move immediately to Step 4.

Visithttp://eclipse.org/downloadsand get the Eclipse IDE.

Most of the time, Eclipse’s website automatically checks your computer’s operating system and offers you a download that’s optimized for your system. But if the website gives a choice, select Eclipse IDE for Java Developers.

The resulting download is either an executable installer file (with the .exe extension) or a compressed archive file (with the .zip or .tar.gz extension).

If you downloaded an.exefile in Step 4, double-click this file’s icon to begin the installation of Eclipse.

If you downloaded a.zipfile or a.tar.gzfile in Step 4, extract the contents of this compressed archive.

If you have a compressed archive, you see a folder named eclipse or Eclipse.app when you uncompress it. Copy this folder to a handy place on your computer’s hard drive. For example, on my Windows computer, I end up with a C:\eclipse folder. On my Mac, I end up with an Eclipse or Eclipse.app icon inside my Applications folder.

In Windows, the blank space in the name Program Files confuses some Java software. I don’t think any of this book’s software presents such a problem, but I can’t guarantee it. If you want, extract Eclipse to your C:\Program Files or C:\Program Files (x86) folder. But make a mental note about your choice (in case you run into any trouble later).

Launch Eclipse and click the Welcome screen’s Workbench icon.

Initially, the Welcome screen’s icons may have no text labels. But when you hover over an icon, a tooltip appears. Select the icon whose tooltip has the title Workbench.

In Eclipse, import the code that you downloaded in Step 1.

For details about any of this stuff, see the next several sections.

THOSE PESKY FILENAME EXTENSIONS

The filenames displayed in Windows File Explorer or in a Finder window can be misleading. You may browse one of your directories and see the name Mortgage. The file’s real name might be Mortgage.java, Mortgage.class, Mortgage.somethingElse, or plain old Mortgage. Filename endings like .zip, .java, and .class are called filename extensions.

The ugly truth is that, by default, Windows and Macs hide many filename extensions. This awful feature tends to confuse programmers. So, if you don’t want to be confused, change your computer’s system-wide settings. Here’s how you do it:

In Windows 10: In the taskbar’s Search box, type File Explorer Options. On the list of choices that appears, choose File Explorer Options. Then follow the instructions in the In All Versions of Windows bullet.In Windows 8: On the Start screen, hold down the Windows key while pressing Q. In the resulting search box, type Folder Options and then press Enter. Then follow the instructions in the In All Versions of Windows bullet.In Windows 7: Choose Start ⇒   Control Panel ⇒   Appearance and Personalization ⇒   Folder Options. Then follow the instructions in the In All Versions of Windows bullet.In all versions of Windows (7 and newer): Follow the instructions in one of the preceding bullets. Then, in the Folder Options (or File Explorer Options) dialog box, click the View tab. Look for the Hide File Extensions for Known File Types option. Make sure that this check box is not selected.In Mac OS X: On the Finder application’s menu, select Preferences. In the resulting dialog box, select the Advanced tab and look for the Show All File Extensions option. Make sure that this check box is selected.In Linux: Linux distributions tend not to hide filename extensions. So, if you use Linux, you probably don’t have to worry about this. But I haven’t checked all Linux distributions. So, if your files are named Mortgage instead of Mortgage.java or Mortgage.class, check the documentation specific to your Linux distribution.

Getting This Book’s Sample Programs

To get copies of this book’s sample programs, visit http://allmycode.com/BeginProg and click the link to download the programs in this book. Save the download file (BeginProgJavaDummies5.zip) to your computer’s hard drive.

In some cases, you click a download link but your web browser doesn’t offer you the option to save a file. If this happens to you, right-click the link (or Control-click on a Mac). On the resulting context menu, select Save Target As, Save Link As, Download Linked File As, or a similarly labeled menu item.

Most web browsers save files to a Downloads directory on your computer’s hard drive. But your browser may be configured a bit differently. One way or another, make note of the folder containing the downloaded BeginProgJavaDummies5.zip file.

COMPRESSED ARCHIVE FILES

When you visit www.allmycode.com/BeginProg and you download this book’s Java examples, you download a file named BeginProgJavaDummies5.zip. A .zip file is a single file that encodes a bunch of smaller files and folders. For example, my BeginProgJavaDummies5.zip file encodes folders named 06-01, 06-02, and so on. The 06-02 folder contains some subfolders, which in turn contain files. (The folder named 06-02 contains the code in Listing 6-2 — the second listing in Chapter 6.)

A .zip file is an example of a compressed archive file. Some other examples of compressed archives include .tar.gz files, .rar files, and .cab files. Uncompressing a file means extracting the original files stored inside the big archive file. (For a .zip file, another word for uncompressing is unzipping.) Uncompressing normally re-creates the folder structure encoded in the archive file. So, after uncompressing my BeginProgJavaDummies5.zip file, your hard drive has folders named 06-01, 06-02, with subfolders named src and bin, which in turn contain files named SnitSoft.java, SnitSoft.class, and so on.

When you download BeginProgJavaDummies5.zip, your web browser may uncompress the file automatically for you. If not, you can see the .zip file’s contents by double-clicking the file’s icon. (In fact, you can copy the file’s contents and perform other file operations after double-clicking the file’s icon.) One way or another, don’t worry about uncompressing my BeginProgJavaDummies5.zip file. When you follow this chapter’s instructions, you import the contents of my BeginProgJavaDummies5.zip file into the Eclipse IDE. And behind the scenes, Eclipse’s import process uncompresses the .zip file.

Setting Up Java

You can get the latest, greatest versions of Java by visiting www.oracle.com/technetwork/java/javase/downloads. Look for the newest available version of the JDK. Select a version that runs on your computer’s operating system.

Figure 2-1 shows me clicking a Download JDK button (circa March 2014) at the Oracle website. When you visit the site, the page on your computer screen probably looks a lot like Figure 2-1, but you might see Java SE 9 instead of Java SE 8.

If you see Java 9, go for it.

If you see Java 8 instead of Java 9, scroll down to find an early access Java 9 preview.

With plain, old Java 8, you can run all the programs in this book. But if you have Java 9, you can use JShell — a tool for experimenting quickly and easily with snippets of Java’s code.

FIGURE 2-1: Getting the Java JDK.