Java All in One For Dummies 4th Edition

The one Java book that’s designed to replace an entire shelf full of the dull, tedious titles you’d otherwise have to buy.


Doug Lowe


963 Pages

158538 Reads

30 Downloads

English

PDF Format

15.9 MB

Java Programming

Download PDF format


  • Doug Lowe   
  • 963 Pages   
  • 23 Feb 2015
  • Page - 1

    Doug Lowe 9 IN 1 BOOKS BOOKS ® ™ read more..

  • Page - 2

    Start with Cheat Sheets Cheat Sheets include Get Smart at Dummies.com Dummies.com makes your life easier with 1,000s of answers on everything from removing wallpaper to using the latest version of Windows. Check out our Plus, each month you can win valuable prizes by entering our Dummies.com sweepstakes. * Want a weekly dose of Dummies? Sign up for Newsletters on read more..

  • Page - 3

    by Doug Lowe Java® ALL -IN- ONE 4th Edition read more..

  • Page - 4

    Java® All-in-One For Dummies®, 4th Edition Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com Copyright © 2014 by John Wiley & Sons, Inc., Hoboken, New Jersey Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, read more..

  • Page - 5

    Contents at a Glance Introduction ................................................................ 1 Book I: Getting Started with Java Basics ....................... 5 Chapter 1: Welcome to Java ............................................................................................. 7 Chapter 2: Installing and Using Java Tools ................................................................... 19 Chapter 3: Working with read more..

  • Page - 6

    Book V: Programming Techniques ............................. 445 Chapter 1: Programming Threads ............................................................................... 447 Chapter 2: Network Programming ............................................................................... 475 Chapter 3: Using Regular Expressions ........................................................................ 499 Chapter 4: Using Recursion read more..

  • Page - 7

    Table of Contents Introduction ................................................................. 1 About this Book ............................................................................................... 1 Foolish Assumptions ....................................................................................... 2 Icons Used in This Book ................................................................................. 3 Beyond the Book read more..

  • Page - 8

    Java All-in-One For Dummies, 4th Edition vi Chapter 3: Working with TextPad ...............................33 Downloading and Installing TextPad .......................................................... 33 Editing Source Files ....................................................................................... 34 Compiling a Program ..................................................................................... 36 Running a read more..

  • Page - 9

    Table of Contents vii The Boolean type ................................................................................. 74 Wrapper classes ................................................................................... 74 Using Reference Types ........................................................................ 75 Working with Strings ..................................................................................... 77 Declaring and read more..

  • Page - 10

    Java All-in-One For Dummies, 4th Edition viii Chapter 4: Making Choices ...................................123 Using Simple Boolean Expressions ........................................................... 123 Using if Statements ...................................................................................... 125 Simple if statements .......................................................................... 126 if-else statements read more..

  • Page - 11

    Table of Contents ix Using the switch Statement ........................................................................ 172 Viewing a boring switch example, complete with flowchart........ 173 Putting if statements inside switch statements ............................. 175 Creating Character Cases ........................................................................... 176 Intentionally Leaving Out a Break Statement read more..

  • Page - 12

    Java All-in-One For Dummies, 4th Edition x Book III: Object-Oriented Programming .......................221 Chapter 1: Understanding Object-Oriented Programming............223 What Is Object-Oriented Programming? ................................................... 223 Understanding Objects ............................................................................... 224 Objects have identity read more..

  • Page - 13

    Table of Contents xi Chapter 4: Using Subclasses and Inheritance ...................261 Introducing Inheritance .............................................................................. 261 Motorcycles, trains, and automobiles............................................. 262 Game play ........................................................................................... 263 A businesslike example read more..

  • Page - 14

    Java All-in-One For Dummies, 4th Edition xii The clone Method ........................................................................................ 309 Implementing the clone method ...................................................... 309 Using clone to create a shallow copy .............................................. 312 Creating deep copies ......................................................................... 313 The Class read more..

  • Page - 15

    Table of Contents xiii Using the StringBuilder and StringBuffer Classes ................................... 362 Creating a StringBuilder object ........................................................ 363 Using StringBuilder methods ........................................................... 363 Viewing a StringBuilder example ..................................................... 366 Using the CharSequence Interface read more..

  • Page - 16

    Java All-in-One For Dummies, 4th Edition xiv Chapter 5: Creating Generic Collection Classes .................421 Why Generics? ............................................................................................. 422 Creating a Generic Class ............................................................................. 423 A Generic Stack Class .................................................................................. 424 read more..

  • Page - 17

    Table of Contents xv Introducing BART ........................................................................................ 485 The BartQuote class .......................................................................... 486 The BartServer program ................................................................... 488 The BartClient program .................................................................... 491 Working with BartServer 2.0 read more..

  • Page - 18

    Java All-in-One For Dummies, 4th Edition xvi Looking Closer at the LocalDate Class ..................................................... 537 Extracting Information About a Date ........................................................ 539 Comparing Dates ......................................................................................... 540 Calculating with Dates read more..

  • Page - 19

    Table of Contents xvii Chapter 3: Getting Input from the User ..........................601 Using Text Fields ......................................................................................... 601 Looking at a sample program ........................................................... 603 Using text fields for numeric entry .................................................. 605 Creating a validation class read more..

  • Page - 20

    Java All-in-One For Dummies, 4th Edition xviii Book VII: Web Programming ..................................... 673 Chapter 1: Creating Applets ...................................675 Understanding Applets ............................................................................... 675 Working with the JApplet Class ................................................................. 676 Looking at a Sample Applet read more..

  • Page - 21

    Table of Contents xix Getting the contents of a directory ................................................. 723 Renaming files .................................................................................... 724 Deleting a file ...................................................................................... 725 Using Command-Line Parameters ............................................................. 725 Choosing Files in a Swing read more..

  • Page - 22

    Java All-in-One For Dummies, 4th Edition xx Updating and Deleting Rows ...................................................................... 778 Using the delete statement ............................................................... 778 Using the update statement ............................................................. 779 Chapter 4: Using JDBC to Connect to a Database ................783 Setting Up a Driver read more..

  • Page - 23

    Table of Contents xxi Setting a component’s font ............................................................... 819 Getting a list of available fonts ......................................................... 820 Viewing a program that plays with fonts ........................................ 820 Working with Color ..................................................................................... 823 Creating colors read more..

  • Page - 24

    Java All-in-One For Dummies, 4th Edition xxii Bouncing the Ball ......................................................................................... 873 Bouncing a Bunch of Balls .......................................................................... 875 Creating a Ball class........................................................................... 875 Animating random balls read more..

  • Page - 25

    Introduction W elcome to Java All-in-One For Dummies, 4th Edition — the one Java book that’s designed to replace an entire shelf full of the dull, tedious titles you’d otherwise have to buy. This book contains all the basic information you need to know to get going with Java programming, starting with writing statements and using variables and ending with techniques read more..

  • Page - 26

    Foolish Assumptions 2 of the programming topics covered in this book. But then, who would carry them home from the bookstore for you? And where would you find the shelf space to store them? And when will you find the time to read them? In this book, all the information you need is conveniently packaged for you in-between one set of covers. And all of the read more..

  • Page - 27

    Icons Used in This Book 3 reasons; maybe you want to become a professional Java programmer, or maybe you are a C# or C++ programmer who occasionally needs to work in Java. On the other hand, maybe you think programming in Java would make an interesting hobby. Regardless of your motivation, I do assume that you are a reasonably intelligent person. You don’t have read more..

  • Page - 28

    Beyond the Book 4 Beyond the Book There’s much more to this book than the thousand or so pages you are holding in your hands. Go online to find the following: ✦ The cheat sheet for this book is at www.dummies.com/cheatsheet/javaaio In the cheat sheet, you’ll find helpful reference information for elements of Java you’ll use all the time, such as if statements read more..

  • Page - 29

    Visit www.dummies.com for great Dummies content online. Book I Getting Started with Java Basics read more..

  • Page - 30

    Contents at a Glance Contents at a Glance Chapter 1: Welcome to Java.....................................7 What Is Java, and Why Is It So Great? .............................................................................7 Java versus Other Languages ..........................................................................................11 Important Features of the Java Language read more..

  • Page - 31

    Chapter 1: Welcome to Java In This Chapter ✓ Finding out about programming ✓ Scoping out Java ✓ Comparing Java with other programming languages ✓ Understanding Java’s incomprehensible version numbers T his chapter is a gentle introduction to the world of Java. In the next few pages, you find out what Java is, where it came from, and where it’s going. You also read more..

  • Page - 32

    What Is Java, and Why Is It So Great? 8 Java differs from other programming languages in a couple of significant ways, however. I point out the most important differences in the following sections. Platform independence One of the main reasons Java is so popular is its platform independence, which simply means that Java programs can be run on many types of comput- ers. A read more..

  • Page - 33

    Book I Chapter 1 W elcome to Java What Is Java, and Why Is It So Great? 9 ✦ When someone asks whether your computer “has Java,” he usually means to ask, “Have you installed the Java Runtime Environment?” (You need the JRE so that you can run Java programs.) ✦ Platform independence goes only so far. If you have some obscure type of computer system — such as an read more..

  • Page - 34

    What Is Java, and Why Is It So Great? 10 Classes are closely related to objects. A class is the program code you write to create objects. The class describes the data and methods that define the object’s state and behavior. When the program executes, classes are used to create objects. Suppose you’re writing a payroll program. This program probably needs objects to read more..

  • Page - 35

    Book I Chapter 1 W elcome to Java Java versus Other Languages 11 You can find two distinct types of Java programs on the Internet: ✦ Applets: Applets are Java programs that run directly within a web browser. To run an applet, the browser starts a JVM, and that virtual machine is given a portion of the web page to work with. Then the vir- tual machine runs the read more..

  • Page - 36

    Important Features of the Java Language 12 Many other similarities aren’t evident in these simple examples, but the examples bring the major difference between C and Java front and center: Object-oriented programming rears its ugly head even in simple examples. Consider the following points: ✦ In Java, even the simplest program is a class, so you have to provide a line that read more..

  • Page - 37

    Book I Chapter 1 W elcome to Java Important Features of the Java Language 13 Type checking All programming languages must deal in one way or the other with type checking — the way that a language handles variables that store different types of data. Numbers, strings, and dates, for example, are commonly used data types available in most programming languages. Most programming read more..

  • Page - 38

    Important Features of the Java Language 14 In Java, every class you define creates a new type of data for the language to work with. Thus, the data types you have available to you in Java aren’t just simple predefined types, such as numbers and strings. You can create your own types. If you’re writing a payroll system, you might create an Employee type. Then you can read more..

  • Page - 39

    Book I Chapter 1 W elcome to Java Important Features of the Java Language 15 In C++ and similar languages, you must write code that explicitly releases that memory so that other programs can access it. If you don’t do this, or if you do it wrong, your program might develop a memory leak. In a memory leak, your program slowly but surely sucks memory away from other read more..

  • Page - 40

    On the Downside: Java’s W eaknesses 16 On the Downside: Java’s W eaknesses So far, I’ve been tooting Java’s horn pretty loudly. Lest you think that figuring out how to use it is a walk in the park, the following paragraphs point out some of Java’s shortcomings (many of which have to do with the API rather than the language itself): ✦ The API is way too big. It read more..

  • Page - 41

    Book I Chapter 1 W elcome to Java Java Version Insanity 17 Java Version Insanity Like most products, Java gets periodic upgrades and enhancements. Since its initial release in 1996, Java has undergone the following version updates: ✦ Java 1.0: This version was the original version of Java, released in 1996. Most of the language is still pretty much the same as it was read more..

  • Page - 42

    What’s in a Name? 18 ✦ Java 1.8: Released in February of 2014, Java 8 (as it is known) adds some significant and long-anticipated new features to Java. One of the most important is lambda expressions, a language feature that simpli- fies certain aspects of object-oriented programming. Other new features include a completely revamped API for working with dates and times, read more..

  • Page - 43

    Chapter 2: Installing and Using Java Tools In This Chapter ✓ Downloading Java from the Oracle website ✓ Installing Java ✓ Using Java tools ✓ Getting help J ava development environments have two basic approaches. On the one hand, you can use a sophisticated integrated development environment (IDE) such as Oracle’s Java Studio Creator, IntelliJ IDEA, or Eclipse. These read more..

  • Page - 44

    Downloading and Installing the Java Development Kit 20 Downloading and Installing the Java Development Kit Before you can start writing Java programs, you have to download and install the correct version of the Java Development Kit (JDK) for the com- puter system you’re using. Oracle’s Java website provides versions for Windows, Solaris, and Unix. The following sections show you how to read more..

  • Page - 45

    Book I Chapter 2 Installing and Using Java T ools Downloading and Installing the Java Development Kit 21 Installing the JDK After you download the JDK file, you can install it by running the executable file you downloaded. The procedure varies slightly depending on your oper- ating system, but basically, you just run the JDK installation program file after you download it, as read more..

  • Page - 46

    Downloading and Installing the Java Development Kit 22 In addition to these folders, the JDK installs several files in the JDK root folder. I list these files in Table 2-2. Table 2-2 Files in the JDK Root Folder File Description README.html The Java read-me file in HTML format. README.txt The read-me file again, this time in text format. LICENSE The Java license that you agreed to read more..

  • Page - 47

    Book I Chapter 2 Installing and Using Java T ools Using Java’s Command-Line Tools 23 Figure 2-1: The Environment Variables dialog box. 4. In the System Variables list, scroll to the Path variable, select it, and then click the Edit button. A little dialog box pops up to let you edit the value of the Path variable. 5. Add the JDK bin folder to read more..

  • Page - 48

    Using Java’s Command-Line Tools 24 Compiling a program You can compile a program from a command prompt by using the javac command. Before you can do that, however, you need a program to compile. Follow these steps: 1. Using any text editor, type the following text in a file, and save it as HelloApp.java: public class HelloApp { public static void main(String[] read more..

  • Page - 49

    Book I Chapter 2 Installing and Using Java T ools Using Java’s Command-Line Tools 25 Compiling more than one file Normally, the javac command compiles only the file that you specify on the command line, but you can coax javac into compiling more than one file at a time by using any of the techniques I describe in the following paragraphs: ✦ If the Java file you read more..

  • Page - 50

    Using Java’s Command-Line Tools 26 Using Java compiler options The javac command has a gaggle of options that you can use to influence the way it compiles your programs. For your reference, I list these options in Table 2-3. Table 2-3 Java Compiler Options Option Description -g Generates all debugging info. -g:none Generates no debugging info. -g:{lines,vars,source} Generates only some read more..

  • Page - 51

    Book I Chapter 2 Installing and Using Java T ools Using Java’s Command-Line Tools 27 To use one or more of these options, type the option before or after the source filename. Either of the following commands, for example, compiles the HelloApp.java file with the -verbose and -deprecation options enabled: javac HelloWorld.java -verbose -deprecation javac -verbose -deprecation read more..

  • Page - 52

    Using Java’s Command-Line Tools 28 Understanding error messages If Java can’t find a filename that corresponds to the class, you get a simple error message indicating that the class can’t be found. Here’s what you get if you type JelloApp instead of HelloApp: C:\java\samples>java JelloApp Exception in thread "main" java.lang.NoClassDefFoundError: JelloApp This error read more..

  • Page - 53

    Book I Chapter 2 Installing and Using Java T ools Using Java’s Command-Line Tools 29 Using the javap command The javap command is called the Java disassembler because it takes class files apart and tells you what’s inside them. You won’t use this command often, but using it to find out how a particular Java statement works is fun sometimes. You can also use it to read more..

  • Page - 54

    Using Java Documentation 30 You may want to use two options with the javap command. If you use the -c option, the javap command displays the actual Java bytecodes created by the compiler for the class. And if you use the -verbose option, the byte- codes (plus a ton of other fascinating information about the innards of the class) are displayed. If you become a read more..

  • Page - 55

    Book I Chapter 2 Installing and Using Java T ools Using Java Documentation 31 Figure 2-2: The documenta- tion page for Java SE API 8 (English version). You can use this page to find complete information for any class in the API. By default, all the Java classes are listed in the frame that appears in the bottom-left corner of the page. You can limit read more..

  • Page - 56

    32 Using Java Documentation Figure 2-3: The docu- mentation page for the String class. Java Language Specification If you’re interested in learning details about some element of the Java lan- guage itself (rather than the information about a class in the API class library), visit the Java Programming Language reference page at http://docs. oracle.com/javase/specs/index.html. read more..

  • Page - 57

    Chapter 3: Working with TextPad In This Chapter ✓ Acquiring TextPad ✓ Using TextPad to edit source files ✓ Compiling Java programs ✓ Running Java programs T extPad is an inexpensive ($33) text editor that you can integrate with the Java Development Kit (JDK) to simplify the task of coding, com- piling, and running Java programs. It isn’t a true integrated development read more..

  • Page - 58

    Editing Source Files 34 Figure 3-1 shows how the Preferences dialog box appears when the Java tools are installed. As you can see, the Tools item in the tree on the left side of the dialog box includes three Java tools: Compile Java, Run Java Application, and Run Java Applet. Figure 3-1: Configuring tools in TextPad. 4. Click OK. The commands you need to compile and read more..

  • Page - 59

    Book I Chapter 3 W orking with TextPad Editing Source Files 35 The following paragraphs describe some of TextPad’s most noteworthy features for working with Java files: ✦ You can’t really tell from Figure 3-2, but T extPad uses different colors to indicate the function of each word or symbol in the program. Brackets are red so that you can spot them quickly and make read more..

  • Page - 60

    Compiling a Program 36 ✦ If you have more than one file open, you can switch between the files by using the Document Selector — the pane on the left side of the TextPad window (refer to Figure 3-2). If the Document Selector isn’t visible, choose View ➪Document Selector to summon it. ✦ Another way to switch between two (or more) files is to choose View ➪ Document Tabs. read more..

  • Page - 61

    Book I Chapter 3 W orking with TextPad Compiling a Program 37 In this example, eight compiler error messages are displayed: javac 1.8.0-ea C:\Users\Doug\Documents\Java 4E\Manuscript\Apps\Book 1\Chapter 3\HelloApp.java:5: error: unclosed string literal printHello("World!); ^ C:\Users\Doug\Documents\Java 4E\Manuscript\Apps\Book 1\Chapter read more..

  • Page - 62

    Running a Java Program 38 ^ C:\Users\Doug\Documents\Java 4E\Manuscript\Apps\Book 1\Chapter 3\HelloApp. java:12: error: reached end of file while parsing } ^ 8 errors Tool completed with exit code 1 If you double-click the first line of each error message, TextPad takes you to read more..

  • Page - 63

    Book I Chapter 3 W orking with TextPad 39 Running an Applet When the program finishes, the message Press any key to continue appears in the command window. When you press a key, the window closes, and TextPad comes back to life. In case you’re wondering, TextPad actually runs your program by creating and running a batch file — a short text file that contains read more..

  • Page - 64

    Running an Applet 40 Figure 3-5: Running an applet. read more..

  • Page - 65

    You can find an interesting programming challenge that requires use of many of the programming techniques covered in this minibook at www.dummies.com/ extras/javaaio. The challenge is to create a program that plays a simple game of Tic-Tac-Toe. Book II Programming Basics read more..

  • Page - 66

    Contents at a Glance Contents at a Glance Chapter 1: Java Programming Basics ...........................43 Looking at the Infamous Hello, W orld! Program ...........................................................43 Dealing with Keywords ......................................................................................................46 Working with Statements read more..

  • Page - 67

    Chapter 1: Java Programming Basics In This Chapter ✓ The famous Hello, World! program ✓ Basic elements of Java programs such as keywords, statements, and blocks ✓ Different ways to add comments to your programs ✓ Basic information about object-oriented programming ✓ Ways to import classes I n this chapter, you find the basics of writing simple Java programs. The read more..

  • Page - 68

    Looking at the Infamous Hello, W orld! Program 44 Listing 1-1: The HelloApp Program public class HelloApp ➝1 { ➝2 public static void main(String[] args) ➝3 { ➝4 System.out.println("Hello, World!"); ➝5 } ➝6 } ➝7 Later in this chapter, you discover in detail all the elements that make up this program. But read more..

  • Page - 69

    Looking at the Infamous Hello, W orld! Program 45 Book II Chapter 1 Java Programming Basics That means classes other than the HelloApp class can use it. All Java programs must have at least one class that declares a public method named main. The main method contains the statements that are executed when you run the program. static: You find all about the static read more..

  • Page - 70

    Dealing with Keywords 46 following the word println. In this case, the text is the string literal Hello, World! enclosed in a set of quotation marks. As a result, this statement displays the text Hello, World! on the console. Note that in Java, most (but not all) statements must end with a semicolon. Because this statement is the only one in the program, this read more..

  • Page - 71

    Dealing with Keywords 47 Book II Chapter 1 Java Programming Basics Table 1-1 Java’s Keywords abstract default goto package synchronized assert do if private this boolean double implements protected throw break else import public throws byte enum instanceof return transient case extends int short true catch false interface static try char final long strictfp void class finally native super volatile const float new switch read more..

  • Page - 72

    Working with Statements 48 When you try to compile this program, the compiler generates a total of four error messages for this one mistake: C:\Java AIO\CaseApp.java:5: '.class' expected For (int i = 0; i<5; i++) ^ C:\Java AIO\CaseApp.java:5: illegal start of type For (int i = 0; i<5; i++) read more..

  • Page - 73

    Working with Statements 49 Book II Chapter 1 Java Programming Basics Types of statements Java has many types of statements. Some statements simply create variables that you can use to store data. These types of statements are often called declaration statements and tend to look like this: int i; String s = "This is a string"; Customer c = new Customer(); Another common read more..

  • Page - 74

    Working with Statements 50 In other words, a single space is treated the same as a tab or line break or any combination of spaces, tabs, and line breaks. If you’ve programmed in Visual Basic, white space is different from what you’re used to. In Visual Basic, line breaks mark the end of statements unless special continuation characters are used. In Java, you don’t read more..

  • Page - 75

    Working with Blocks 51 Book II Chapter 1 Java Programming Basics Working with Blocks A block is a group of one or more statements that’s enclosed in braces. A block begins with an opening brace ( {) and ends with a closing brace ( }). Between the opening and closing braces, you can code one or more state- ments. Here’s a block that consists of three statements: { read more..

  • Page - 76

    Creating Identifiers 52 Note that even though a block can be treated as a single statement, you should not end a block with a semicolon. The statements within the block may require semicolons, but the block itself does not. Creating Identifiers An identifier is a word that you make up to refer to a Java programming element by name. Although you can assign read more..

  • Page - 77

    Crafting Comments 53 Book II Chapter 1 Java Programming Basics Crafting Comments A comment is a bit of text that provides explanations of your code. The com- piler ignores comments, so you can place any text you want in a comment. Using plenty of comments in your program is a good way to explain what your program does and how it works. Java has three basic types of read more..

  • Page - 78

    Introducing Object-Oriented Programming 54 Usually, traditional comments appear on separate lines. One common use for traditional comments is to place a block of comment lines at the beginning of a class to indicate information about the class — such as what the class does, who wrote it, and so on. That type of comment, however, is usually better coded as a JavaDoc comment, as read more..

  • Page - 79

    Introducing Object-Oriented Programming 55 Book II Chapter 1 Java Programming Basics object might be keeping track of, and the behavior consists of actions that the object can perform. The behaviors are represented in the class by one or more methods that can be called on to perform actions. The difference between a class and an object is similar to the difference between read more..

  • Page - 80

    Introducing Object-Oriented Programming 56 Many Java programs — in fact, many of the programs in the rest of Book II — are entirely made up of static methods. Most realistic programs, however, require that you create one or more objects that the program uses as it executes. As a result, knowing how to create simple classes and how to create objects from those classes read more..

  • Page - 81

    Introducing Object-Oriented Programming 57 Book II Chapter 1 Java Programming Basics but uses an object created from the second class, named Greeter, to actu- ally display the "Hello, World!" message on the console. The Greeter class is shown in Listing 1-3. It defines a method named sayHello that dis- plays the message. Both the HelloApp and the Greeter classes read more..

  • Page - 82

    Introducing Object-Oriented Programming 58 ➝ 10 The first line in the body of the main method creates a variable named myGreeterObject that can hold objects created from the Greeter class. Then it creates a new object using the Greeter class and assigns this object to the myGreeterObject variable. ➝ 11 The second line in the body of the main method calls read more..

  • Page - 83

    Introducing Object-Oriented Programming 59 Book II Chapter 1 Java Programming Basics Other than the fact that the second version requires roughly twice as much code as the first version, what really is the difference between these two applications? Simply put, the first version is procedural, and the second is object-oriented. In the first version of the program, the main read more..

  • Page - 84

    Importing Java API Classes 60 The important point to realize here is that the HelloApp2 class doesn’t have to be changed to use this new version of the Greeter class. Instead, all you have to do is replace the old Greeter class with the new one, recompile the Greeter class, and the HelloApp2 class won’t know the difference. That’s one of the main read more..

  • Page - 85

    Chapter 2: Working with Variables and Data Types In This Chapter ✓ Creating proper variable declarations ✓ Discovering the difference between primitive and reference types ✓ Looking at Java’s built-in data types ✓ Introducing strings ✓ Getting input from the console ✓ Getting input if you’re using an older version of Java I n this chapter, you find out the basics read more..

  • Page - 86

    Declaring Variables 62 Allowing you to use variables that you haven’t explicitly declared might seem a pretty good idea at first glance, but it’s a common source of bugs that result from misspelled variable names. Java requires that you explicitly declare vari- ables so that if you misspell a variable name, the compiler can detect your mistake and display a compiler read more..

  • Page - 87

    Book II Chapter 2 W orking with Variables and Data T ypes Declaring Variables 63 Declaring class variables A class variable is a variable that any method in a class can access, including static methods such as main. When declaring a class variable, you have two basic rules to follow: ✦ You must place the declaration within the body of the class but not within read more..

  • Page - 88

    Declaring Variables 64 Declaring instance variables An instance variable is similar to a class variable but doesn’t specify the word static in its declaration. As the name suggests, instance variables are associated with instances of classes. As a result, you can use them only when you create an instance of a class. Because static methods aren’t asso- ciated with an instance read more..

  • Page - 89

    Book II Chapter 2 W orking with Variables and Data T ypes Declaring Variables 65 helloMessage = "Hello, World!"; System.out.println(helloMessage); } } Note that you don’t specify static on a declaration for a local variable. If you do, the compiler generates an error message and refuses to compile your program. Local read more..

  • Page - 90

    Initializing Variables 66 Initializing Variables In Java, local variables are not given initial default values. The compiler checks to make sure that you have assigned a value before you use a local variable. The following example program won’t compile: public class testApp { public static void main(String[] args) { int i; read more..

  • Page - 91

    Book II Chapter 2 W orking with Variables and Data T ypes Using Final Variables (Constants) 67 You find out a lot more about expressions in Book II, Chapter 3. For now, you can just use simple literal values, such as 0 in this example. Initializing variables with initializers Java also allows you to initialize a variable on the same statement that declares the read more..

  • Page - 92

    Working with Primitive Data T ypes 68 Although you can create final local variables, most final variables are class or instance variables. To create a final class variable (sometimes called a class constant), add static final (not final static) to the declaration, as follows: static final WEEKDAYS = 5; Although it isn’t required, using all capital letters for final variable read more..

  • Page - 93

    Book II Chapter 2 W orking with Variables and Data T ypes Working with Primitive Data T ypes 69 Java makes an important distinction between primitive types and reference types. ✦ Primitive types are the data types defined by the language itself. ✦ Reference types are types defined by classes in the Java application programming interface (API) or by classes you read more..

  • Page - 94

    Working with Primitive Data T ypes 70 Integer types An integer is a whole number — that is, a number with no fractional or deci- mal portion. Java has four integer types, which you can use to store num- bers of varying sizes. The most commonly used integer type is int. This type uses 4 bytes to store an integer value that can range from about nega- tive 2 billion to read more..

  • Page - 95

    Book II Chapter 2 W orking with Variables and Data T ypes Working with Primitive Data T ypes 71 Here you can assign the value of the xInt variable to the yLong variable because yLong is larger than xInt. Java does not allow the converse, however: int xInt; long yLong; yLong = 32; xInt = yLong; The value of the yLong variable cannot be assigned to the xInt read more..

  • Page - 96

    Working with Primitive Data T ypes 72 Floating-point numbers actually use exponential notation (also called scien- tific notation) to store their values. That means that a floating-point number actually records two numbers: a base value (also called the mantissa) and an exponent. The actual value of the floating-point number is calculated by mul- tiplying the mantissa by 2 raised to read more..

  • Page - 97

    Book II Chapter 2 W orking with Variables and Data T ypes Working with Primitive Data T ypes 73 If you omit the suffix, D is assumed. As a result, you can usually omit the D suffix for double literals. Interestingly, floating-point numbers have two distinct zero values: a negative zero and a positive zero. You don’t have to worry about these much, because Java read more..

  • Page - 98

    Working with Primitive Data T ypes 74 Table 2-2 Escape Sequences for Character Constants Escape Sequence Explanation \b Backspace \t Horizontal tab \n Line feed \f Form feed \r Carriage return \" Double quote \' Single quote \\ Backslash The Boolean type A boolean type can have one of two values: true or false. Booleans are used to perform logical operations, most commonly to determine read more..

  • Page - 99

    Book II Chapter 2 W orking with Variables and Data T ypes Working with Primitive Data T ypes 75 Table 2-3 Wrapper Classes for the Primitive Types Primitive Type Wrapper Class int Integer short Short long Long byte Byte float Float double Double char Character boolean Boolean Using Reference Types In Book III, Chapter 1, you’re introduced to some of the basic concepts of object-oriented read more..

  • Page - 100

    Working with Primitive Data T ypes 76 To create a new instance of an object from a class, you use the new keyword along with the class name. This second reference to the class name is actually a call to a special routine of the class called a constructor. The constructor is responsible for initializing the new object. Here’s a statement that declares a variable read more..

  • Page - 101

    Book II Chapter 2 W orking with Variables and Data T ypes Working with Strings 77 Working with Strings A string is a sequence of text characters, such as the message "Hello, World!" displayed by the HelloApp program illustrated in this chapter and the preceding chapter. In Java, strings are an interesting breed. Java doesn’t define strings as a primitive type. read more..

  • Page - 102

    Working with Strings 78 Combining strings Combine two strings by using the plus sign (+) as a concatenation operator. (In Java-speak, combining strings is called concatenation.) The following statement combines the value of two string variables to create a third string: String hello = "Hello, "; String world = "World!"; String greeting = hello + world; The final value read more..

  • Page - 103

    Book II Chapter 2 W orking with Variables and Data T ypes Working with Strings 79 The answer is that Java automatically converts primitive values to string values whenever you use a primitive value in a concatenation. You can explicitly convert a primitive value to a string by using the toString method of the primitive type’s wrapper class. To convert the int read more..

  • Page - 104

    Converting and Casting Numeric Data 80 Wrapper parse Method Example Float parseByte(String) float x = Float. parseFloat("19.95"); Double parseByte(String) double x = Double. parseDouble("19.95"); Character (none) Boolean parseBoolean boolean x = Boolean.parseBoolean (String) ("true"); You have no real reason to do this, of course, but as you see later in this chapter, you read more..

  • Page - 105

    Book II Chapter 2 W orking with Variables and Data T ypes Converting and Casting Numeric Data 81 Figure 2-1: Numeric type conver- sions that are done automati- cally. Whenever you perform a mathematical operation on two values that aren’t of the same type, Java automatically converts one of them to the type of the other. Here are the rules Java follows when read more..

  • Page - 106

    Thinking Inside the Box 82 To cast a primitive value from one type to another, you use a cast operator, which is simply the name of a primitive type in parentheses placed before the value you want to cast. For example: double pi = 3.1314; int iPi; iPi = (int) pi; Note that the fractional part of a double is simply discarded when cast to an integer; it isn’t read more..

  • Page - 107

    Book II Chapter 2 W orking with Variables and Data T ypes Understanding Scope 83 Understanding Scope The scope of a variable refers to which parts of a class the variable exists in. In the simplest terms, every variable exists only within the block in which the variable is declared, as well as any blocks that are contained within that block. That’s why class and read more..

  • Page - 108

    Shadowing Variables 84 The following paragraphs explain the scope of each of the variables used in this class: ➝ 2 The variable x is a class variable. Its scope begins in line 2 and ends in line 27. As a result, both the main method and the myMethod method can access it. ➝ 16 The variable y is a local variable that’s initialized in line 16. As read more..

  • Page - 109

    Book II Chapter 2 W orking with Variables and Data T ypes Shadowing Variables 85 Listing 2-2: A Class That Demonstrates Shadowing public class ShadowApp { ➝2 static int x; ➝4 public static void main(String[] args) { x = 5; ➝8 System.out.println("x = " + x); ➝9 int x; ➝10 read more..

  • Page - 110

    Printing Data with System.out 86 Here is the output you will get from this program: x = 5 x = 10 ShadowApp.x = 5 The scope of a local variable that shadows a class variable doesn’t necessarily begin at the same point that the local variable’s scope begins. The shadowing begins when the local variable is declared, but the local variable’s scope doesn’t begin read more..

  • Page - 111

    Book II Chapter 2 W orking with Variables and Data T ypes Printing Data with System.out 87 Windows and other operating systems allow you to redirect standard output to some other destination — typically a file. When you do that, only the stan- dard output data is redirected. Text written to standard error is still dis- played in the console window. To redirect read more..

  • Page - 112

    Getting Input with the Scanner Class 88 Using System.out and System.err Both System.out and System.err represent instances of a class called PrintWriter, which defines the print and println methods used to write data to the console. You can use both methods with either a String argument or an argument of any primitive data type. The only difference between the print and read more..

  • Page - 113

    Book II Chapter 2 W orking with Variables and Data T ypes Getting Input with the Scanner Class 89 If you’re using an older version of Java, you should still read this section, because many of the programs in this book use the Scanner class. However, you should also read the next section, “Getting Input with the JOptionPane Class,” because that section describes a read more..

  • Page - 114

    Getting Input with the Scanner Class 90 If you’re using other classes in the java.util package, you can import the entire package by coding the import statement like this: import java.util.*; Declaring and creating a Scanner object Before you can use the Scanner class to read input from the console, you must declare a Scanner variable and create an instance of the read more..

  • Page - 115

    Book II Chapter 2 W orking with Variables and Data T ypes Getting Input with the Scanner Class 91 Notice in the first column of the table that each method listing begins with the type of the value that’s returned by the method. The nextInt method, for example, returns an int value. Also, notice that each of the methods ends with an empty set of parentheses. read more..

  • Page - 116

    Getting Input with the JOptionPane Class 92 Table 2-7 Scanner Class Methods That Check for Valid Input Values Method Explanation boolean hasNextBoolean() Returns true if the next value entered by the user is a valid boolean value. boolean hasNextByte() Returns true if the next value entered by the user is a valid byte value. boolean hasNextDouble() Returns true if the read more..

  • Page - 117

    Book II Chapter 2 W orking with Variables and Data T ypes Getting Input with the JOptionPane Class 93 The JOptionPane class is a part of the javax.swing package, so you need to add an import javax.swing.JOptionPane statement to the beginning of any program that uses this class. Listing 2-4 shows a simple program that uses the JOPtionPane class to get an integer value read more..

  • Page - 118

    Using enum to Create Y our Own Data Types 94 Using enum to Create Y our Own Data Types You will often find yourself using a String or int variable that you want to constrain to just a few different values. For example, suppose you’re writing a program that plays a card game and you want a way to represent the suite of each card. You could do that with a read more..

  • Page - 119

    Chapter 3: Working with Numbers and Expressions In This Chapter ✓ Dealing with operators, such as +, -, *, and / ✓ Creating finely crafted expressions ✓ Incrementing and decrementing ✓ Accepting an assignment ✓ Using the Math class ✓ Formatting your numbers ✓ Seeing strange things that can happen with numbers I n Book II, Chapter 2, you discover the various primitive numeric read more..

  • Page - 120

    Working with Arithmetic Operators 96 Operator Description / Division % Remainder (Modulus) ++ Increment -- Decrement The following section of code can help clarify how these operators work for int types: int a = 32, b = 5; int c = a + b; // c is 37 int d = a - b; // d is 27 int e = a * b; // e is 160 int f = a / b; // read more..

  • Page - 121

    Book II Chapter 3 W orking with Numbers and Expressions Working with Arithmetic Operators 97 The moral of the story is that if you want to divide int values and get an accu- rate double result, you must cast at least one of the int values to a double. Here are a few additional things to think about tonight as you lie awake pon- dering the wonder of Java’s read more..

  • Page - 122

    Dividing Integers 98 Dividing Integers When you divide one integer into another, the result is always another integer. Any remainder is simply discarded, and the answer is not rounded up. 5 / 4 gives the result 1, for example, and 3 / 4 gives the result 0. If you want to know that 5 / 4 is actually 1.25 or that 3 / 4 is actually 0.75, you need read more..

  • Page - 123

    Book II Chapter 3 W orking with Numbers and Expressions Combining Operators 99 // print the results ➝26 System.out.println("Give each child " + marblesPerChild + " marbles."); System.out.println("You will have " + marblesLeftOver + " marbles left over."); read more..

  • Page - 124

    Using the Unary Plus and Minus Operators 100 In the expression a + b * c, for example, multiplication has a higher pre- cedence than addition. Thus b is multiplied by c first. Then the result of that multiplication is added to a. If an expression includes two or more operators at the same order of pre- cedence, the operators are evaluated left to right. Thus, in the read more..

  • Page - 125

    Book II Chapter 3 W orking with Numbers and Expressions Using Increment and Decrement Operators 101 The unary minus operator doesn’t necessarily make an operand have a nega- tive value. Instead, it changes whatever sign the operand has to start with. Thus, if the operand starts with a positive value, the unary minus operator changes it to negative. But if the operand read more..

  • Page - 126

    Using Increment and Decrement Operators 102 Note that an expression that uses an increment or decrement operator is a statement by itself. That’s because the increment or decrement operator is also a type of assignment operator, as it changes the value of the variable it applies to. You can use the increment and decrement operators only on variables — not on numeric read more..

  • Page - 127

    Book II Chapter 3 W orking with Numbers and Expressions Using the Assignment Operator 103 This time, b is incremented before the multiplication is performed, so c is set to 20. Either way, b ends up set to 4. Similarly, consider this example: int a = 5; int b = --a; // b is set to 5, a is set to 4. This example is similar to an earlier example, but read more..

  • Page - 128

    Using the Assignment Operator 104 In the rest of this section, I point out some unusual ways in which you can use the assignment operator. I don’t recommend that you actually use any of these techniques, as they’re rarely necessary and almost always confusing, but knowing about them can shed light on how Java expressions work and sometimes can help you find sneaky read more..

  • Page - 129

    Book II Chapter 3 W orking with Numbers and Expressions Using Compound Assignment Operators 105 This expression assigns the value 3 to all three variables. Although this code seems pretty harmless, you’re better off just writing three assignment state- ments. (You might guess that clumping the assignments together is more efficient than writing them on three lines, but read more..

  • Page - 130

    Using the Math Class 106 Is a set to 7 or 8? In other words, is the third statement equivalent to a = a * b + 1; // This would give 7 as the result or a = a * (b + 1); // This would give 8 as the result At first glance, you might expect the answer to be 7, because multiplication has a higher precedence than addition. But assignment has read more..

  • Page - 131

    Book II Chapter 3 W orking with Numbers and Expressions Using the Math Class 107 Using constants of the Math class The Math class defines two constants that are useful for many mathematical calculations. Table 3-3 lists these constants. Table 3-3 Constants of the Math Class Constant What It Is Value PI The constant pi (π), the ratio of a circle’s radius and diameter 3.141592653589793 E read more..

  • Page - 132

    Using the Math Class 108 Working with mathematical functions Table 3-4 lists the basic mathematical functions that are provided by the Math class. As you can see, you can use these functions to calculate such things as the absolute value of a number, the minimum and maximum of two values, square roots, powers, and logarithms. Table 3-4 Mathematical Functions Provided by the read more..

  • Page - 133

    Book II Chapter 3 W orking with Numbers and Expressions Using the Math Class 109 Method Explanation signum(argument) Returns a number that represents the sign of the argument: –1.0 if the argument is negative, 0.0 if the argument is zero, and 1.0 if the argument is positive. The argument can be a double or a float. The return value is the same type as the read more..

  • Page - 134

    Using the Math Class 110 ✦ In the classic movie The Wizard of Oz, when the Wizard finally grants the Scarecrow his brains, the Scarecrow suddenly becomes intelligent and quotes the Pythagorean theorem, which is (coincidentally) used by the hypot method of the Math class. Unfortunately, he quotes it wrong. What the Scarecrow actually says in the movie is this: "The sum read more..

  • Page - 135

    Book II Chapter 3 W orking with Numbers and Expressions Using the Math Class 111 Strictly speaking, computers are not capable of generating truly random numbers, but over the years, clever computer scientists have developed ways to generate numbers that are random for all practical purposes. These numbers are called pseudorandom numbers because although they aren’t completely read more..

  • Page - 136

    Using the Math Class 112 To give you an idea of how this random-number calculation works, Listing 3-4 shows a program that places this calculation in a method called randomInt and then calls it to simulate 100 dice rolls. The randomInt method accepts two parameters representing the low and high ends of the range, and it returns a random integer within the range. In read more..

  • Page - 137

    Book II Chapter 3 W orking with Numbers and Expressions Using the Math Class 113 ➝ 8 The for statement causes the statements in its body (lines 10 and 11) to be executed 100 times. Don’t worry about how this statement works for now; you find out about it in Book II, Chapter 5. ➝ 10 This statement calls the randomInt method, specifying 1 and 6 as read more..

  • Page - 138

    Using the Math Class 114 Listing 3-5 shows a program that uses each of the four methods to round three double values: 29.4, 93.5, and -19.3. Here’s the output from this program: round(x) = 29 round(y) = 94 round(z) = -19 ceil(x) = 30.0 ceil(y) = 94.0 ceil(z) = -19.0 floor(x) = 29.0 floor(y) = 93.0 floor(z) = -20.0 rint(x) = 29.0 rint(y) = 94.0 rint(z) = -19.0 Note that read more..

  • Page - 139

    Book II Chapter 3 W orking with Numbers and Expressions Formatting Numbers 115 System.out.println(); System.out.println("floor(x) = " + Math.floor(x)); System.out.println("floor(y) = " + Math.floor(y)); System.out.println("floor(z) = " + Math.floor(z)); System.out.println(); read more..

  • Page - 140

    Formatting Numbers 116 Like many aspects of Java, the procedure for using the NumberFormat class is a little awkward. It’s designed to be efficient for applications that need to format a lot of numbers, but it’s overkill for most applications. The procedure for using the NumberFormat class to format numbers takes a little getting used to. First, you must call one read more..

  • Page - 141

    Book II Chapter 3 W orking with Numbers and Expressions Formatting Numbers 117 When you run this code, the following line is printed: 92% If your program formats several numbers, consider creating the NumberFormat object as a class variable. That way, the NumberFormat object is created when the program starts. Then you can use the NumberFormat object from any method read more..

  • Page - 142

    Recognizing Weird Things about Java Math 118 Recognizing Weird Things about Java Math Believe it or not, computers — even the most powerful ones — have certain limitations when it comes to performing math calculations. These limitations are usually insignificant, but sometimes they sneak up and bite you. The fol- lowing sections describe the things you need to watch out for when read more..

  • Page - 143

    Book II Chapter 3 W orking with Numbers and Expressions Recognizing Weird Things about Java Math 119 Floating-point weirdness Floating-point numbers have problems of their own. For starters, floating- point numbers are stored using the binary number system (base 2), but humans work with numbers in the decimal number system (base 10). Unfortu- nately, accurately converting numbers read more..

  • Page - 144

    Recognizing Weird Things about Java Math 120 times zero is zero. Therefore, both a and c would also have to be zero. In short, mathematicians solved this dilemma centuries ago by saying that division by zero is simply not allowed. So what happens if you do attempt to divide a number by zero in a Java pro- gram? The answer depends on whether you’re dividing read more..

  • Page - 145

    Book II Chapter 3 W orking with Numbers and Expressions Recognizing Weird Things about Java Math 121 Table 3-7 Special Constants of the float and double Classes Constant Meaning POSITIVE_INFINITY Positive infinity NEGATIVE_INFINITY Negative infinity NaN Not a number The following paragraphs describe some final bits of weirdness I want to sneak in before closing this chapter: ✦ read more..

  • Page - 146

    122 Book II: Programming Basics read more..

  • Page - 147

    Chapter 4: Making Choices In This Chapter ✓ Boolean expressions for fun and profit (or is it for fun or profit?) ✓ Your basic, run-of-the-mill if statement ✓ else clauses and else-if statements ✓ Nested if statements ✓ Logical operators ✓ The weird ?: operator ✓ The proper way to do string comparisons S o far in this book, all the programs have run straight read more..

  • Page - 148

    Using Simple Boolean Expressions 124 As you discover later in this chapter, boolean expressions can be very complicated. Most of the time, however, you use simple expressions that compare the value of a variable with the value of some other variable, a literal, or perhaps a simple arithmetic expression. This comparison uses one of the relational operators listed in Table 4-1. read more..

  • Page - 149

    Using if Statements 125 Book II Chapter 4 Making Choices Here are the sample expressions, along with their results (based on the values supplied): Expression Value Explanation i == 5 true The value of i is 5. i == 10 false The value of i is not 10. i == j false i is 5, and j is 10, so they are not equal. i == j - 5 true i is 5, and j – 5 is 5. i read more..

  • Page - 150

    Using if Statements 126 Simple if statements In its most basic form, an if statement lets you execute a single statement or a block of statements only if a boolean expression evaluates to true. The basic form of the if statement looks like this: if (boolean-expression) statement Note that the boolean expression must be enclosed in parentheses. Also, if you use read more..

  • Page - 151

    Using if Statements 127 Book II Chapter 4 Making Choices Here’s an example that uses a block rather than a single statement: double commissionRate = 0.0; if (salesTotal > 10000.0) { commissionRate = 0.05; commission = salesTotal * commissionRate; } In this example, the two statements within the braces are executed if sales Total is greater than $10,000. read more..

  • Page - 152

    Using if Statements 128 This method works, but I’d avoid it. Your classes are easier to follow if you use line breaks and indentation to highlight their structure. if-else statements An if-else statement adds an additional element to a basic if statement: a statement or block that’s executed if the boolean expression is not true. Its basic format is if read more..

  • Page - 153

    Using if Statements 129 Book II Chapter 4 Making Choices double commissionRate = 0.05; if (salesTotal <= 10000.0) commissionRate = 0.02; You can use blocks for either or both of the statements in an if-else statement. Here’s an if-else statement in which both statements are blocks: double commissionRate; if (salesTotal <= 10000.0) { commissionRate = 0.02; read more..

  • Page - 154

    Using if Statements 130 Nesting can be as complex as you want, but try to keep it as simple as possible. Also, be sure to use indentation to indicate the structure of the nested statements. Suppose that your company has two classes of sales representatives (Class 1 and Class 2) and that these reps get different commissions for sales below $10,000 and sales above read more..

  • Page - 155

    Using if Statements 131 Book II Chapter 4 Making Choices You could just use a pair of separate if statements, of course, like this: if (salesClass == 1) if (salesTotal < 10000.0) commissionRate = 0.02; else commissionRate = 0.04; if (salesClass == 2) if (salesTotal < 10000.0) commissionRate = 0.025; read more..

  • Page - 156

    Using if Statements 132 Sorry — you can’t coax Java into pairing the if and else keywords differ- ently by using indentation. Suppose that Class 2 sales reps don’t get any commission, so the inner if statements in the preceding example don’t need else statements. You may be tempted to calculate the commission rate by using this code: if (salesTotal < 10000) if read more..

  • Page - 157

    Using if Statements 133 Book II Chapter 4 Making Choices else-if statements A common pattern for nested if statements is to have a series of if-else statements with another if-else statement in each else part: if (expression-1) statement-1 else if (expression-2) statement-2 else if (expression-3) statement-3 These statements are sometimes called else-if read more..

  • Page - 158

    Using if Statements 134 Figure 4-3: The flow- chart for a sequence of else-if statements. You have to think through carefully how you set up these else-if statements. At first glance, for example, this sequence looks as though it might work: if (salesTotal > 0.0) commissionRate = 0.0; else if (salesTotal >= 1000.0) commissionRate = 0.02; else if read more..

  • Page - 159

    Using Mr. Spock’s Favorite Operators (Logical Ones, of Course) 135 Book II Chapter 4 Making Choices Using Mr. Spock’s Favorite Operators (Logical Ones, of Course) A logical operator (sometimes called a Boolean operator) is an operator that returns a Boolean result that’s based on the Boolean result of one or two other expressions. Expressions that use logical operators read more..

  • Page - 160

    Using Mr. Spock’s Favorite Operators (Logical Ones, of Course) 136 The Not operator reverses the value of a boolean expression. Thus, if the expression is true, Not changes it to false. If the expression is false, Not changes it to true. Here’s an example: !(i = 4) This expression evaluates to true if i is any value other than 4. If i is 4, it evaluates to read more..

  • Page - 161

    Using Mr. Spock’s Favorite Operators (Logical Ones, of Course) 137 Book II Chapter 4 Making Choices both true, the & operator returns true. If one is false or both are false, the & operator returns false. Notice that I use parentheses liberally to clarify where one expression ends and another begins. Using parentheses isn’t always necessary, but when you read more..

  • Page - 162

    Using Mr. Spock’s Favorite Operators (Logical Ones, of Course) 138 With an Or operator, however, you can do the same thing with a compound condition: if ((salesTotal < 1000.0) | (salesClass == 3)) commissionRate = 0.0; To evaluate the expression for this if statement, Java first evaluates the expres- sions on either side of the | operator. Then, if at least one read more..

  • Page - 163

    Using Mr. Spock’s Favorite Operators (Logical Ones, of Course) 139 Book II Chapter 4 Making Choices if ( switch1 == switch2 ) System.out.println("Trouble! The switches are the same"); else System.out.println("OK, the switches are different."); Now, suppose that (for some reason) one of the switches is represented by an int variable where 1 means the switch goes read more..

  • Page - 164

    Using Mr. Spock’s Favorite Operators (Logical Ones, of Course) 140 In many cases, you can clarify how an expression works just by indenting its pieces differently and spacing out its subexpressions. This version of the preceding if statement is a little easier to follow: if ((salesTotal < 1000.0) || ( (salesTotal < 5000.0) && (salesClass == 1)) read more..

  • Page - 165

    Comparing Strings 141 Book II Chapter 4 Making Choices Using the Conditional Operator Java has a special operator called the conditional operator that’s designed to eliminate the need for if statements in certain situations. It’s a ternary operator, which means that it works with three operands. The general form for using the conditional operator is this: boolean-expression ? read more..

  • Page - 166

    Comparing Strings 142 if (answer == "Yes") System.out.println("The answer is Yes."); Unfortunately, that’s not correct. The problem is that in Java, strings are ref- erence types, not primitive types; when you use the == operator with refer- ence types, Java compares the references to the objects, not the objects themselves. As a result, the expression read more..

  • Page - 167

    Chapter 5: Going Around in Circles (Or, Using Loops) In This Chapter ✓ The thrill of while loops ✓ The rapture of infinite loops ✓ The splendor of do loops ✓ The joy of validating input ✓ The wonder of for loops ✓ The ecstasy of nested loops S o far, all the programs in this book have started, run quickly through their main method, and then read more..

  • Page - 168

    Using Your Basic while Loop 144 Using Your Basic while Loop The most basic of all looping statements in Java is while. The while state- ment creates a type of loop that’s called a while loop, which is simply a loop that executes continuously as long as some conditional expression evaluates to true. while loops are useful in all sorts of programming situations, read more..

  • Page - 169

    Breaking Out of a Loop 145 Book II Chapter 5 Going Around in Circles (Or , Using Loops) The conditional expression in this program’s while statement is number <= 20. That means the loop repeats as long as the value of number is less than or equal to 20. The body of the loop consists of two statements. The first prints the value of number followed by read more..

  • Page - 170

    Looping Forever 146 Suppose that you’re afraid of the number 12. (I’m not a doctor, and I don’t play one on TV, but I think the scientific name for this condition would be dodecaphobia.) You could modify the counting program shown in the pre- ceding section so that when it gets to the number 12, it panics and aborts the loop: public class Dodecaphobia { read more..

  • Page - 171

    Looping Forever 147 Book II Chapter 5 Going Around in Circles (Or , Using Loops) If you run this program, your console window quickly fills up with numbers and just keeps going. That’s great if you really like even numbers, but even- tually you’ll tire of this loop and want it to stop. You can stop an infinite loop in any of three ways: ✦ Turn off your read more..

  • Page - 172

    Looping Forever 148 { int number = 2; String input; while (true) { System.out.println(number + " "); System.out.print ("Do you want to keep counting?" + " (Y or read more..

  • Page - 173

    Using the continue Statement 149 Book II Chapter 5 Going Around in Circles (Or , Using Loops) ("Do you want to keep counting?" + " (Y or N)"); input = sc.next(); number += 2; } read more..

  • Page - 174

    Running do-while Loops 150 Notice that I had to make several changes in this program to get it to work with a continue statement instead of a break statement. If I had just replaced the word break with continue, the program wouldn’t have worked, because the statement that added 2 to the number came after the break statement in the original version. As a result, read more..

  • Page - 175

    Running do-while Loops 151 Book II Chapter 5 Going Around in Circles (Or , Using Loops) } while (number <= 20); System.out.println(); } } Here’s the most important thing to remember about do-while loops: The statement or statements in the body of a do-while loop always get executed at least once. By contrast, the read more..

  • Page - 176

    Validating Input from the User 152 Here are a few other things to be aware of concerning do-while loops: ✦ You often can skip initializing the variables that appear in the expression before the loop, because the expression isn’t evaluated until the state- ments in the loop body have been executed at least once. ✦ You can use break and continue statements in a read more..

  • Page - 177

    Validating Input from the User 153 Book II Chapter 5 Going Around in Circles (Or , Using Loops) Here the expression used by the do-while loop validates the data entered by the user, which means that it checks the data against some set of criteria to make sure the data is acceptable. The || operator performs an Or test. It returns true if at least one of the read more..

  • Page - 178

    Using the Famous for Loop 154 Here, the if statement displays the message "What, are you crazy?" if the user tries to enter an inappropriate bet. You can avoid duplicating the expression that does the data validation by adding a boolean variable that’s set in the body of the do-while loop if the data is invalid, as in this example: import java.util.Scanner; public read more..

  • Page - 179

    Using the Famous for Loop 155 Book II Chapter 5 Going Around in Circles (Or , Using Loops) programs, so the people who design computer programming languages (they’re called computer programming language designers) long ago concocted a spe- cial kind of looping mechanism that’s designed just for counting. The basic principle behind a for loop is that the loop itself maintains read more..

  • Page - 180

    Using the Famous for Loop 156 Figure 5-3: The flowchart for a for loop. Here’s a simple for loop that displays the numbers 1 to 10 on the console: public class CountToTen { public static void main(String[] args) { for (int i = 1; i <= 10; i++) System.out.println(i); } } Run this program, read more..

  • Page - 181

    Using the Famous for Loop 157 Book II Chapter 5 Going Around in Circles (Or , Using Loops) 7 8 9 10 This for loop has the following pieces: ✦ The initialization expression is int i = 1. This expression declares a variable named i of type int and assigns it an initial value of 1. ✦ The test expression is i <= 10. As a result, the loop continues to read more..

  • Page - 182

    Using the Famous for Loop 158 public class CountToTenErrorFixed { public static void main(String[] args) { int i; for (i = 1; i <=10; i++) System.out.println(i); System.out.println("The final value of i is " + i); } } Note that read more..

  • Page - 183

    Using the Famous for Loop 159 Book II Chapter 5 Going Around in Circles (Or , Using Loops) Counting backward No rule says for loops can only count forward. To count backward, you simply have to adjust the three for loop expressions. As usual, the initializa- tion expression specifies the starting value for the counter variable. The test expression uses a greater-than test read more..

  • Page - 184

    Using the Famous for Loop 160 System.out.println("Liftoff! We have a liftoff!"); } } When you run it, here’s the output that’s displayed: We are go for launch in T minus 10... 9... Ignition sequence start! 7... 6... 5... 4... 3... 2... 1... 0... All engines running! Liftoff! We have a liftoff! Can’t you just hear the voice of Paul Haney, the famous read more..

  • Page - 185

    Using the Famous for Loop 161 Book II Chapter 5 Going Around in Circles (Or , Using Loops) Ganging up your expressions An obscure aspect of for loops is the fact that the initialization and count expressions can actually be a list of expressions separated by commas. This can be useful if you need to keep track of two counter variables at the same time. Here’s a read more..

  • Page - 186

    Using the Famous for Loop 162 Here, just to prove that I can do it, is a version of the LaunchController program that uses a bodiless for loop: public class ExpressionGanging { public static void main(String[] args) { System.out.print ("We are go for launch in T minus "); for (int count = 10; count >= read more..

  • Page - 187

    Using the Famous for Loop 163 Book II Chapter 5 Going Around in Circles (Or , Using Loops) If you omit the test expression, you’d better throw a break statement in the loop somewhere (as described earlier in the chapter in the “Breaking Out of a Loop” section). Otherwise you’ll find yourself in an infinite loop. You can omit all three of the expressions if you read more..

  • Page - 188

    Nesting Your Loops 164 System.out.println(); } } The console output from this version looks like this: 2 4 6 8 10 14 16 18 20 Nesting Your Loops Loops can contain loops. The technical term for this is loop-de-loop. Just kid- ding. Actually, the technical term is nested loop, which is simply a loop that is completely contained inside another loop. read more..

  • Page - 189

    Nesting Your Loops 165 Book II Chapter 5 Going Around in Circles (Or , Using Loops) A guessing game Listing 5-1 shows a more complicated but realistic example of nesting. This program implements a simple guessing game in which the computer picks a number between 1 and 10, and you have to guess the number. After you guess, the computer tells you whether you’re right read more..

  • Page - 190

    Nesting Your Loops 166 Listing 5-1: The Guessing Game import java.util.Scanner; public class GuessingGame { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { boolean keepPlaying = true; ➝10 System.out.println("Let's play a guessing game!"); while (keepPlaying) ➝13 read more..

  • Page - 191

    Nesting Your Loops 167 Book II Chapter 5 Going Around in Circles (Or , Using Loops) else validInput = false; } while (!validInput); ➝57 } ➝58 System.out.println("\nThank you for playing!"); ➝59 } } The following paragraphs read more..

  • Page - 192

    168 Book II: Programming Basics read more..

  • Page - 193

    Chapter 6: Pulling a Switcheroo In This Chapter ✓ Avoiding the trouble with big else-if statements ✓ Using the switch statement ✓ Creating case groups ✓ Using characters with case I n Book II, Chapter 4, you find out about the workhorses of Java decision-making: boolean expressions and the mighty if statement. In this chapter, you discover another Java tool for decision-making: the read more..

  • Page - 194

    Battling else-if Monstrosities 170 Listing 6-1: The else-if Version of a Voting Machine Error Decoder import java.util.Scanner; public class VoterApp { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { System.out.println ("Welcome to the voting machine " + "error code decoder.\n\n" + read more..

  • Page - 195

    Book II Chapter 6 Pulling a Switcheroo Battling else-if Monstrosities 171 switch statement. Specifically, the switch statement is useful when you need to select one of several alternatives based on the value of an integer or character type variable. Listing 6-2 shows a version of the voting machine error decoder program that uses a switch statement instead of a big else-if read more..

  • Page - 196

    Using the switch Statement 172 case 6: msg = "Voter drooled in voting machine.\n" + "Beginning spin cycle."; break; case 7: msg = "Voter lied to pollster after voting.\n" + "Voter's ballot changed " + "to match read more..

  • Page - 197

    Book II Chapter 6 Pulling a Switcheroo Using the switch Statement 173 Note that the case groups are not true blocks marked with braces. Instead, each case group begins with the case keyword and ends with the case key- word that starts the next case group. All the case groups together, however, are defined as a block marked with a set of braces. The last statement read more..

  • Page - 198

    Using the switch Statement 174 Figure 6-1 shows a flowchart that describes the operation of this switch statement. As you can see, this flowchart is similar to the flowchart in Figure 4-3 (Book II, Chapter 4), because the operation of the switch statement is similar to the operation of a series of else-if statements. Figure 6-1: The flowchart for a switch read more..

  • Page - 199

    Book II Chapter 6 Pulling a Switcheroo Using the switch Statement 175 Putting if statements inside switch statements You’re free to include any type of statements you want in the case groups, including if statements. Suppose that your commission structure depends on total sales as well as sales class, as in this table: Class Sales < $10,000 Sales $10,000 and Above 11% 2% 2 2.5% read more..

  • Page - 200

    Creating Character Cases 176 Creating Character Cases Aside from having a nice alliterative title, this section shows how you can use a char variable rather than an integer in a switch statement. When you use a char type, providing two consecutive case constants for each case group is common, to allow for both lowercase and uppercase letters. Suppose that you need to read more..

  • Page - 201

    Book II Chapter 6 Pulling a Switcheroo Intentionally Leaving Out a Break Statement 177 Intentionally Leaving Out a Break Statement Although the most common cause of problems with the switch statement is accidentally leaving out a break statement at the end of a case group, some- times you need to do it on purpose. Many applications have features that are progressively added read more..

  • Page - 202

    Intentionally Leaving Out a Break Statement 178 case 'D': case 'd': details += "\tTire Treatment, plus . . . \n"; case 'C': case 'c': details += "\tLeather/Vinyl Treatment, plus . . . \n"; case 'B': case 'b': details += read more..

  • Page - 203

    Book II Chapter 6 Pulling a Switcheroo Intentionally Leaving Out a Break Statement 179 switch (p) { case 'E': case 'e': details = packageE() + packageD() + packageC() + packageB() + packageA(); break; case 'D': case 'd': details = read more..

  • Page - 204

    Switching with Strings 180 Switching with Strings Beginning with Java 1.7, the expression in the switch statement can evalu- ate to a String value. Listing 6-5 shows a version of the car wash program that uses the string codes PRESIDENTIAL, ELITE, DELUXE, SUPER, and STANDARD as the car wash types, instead of the letters A through E. Notice that to allow for variations in read more..

  • Page - 205

    Chapter 7: Adding Some Methods to Your Madness In This Chapter ✓ Introducing static methods ✓ Seeing some good reasons to use methods in your programs ✓ Creating methods that return values ✓ Creating methods that accept parameters I n Java, a method is a block of statements that has a name and can be executed by calling (also called invoking) it from some read more..

  • Page - 206

    The Basics of Making Methods 182 Or suppose that your program needs to perform some calculation, such as how long to let the main rockets burn to make a midcourse correction on a moon flight, and the program needs to perform this calculation in several places. Without methods, you’d have to duplicate the statements that do this calculation. That approach is not only read more..

  • Page - 207

    Book II Chapter 7 Adding Some Methods to Y our Madness The Basics of Making Methods 183 ✦ static: This keyword declares that the method is a static method, which means that you can call it without first creating an instance of the class in which it’s defined. The main method must always be static, and any other methods in the class that contains the main read more..

  • Page - 208

    The Basics of Making Methods 184 sayHello(); } public static void sayHello() { System.out.println("Hello, World!"); } } This program is admittedly trivial, but it illustrates the basics of creating and using methods in Java. Here, the statement in the main method calls the sayHello method, which in turn read more..

  • Page - 209

    Book II Chapter 7 Adding Some Methods to Y our Madness The Basics of Making Methods 185 so that the while loop needed 4,100 statements to play a single cycle of the game? Do you really want a while loop that has 4,100 statements in its body? I should think not. Listing 7-1 shows how you can simplify this game a bit just by placing the body of the main while read more..

  • Page - 210

    Methods That Return V alues 186 if (guess == number) System.out.println("You're right!"); else System.out.println("You're wrong!" + " The number was " + number); // Play again? do { System.out.print("\nPlay again? (Y read more..

  • Page - 211

    Book II Chapter 7 Adding Some Methods to Y our Madness Methods That Return V alues 187 Declaring the method’s return type To create a method that returns a value, you simply indicate the type of the value returned by the method on the method declaration in place of the void keyword. Here’s a method declaration that creates a method that returns an int value: public read more..

  • Page - 212

    Methods That Return V alues 188 public static int getRandomNumber() { int num = (int)(Math.random() * 10) + 1; return num; } } In this program, the getRandomNumber method uses the Math.random method to calculate a random number from 1 to 10. (For more information about the Math.random method, see Book II, Chapter read more..

  • Page - 213

    Book II Chapter 7 Adding Some Methods to Y our Madness Methods That Return V alues 189 Things can get complicated if your return statements are inside if state- ments. Sometimes, the compiler gets fooled and refuses to compile your pro- gram. To explain this situation, I offer the following tale of multiple attempts to solve what should be a simple programming problem. read more..

  • Page - 214

    Methods That Return V alues 190 do { num = (int)(Math.random() * 20) + 1; if (num != 12) return num; } while (num == 12); } But the compiler refuses to compile the method again. It turns out that the compiler is smart, but not very smart. It doesn’t catch the fact that the read more..

  • Page - 215

    Book II Chapter 7 Adding Some Methods to Y our Madness Methods That Return V alues 191 ✦ getGuess: This method gets the user’s guess, makes sure that it is between 1 and 10, and returns the guess if it’s within the acceptable range. ✦ askForAnotherRound: This method asks the user to play another round and returns a boolean value to indicate whether the user read more..

  • Page - 216

    Methods That Return V alues 192 { int guess = sc.nextInt(); if ((guess < 1) || (guess > 10)) { System.out.print("I said, between 1 and 10. " + "Try again: "); } else read more..

  • Page - 217

    Book II Chapter 7 Adding Some Methods to Y our Madness Methods That Take Parameters 193 ➝ 43 The return statement for the getRandomNumber method. The random number is calculated using the Math.random method, and the result of this calculation is returned as the value of the getRandomNumber method. ➝ 46 The start of the getGuess method, which indicates that read more..

  • Page - 218

    Methods That Take Parameters 194 Then, if your program needs to roll dice, you could call the same method: int number = getRandomNumber(1, 6); Or, to pick a random card from a deck of 52 cards, you could call it like this: int number = getRandomNumber(1, 52); You wouldn’t have to start with 1, either. To get a random number between 50 and 100, you’d call the method read more..

  • Page - 219

    Book II Chapter 7 Adding Some Methods to Y our Madness Methods That Take Parameters 195 Or you could call it like this: int low = 1; int high = 10; int number = getRandomNumber(low, high); Or you could dispense with the variables altogether and just pass literal values to the method: int number = getRandomNumber(1, 10); You can also specify expressions as the parameter values: read more..

  • Page - 220

    Methods That Take Parameters 196 Understanding pass-by-value When Java passes a variable to a method via a parameter, the method itself receives a copy of the variable’s value, not the variable itself. This copy is called a pass-by-value, and it has an important consequence: If a method changes the value it receives as a parameter, that change is not reflected in the read more..

  • Page - 221

    Book II Chapter 7 Adding Some Methods to Y our Madness Methods That Take Parameters 197 ✦ getRandomNumber: This method returns a random number between min and max values passed as parameters. ✦ getGuess: This method also accepts two parameters, min and max, to limit the range within which the user must guess. ✦ askForAnotherRound: This method asks the user to read more..

  • Page - 222

    Methods That Take Parameters 198 public static int getGuess(int min, int max) ➝47 { while (true) { int guess = sc.nextInt(); if ( (guess < min) || (guess > max) ) ➝52 { System.out.print("I said, between " read more..

  • Page - 223

    Book II Chapter 7 Adding Some Methods to Y our Madness Methods That Take Parameters 199 ➝ 43 The calculation for the random number is complicated a bit by the fact that min may not be 1. ➝ 47 The declaration for the getGuess method accepts the min and max parameters. ➝ 52 The if statement in the getGuess method uses the min and max read more..

  • Page - 224

    200 Book II: Programming Basics read more..

  • Page - 225

    Chapter 8: Handling Exceptions In This Chapter ✓ Seeing what to do when bad things happen to good programs ✓ Finding out all about exceptions ✓ Using try, catch, and finally ✓ Preventing exceptions from happening in the first place T his chapter is about what happens when Java encounters an error situ- ation that it can’t deal with. Over the years, computer read more..

  • Page - 226

    Understanding Exceptions 202 Each type of exception that can occur is represented by a different exception class. Here are some typical exceptions: ✦ IllegalArgumentException: You passed an incorrect argument to a method. ✦ InputMismatchException: The console input doesn’t match the data type expected by a method of the Scanner class. ✦ ArithmeticException: You tried read more..

  • Page - 227

    Understanding Exceptions 203 Book II Chapter 8 Handling Exceptions Witnessing an exception Submitted for your approval is a tale of a hastily written Java program, quickly put together to illustrate certain Java programming details while ignoring others. Out of sight, out of mind, as they say. Said program played a guessing game with the user, accepting numeric input via a read more..

  • Page - 228

    Catching Exceptions 204 Finding the culprit You can find the exact statement in your program that caused the exception to occur by examining the lines that are displayed right after the line that indicates which exception was encountered. These lines, called the stack trace, list the methods that the exception passed through before your pro- gram was aborted. Usually, the first read more..

  • Page - 229

    Book II Chapter 8 Handling Exceptions Catching Exceptions 205 Here, you place the statements that might throw an exception within a try block. Then you catch the exception with a catch block. Here are a few things to note about try statements: ✦ You can code more than one catch block. That way, if the statements in the try block might throw more than one read more..

  • Page - 230

    Catching Exceptions 206 When you run this program, the following is displayed on the console: Oops, you can 't divide by zero. There’s nothing else to see here. The next section shows a more complicated example, though. Another example Listing 8-1 shows a simple example of a program that uses a method to get a valid integer from the user. If the user enters a value that read more..

  • Page - 231

    Book II Chapter 8 Handling Exceptions Catching Exceptions 207 If the user enters data that can’t be converted to an integer, however, the nextInt method throws an InputMismatchException. Then this excep- tion is intercepted by the catch block — which disposes of the user’s incor- rect input by calling the next method, as well as by displaying an error message. Then read more..

  • Page - 232

    Handling Exceptions with a Preemptive Strike 208 Handling Exceptions with a Preemptive Strike The try statement is a useful and necessary tool in any Java programmer’s arsenal. The best way to handle exceptions, however, is to prevent them from happening in the first place. That’s not possible all the time, but in many cases it is. The key is to test your data before read more..

  • Page - 233

    Book II Chapter 8 Handling Exceptions Catching All Exceptions at Once 209 This is a clever little bit of programming, don’t you think? The conditional expression in the while statement calls the hasNextInt method of the Scanner to see whether the next value is an integer. The while loop repeats as long as this call returns false, indicating that the next value is read more..

  • Page - 234

    Displaying the Exception Message 210 catch (Exception e) { // statements that process all other exception types } In this example, imagine that the code in the try block could throw an InputMismatchException, an IOException, and perhaps some other type of unanticipated exception. Here the three catch blocks provide for each of these possibilities. When you code more than read more..

  • Page - 235

    Book II Chapter 8 Handling Exceptions Using a finally Block 211 This code displays the text / by zero on the console if b has a value of 0. You can get even more interesting output by using this line in the catch clause: e.printStackTrace(System.out); Using a finally Block A finally block is a block that appears after all the catch blocks for a read more..

  • Page - 236

    Using a finally Block 212 public static int divideTheseNumbers(int a, int b) ➝16 throws Exception { int c; try { c = a / b; ➝22 System.out.println("It worked!"); ➝23 } catch (Exception e) read more..

  • Page - 237

    Book II Chapter 8 Handling Exceptions Handling Checked Exceptions 213 message "It worked the second time!" on the console. (If you do, you’re in an episode of The Twilight Zone.) ➝ 33 This statement in the finally clause is always executed, no matter what happens. That’s where the second line in the console output came from. After the finally clause executes, read more..

  • Page - 238

    Handling Checked Exceptions 214 Consider the following program: import java.io.*; public class FileException1 { public static void main(String[] args) { openFile("C:\test.txt"); } public static void openFile(String name) { FileInputStream f = new FileInputStream(name); } } This program won’t compile. read more..

  • Page - 239

    Book II Chapter 8 Handling Exceptions Handling Checked Exceptions 215 In this example, the message "File not found." is displayed if the C:\test.txt file doesn’t exist. Throwing the FileNotFoundException Suppose that you don’t want to deal with this error condition in the openFile method, but would rather just pass the exception up to the method that calls the read more..

  • Page - 240

    Handling Checked Exceptions 216 Then, if the file doesn’t exist, the catch block catches the exception, and the error message is displayed. Throwing an exception from main If you don’t want the program to handle the FileNotFound exception at all, you can add a throws clause to the main method, like this: public static void main(String[] args) throws read more..

  • Page - 241

    Book II Chapter 8 Handling Exceptions Throwing Your Own Exceptions 217 Note that not all exception swallowing is bad. Suppose you want the openFile method to return a boolean value to indicate whether the file exists, rather than throw an exception. Then you could code the method something like this: public static boolean openFile(String name) { boolean fileOpened = read more..

  • Page - 242

    218 Catching Multiple Exceptions { System.out.println("Exception!"); } } public static void doSomething(boolean t) throws Exception { if (t) throw new Exception(); } } Here the doSomething method accepts a boolean value read more..

  • Page - 243

    Book II Chapter 8 Handling Exceptions Catching Multiple Exceptions 219 This method works, but it’s clumsy. Java lets you specify two or more excep- tion types in the catch statement. You separate the exception types with a vertical bar, like this: { // statements that might throw FileNotFoundException // or IOException } catch (FileNotFoundException | IOException e) { read more..

  • Page - 244

    220 Book II: Programming Basics read more..

  • Page - 245

    You can find an interesting programming challenge that requires use of many of the programming techniques covered in this minibook at www.dummies.com/ extras/javaaio. I challenge you to create an enhanced version of the Tic-Tac-Toe program you created for Book II so that it incorporates simple strategy into the computer’s plays. Book III Object-Oriented Programming read more..

  • Page - 246

    Contents at a Glance Contents at a Glance Chapter 1: Understanding Object-Oriented Programming............223 What Is Object-Oriented Programming? ......................................................................223 Understanding Objects ....................................................................................................224 Understanding the Life Cycle of an Object read more..

  • Page - 247

    Chapter 1: Understanding Object-Oriented Programming In This Chapter ✓ Looking at what object-oriented programming is ✓ Understanding objects and classes ✓ Investigating inheritance and interfaces ✓ Designing programs with objects ✓ Diagramming with UML T his chapter is a basic introduction to object-oriented programming. It introduces some of the basic concepts and terms you read more..

  • Page - 248

    Understanding Objects 224 ✦ Business programs can be thought of as simulations of business pro- cesses — such as or der taking, customer service, shipping, and billing. An invoice, for example, isn’t just a piece of paper; it’s a paper that rep- resents a transaction that has occurred between a company and one of its customers. Thus, a computer-based invoice is really just read more..

  • Page - 249

    Book III Chapter 1 Understanding Object-Oriented Programming Understanding Objects 225 In the real world, object identity is a pretty intuitive and obvious concept. Pick up two apples, and you know that although both of them are apples (that’s the object type, described in the next section), you know that they aren’t the same apple. Each has a distinct identity. Both read more..

  • Page - 250

    Understanding Objects 226 Sure, it’s a fine antiwar poem and all that, but it’s also a little instructive about object-oriented programming. After the first stanza, the poem goes on to name the parts of a rifle: This is the lower sling swivel. And this Is the upper sling swivel, whose use you will see, When you are given your slings. And this is the piling swivel, read more..

  • Page - 251

    Book III Chapter 1 Understanding Object-Oriented Programming Understanding Objects 227 The combination of the values for all the attributes of an object is called the object’s state. Unlike its identity, an object’s state can — and usually does — change over its lifetime. Some fish can change colors, for example. The total sales for a particular customer changes each time the read more..

  • Page - 252

    Understanding the Life Cycle of an Object 228 Understanding the Life Cycle of an Object As you work with objects in Java, understanding how objects are born, live their lives, and die is important. This topic is called the life cycle of an object, and it goes something like this: 1. Before an object can be created from a class, the class must be loaded. To do that, read more..

  • Page - 253

    Book III Chapter 1 Understanding Object-Oriented Programming Working with Related Classes 229 If you’re creating a program that simulates the way baseballs and softballs work, you need a way to represent these two types of balls. One option is to create separate classes to represent each type of ball. These classes are similar, so you can just copy most of the code from read more..

  • Page - 254

    Designing a Program with Objects 230 You could use an interface to solve the baseball/softball problem by creating an interface named Ball that specifies all the methods and fields that a ball should have. Then you could create the SoftBall and BaseBall classes so that they both implement the Ball interface. Interfaces are closely related to inheritance but have two key read more..

  • Page - 255

    Book III Chapter 1 Understanding Object-Oriented Programming Diagramming Classes with UML 231 ✦ Logic: The objects in this layer represent the core objects of the applica- tion. For a typical business-type application, this layer includes objects that represent business entities such as customer, products, orders, suppliers, and the like. This layer is sometimes called the read more..

  • Page - 256

    Diagramming Classes with UML 232 Figure 1-2: A simple class diagram. You can draw class diagrams in many ways. To add some consistency to their diagrams, most programmers use a standard called UML, which stands for Unified Modeling Language. The class diagram in Figure 1-2 is an example of a simple UML diagram, but UML diagrams can get much more complicated. The read more..

  • Page - 257

    Book III Chapter 1 Understanding Object-Oriented Programming Diagramming Classes with UML 233 The middle compartment of a class lists the class variables, whereas the bottom compartment lists the class methods. The name of each variable or method can be preceded by a visibility indicator, which can be one of the sym- bols listed in Table 1-1. (In actual practice, it’s common to read more..

  • Page - 258

    Diagramming Classes with UML 234 Drawing arrows Besides using rectangles to represent classes, class diagrams include arrows to represent relationships among classes. UML uses a variety of types of arrows, as I describe in the following paragraphs. A solid line with a hollow closed arrow at one end represents inheritance: The arrow points to the base class. A dashed line with a read more..

  • Page - 259

    Chapter 2: Making Your Own Classes In This Chapter ✓ Creating your own class ✓ Looking at the pieces of a class declaration ✓ Finding out about class fields ✓ Constructing constructors ✓ Adding methods to your classes ✓ Using the this keyword O kay, class, it’s time to learn how to create your own classes. In this chapter, you discover the basics of read more..

  • Page - 260

    Declaring a Class 236 Picking class names The ClassName is an identifier that provides a name for your class. You can use any identifier you want to name a class, but the following three guide- lines can simplify your life: ✦ Begin the class name with a capital letter. If the class name consists of more than one word, capitalize each word: for example, Ball, read more..

  • Page - 261

    Declaring a Class 237 Book III Chapter 2 Making Y our Own Classes ✦ Other classes and interfaces: A class can include another class, which is then called an inner class or a nested class. Classes can also contain interfaces. (For more information about inner classes, see Book III, Chapter 7. And for information about interfaces, r efer to Book III, Chapter 5.) Unlike some read more..

  • Page - 262

    Declaring a Class 238 The compiler coughs up a message indicating that Dice is a public class and must be declared in a file named Dice.java. This problem has two solutions. The first is to remove the public keyword from the Dice class: public class DiceGame { public static void main(String[] args) { Dice d = new Dice(); read more..

  • Page - 263

    Working with Members 239 Book III Chapter 2 Making Y our Own Classes Working with Members The members of a class are the fields and methods defined in the class body. (Technically, classes and interfaces defined within a class are members too. I don’t discuss them in this chapter, though, so you can ignore them for now.) The following sections describe the basics of working read more..

  • Page - 264

    Using Getters and Setters 240 To create a private method that can be used within the class but isn’t visible outside the class, use the private keyword: private void calculateLunarTrajectory() { // code to get the calculated lunar trajectory } Understanding visibility In the preceding sections, I mention that both fields and methods can use the public or private read more..

  • Page - 265

    Using Getters and Setters 241 Book III Chapter 2 Making Y our Own Classes Here’s a class that uses a private field named Health to indicate the health of a player in a game program: public class Player { private int health; public int getHealth() { return health; } public void setHealth(int h) { read more..

  • Page - 266

    Overloading Methods 242 health = 0; else if (h > 100) health = 100; else health = h; } Here, if the setHealth method is called with a value less than 0, health is set to 0. Likewise, if the value is greater than 100, health is set read more..

  • Page - 267

    Overloading Methods 243 Book III Chapter 2 Making Y our Own Classes The term overloading is accurate but a little unfortunate. Normally, when you say that something is overloaded, there’s a problem. I once saw a pic- ture of a Volkswagen Jetta loaded down with 3,000 pounds of lumber. (You can find the picture courtesy of Snopes.com, the Urban Legend Reference Page read more..

  • Page - 268

    Creating Constructors 244 Creating Constructors A constructor is a block of code that’s called when an instance of an object is created. In many ways, a constructor is similar to a method, but a few differ- ences exist: ✦ A constructor doesn’t have a return type. ✦ The name of the constructor must be the same as the name of the class. ✦ Unlike methods, read more..

  • Page - 269

    Creating Constructors 245 Book III Chapter 2 Making Y our Own Classes Then you create an instance of the Actor class by calling this constructor: Actor a = new Actor("Arnold", "Schwarzenegger"); A new Actor object for Arnold Schwarzenegger is created. Like methods, constructors can be overloaded. In other words, you can pro- vide more than one constructor for a read more..

  • Page - 270

    Creating Constructors 246 In the first example, the class explicitly declares a constructor that doesn’t accept any parameters and has no statements in its body. In the second example, Java creates a default constructor that works just like the constructor shown in the first example. The default constructor is not created if you declare any constructors for the class. As read more..

  • Page - 271

    Creating Constructors 247 Book III Chapter 2 Making Y our Own Classes Calling other constructors A constructor can call another constructor of the same class by using the special keyword this as a method call. This technique is commonly used when you have several constructors that build on one another. Consider this class: public class Actor { private String lastName; read more..

  • Page - 272

    Finding More Uses for the this Keyword 248 ✦ Each constructor can call only one other constructor, but you can chain constructors. If a class has three constructors, the first constructor can call the second one, which in turn calls the third one. ✦ You can’t create loops in which constructors call one another. Here’s a class that won’t compile: class CrazyClass { read more..

  • Page - 273

    Finding More Uses for the this Keyword 249 Book III Chapter 2 Making Y our Own Classes The this keyword is usually used to qualify references to instance variables of the current object. For example: public Actor(String last, String first) { this.lastName = last; this.firstName = first; } Here this isn’t really necessary because the compiler can tell that read more..

  • Page - 274

    Using Initializers 250 Using Initializers An initializer (sometimes called an initializer block) is a lonely block of code that’s placed outside any method, constructor, or other block of code. Initializers are executed whenever an instance of a class is created, regardless of which constructor is used to create the instance. Initializer blocks are similar to variable initializers used to initialize read more..

  • Page - 275

    Using Initializers 251 Book III Chapter 2 Making Y our Own Classes Either way, the effect is the same. Here are a few other tidbits of information concerning initializers: ✦ If a class contains more than one initializer, the initializers are executed in the order in which they appear in the program. ✦ Initializers are executed before any class constructors. ✦ A read more..

  • Page - 276

    Book III: Object-Oriented Programming 252 read more..

  • Page - 277

    Chapter 3: Working with Statics In This Chapter ✓ Adding static fields to a class ✓ Creating static methods ✓ Creating classes that can be instantiated ✓ Working with static initializers A static method is a method that isn’t associated with an instance of a class. (Unless you jumped straight to this chapter, you already knew that.) Instead, the method belongs to read more..

  • Page - 278

    Working with Static Fields 254 The value of a static field is the same across all instances of the class. In other words, if a class has a static field named CompanyName, all objects created from the class will have the same value for CompanyName. Static fields and methods have many common uses. Here are but a few: ✦ To provide constants or other values that read more..

  • Page - 279

    Book III Chapter 3 W orking with Statics Using Static Methods 255 As a convention, most programmers tend to put the visibility keyword first. Note that you can’t use the static keyword within a class method. Thus the following code won’t compile: private void someMethod() { static int x; } In other words, fields can be static, but local variables can’t. You read more..

  • Page - 280

    Counting Instances 256 Here the main method is static, so it can’t access the instance variable x. Note: You can access static methods and fields from an instance method, however. The following code works fine: public class Invoice { private static double taxRate = 0.75; private double salesTotal; public double getTax() { read more..

  • Page - 281

    Book III Chapter 3 W orking with Statics Counting Instances 257 private static void printCount() { System.out.println("There are now " ➝15 + CountTest.getInstanceCount() + "instances of the CountTest class."); } } class CountTest ➝21 { private static int instanceCount = read more..

  • Page - 282

    258 Counting Instances The Singleton pat tern A singleton is a class that you can use to create only one instance. When you try to create an instance, the class first checks to see whether an instance already exists. If so, the exist- ing instance is used; if not, a new instance is created. You can’t achieve this effect by using Java constructors, because a class instance has read more..

  • Page - 283

    Book III Chapter 3 W orking with Statics Using Static Initializers 259 Preventing Instances Sometimes you want to create a class that can’t be instantiated at all. Such a class consists entirely of static fields and methods. A good example in the Java API is the Math class. Its methods provide utility-type functions that aren’t really associated with a particular object. read more..

  • Page - 284

    Using Static Initializers 260 Java provides a feature called a static initializer that’s designed specifically to let you initialize static fields. The general form of a static initializer looks like this: static { statements... } As you can see, a static initializer is similar to an initializer block but begins with the word static. As with an initializer block, you read more..

  • Page - 285

    Chapter 4: Using Subclasses and Inheritance In This Chapter ✓ Explaining inheritance ✓ Creating subclasses ✓ Using protected access ✓ Creating final classes ✓ Demystifying polymorphism ✓ Creating custom exception classes A s you find out in Book III, Chapter 1, a Java class can be based on another class. Then the class becomes like a child to the parent class: It inherits read more..

  • Page - 286

    Introducing Inheritance 262 In Java, inheritance refers to a feature of object-oriented programming that lets you create classes that are derived from other classes. A class that’s based on another class is said to inherit the other class. The class that is inherited is called the parent class, the base class, or the superclass. The class that does the read more..

  • Page - 287

    Book III Chapter 4 Using Subclasses and Inheritance Introducing Inheritance 263 a driver; possibly passengers; and the ability to drive, stop, turn, and crash. In addition, it would have features that differentiate it from other types of vehi- cles, such as two wheels and handlebars used for steering control. A car is also a type of vehicle. The Car class would inherit the read more..

  • Page - 288

    Creating Subclasses 264 The employee types also have important differences. The most obvious one is that the salaried employees have an annual salary, and the hourly employ- ees have an hourly pay rate. Also, hourly employees have a schedule that changes week to week, and salaried employees may have a benefit plan that isn’t offered to hourly employees. Thus you decide to read more..

  • Page - 289

    Book III Chapter 4 Using Subclasses and Inheritance Creating Subclasses 265 Suppose that you have a class named Ball that defines a basic ball, and you want to create a subclass named BouncingBall that adds the ability to bounce: public class BouncingBall extends Ball { // methods and fields that add the ability to bounce // to a basic Ball object: read more..

  • Page - 290

    Overriding Methods 266 You need to know some important details to use inheritance properly: ✦ A subclass inherits all the members from its base class. Constructors are not considered to be members, however. As a result, a subclass does not inherit constructors from its base class. ✦ The visibility ( public or private) of any members inherited from the base class is read more..

  • Page - 291

    Book III Chapter 4 Using Subclasses and Inheritance Protecting Your Members 267 Here, when you call the play method of a Chess object, the game announces that it gives up. (I was going to provide a complete implementation of an actual chess game program for this example, but it would have made this chapter about 600 pages long. So I opted for the simpler read more..

  • Page - 292

    Using this and super in Your Subclasses 268 Here, the getWeight and setWeight methods are declared with protected access, which means that they’re visible in the subclass BaseBall. These methods aren’t visible to classes that don’t extend Ball, however. Using this and super in Your Subclasses You already know about the this keyword: It provides a way to refer to the read more..

  • Page - 293

    Book III Chapter 4 Using Subclasses and Inheritance Understanding Inheritance and Constructors 269 Here the hit method in the BaseBall class calls the hit method of its base class object. Thus, if you call the hit method of a BaseBall object, the following two lines are displayed on the console: You tore the cover off! You hit it a mile! You can also use the read more..

  • Page - 294

    Using final 270 public Ball(double weight) { this.weight = weight; } } public class BaseBall extends Ball { public BaseBall() { super(5.125); } } Here the BaseBall constructor calls the Ball constructor to supply a default weight for the ball. You need to obey a few rules and regulations read more..

  • Page - 295

    Book III Chapter 4 Using Subclasses and Inheritance Casting Up and Down 271 return this.velocity; } } Here the method getVelocity is declared as final. Thus, any class that uses the SpaceShip class as a base class can’t override the getVelocity method. If it tries, the compiler issues the error message ("Overridden method final"). Here are read more..

  • Page - 296

    Casting Up and Down 272 called upcasting, and Java does it automatically, so you don’t have to code a casting operator. Thus the following code is legal: Ball b = new BaseBall(); Here an object of type BaseBall is created. Then a reference to this object is assigned to the variable b, whose type is Ball, not BaseBall. Now suppose that you have a method in a read more..

  • Page - 297

    Book III Chapter 4 Using Subclasses and Inheritance Determining an Object’s T ype 273 What if you want to call a method that’s defined by a subclass from an object that’s referenced by a variable of the superclass? Suppose that the SoftBall class has a method named riseBall that isn’t defined by the Ball class. How can you call it from a Ball variable? One read more..

  • Page - 298

    Poly What? 274 Suppose you have a method named getEmployee whose return type is Employee but that actually returns either a SalariedEmployee or an HourlyEmployee object: Employee emp = getEmployee(); In many cases, you don’t need to worry about which type of employee this method returns, but sometimes you do. Suppose that the Salaried Employee class extends the Employee read more..

  • Page - 299

    Book III Chapter 4 Using Subclasses and Inheritance Poly What? 275 that represents one of the players. This class has a public method named move that returns an int to indicate which square of the board the player wants to mark: class Player { public int move() { for (int i = 0; i < 9; i++) { read more..

  • Page - 300

    Poly What? 276 As you can see, this version of the Player class overrides the move method and uses a better algorithm to pick its move. (Again, to keep the illustration simple, I don’t show the code that actually chooses the move.) The next thing to do is write a short class that uses these two Player classes to play a game. This class contains a method read more..

  • Page - 301

    Book III Chapter 4 Using Subclasses and Inheritance Creating Custom Exceptions 277 Creating Custom Exceptions The last topic I want to cover in this chapter is how to use inheritance to create your own custom exceptions. I cover most of the details of working with exceptions in Book II, Chapter 8, but I hadn’t explored inheritance, so I couldn’t discuss custom read more..

  • Page - 302

    Creating Custom Exceptions 278 Machine runs out of memory, for example, a VirtualMachineError is thrown. You don’t have to worry about catching these errors in your programs. ✦ Exception: This subclass of Throwable represents an error condition that most programs should try to recover from. Thus, Exception is effectively the top of the hierarchy for the types of read more..

  • Page - 303

    Book III Chapter 4 Using Subclasses and Inheritance Creating Custom Exceptions 279 means that you want to add an explicit default constructor too. So now the ProductDataException class looks like this: public class ProductDataException extends Exception { public ProductDataException { } public ProductDataException(String message) { read more..

  • Page - 304

    Creating Custom Exceptions 280 Here’s some code that calls the getProduct method and catches the exception: try { Product p = ProductDB.getProduct(productCode); } catch (ProductDataException e) { System.out.println(e.getMessage()); } Here the message is simply displayed on the console if a ProductData Exception is thrown. In an actual program, you want to log the error, read more..

  • Page - 305

    Chapter 5: Using Abstract Classes and Interfaces In This Chapter ✓ Understanding abstract methods and classes ✓ Using basic interfaces ✓ Using interfaces as types ✓ Adding constants to an interface ✓ Inheriting interfaces ✓ Working with callbacks ✓ Using default methods I n this chapter, you find out how to use two similar but subtly distinct features: abstract read more..

  • Page - 306

    Using Abstract Classes 282 A class that contains at least one abstract method is called an abstract class and must be declared with the abstract modifier on the class declaration. For example: public abstract class Ball { public abstract int hit(int batSpeed); } If you omit the abstract modifier from the class declaration, the Java compiler coughs up an error read more..

  • Page - 307

    Book III Chapter 5 Using Abstract Classes and Interfaces Using Abstract Classes 283 The problem here isn’t with declaring the variable b as a Ball; it’s using the new keyword with the Ball class in an attempt to create a Ball object. Because Ball is an abstract class, you can use it to create an object instance. You can create a subclass from an abstract read more..

  • Page - 308

    Using Interfaces 284 Abstract classes are used extensively in the Java API. Many of the abstract classes have names that begin with Abstract — such as AbstractBorder, AbstractCollection, and AbstractMap — but most of the abstract classes don’t. The InputStream class (used by System.in) is abstract, for example. Using Interfaces An interface is similar to an abstract read more..

  • Page - 309

    Book III Chapter 5 Using Abstract Classes and Interfaces Using Interfaces 285 In case you haven’t been to English class in a while, an adjective is a word that modifies a noun. You can convert many verbs to adjectives by adding -able to the end of the word — playable, readable, drivable, and stoppable, for example. This type of adjective is commonly used read more..

  • Page - 310

    Using Interfaces 286 Here, the Hearts class implements two interfaces: Playable and CardGame. A class can possibly inherit a superclass and implement one or more interfaces. Here’s an example: public class Poker extends Game implements Playable, CardGame { // inherits all members of the Game class // must implement methods of the Playable // read more..

  • Page - 311

    Book III Chapter 5 Using Abstract Classes and Interfaces More Things You Can Do with Interfaces 287 else if (game.equals("Hearts")) deck.deal(13); else if (game.equals("Gin")) deck.deal(10); } Assuming that you also have a class named CardDeck that implements the Dealable interface, you might use a statement like read more..

  • Page - 312

    More Things You Can Do with Interfaces 288 Note that interface fields are automatically assumed to be static, final, and public. You can include these keywords when you create interface constants, but you don’t have to. Extending interfaces You can extend interfaces by using the extends keyword. An interface that extends an existing interface is called a subinterface, and read more..

  • Page - 313

    Book III Chapter 5 Using Abstract Classes and Interfaces More Things You Can Do with Interfaces 289 Using interfaces for callbacks In the theater, a callback is when you show up for an initial audition, they like what they see, and they tell you that they want you to come back so they can have another look. In Java, a callback is sort of like that. It’s a read more..

  • Page - 314

    More Things You Can Do with Interfaces 290 You find out all about Swing in Book VI. For now, I look at callbacks by using the Timer class, which is part of the javax.Swing package. This class implements a basic timer that generates events at regular intervals — and lets you set up a listener object to handle these events. The listener object must implement the read more..

  • Page - 315

    Book III Chapter 5 Using Abstract Classes and Interfaces More Things You Can Do with Interfaces 291 Listing 5-1: The T ick Tock Program import java.awt.event.*; ➝1 import javax.swing.*; ➝2 public class TickTock { public static void main(String[] args) { // create a timer that calls the Ticker class // at one second intervals read more..

  • Page - 316

    Using Default Methods 292 The following paragraphs describe the important details of this program’s operation: ➝ 1 The ActionListener interface is part of the java.awt.event package, so this import statement is required. ➝ 2 The Timer class is part of the javax.swing package, so this import statement is required. ➝ 10 This statement creates a new read more..

  • Page - 317

    Book III Chapter 5 Using Abstract Classes and Interfaces Using Default Methods 293 For example, suppose you have created the following interface: public interface Playable { void play(); } You then build several classes that implement this interface. Here’s a simple example: class Game implements Playable { public void play() { read more..

  • Page - 318

    Using Default Methods 294 Thus, Java 8 allows you to safely add the quit method to the Playable interface by specifying it as a default method, like this: interface Playable { void play(); default void quit() { System.out.println("Sorry, quitting is not allowed."); } } Here the Playable interface specifies that if an implementing class does not provide an implementation of read more..

  • Page - 319

    Book III Chapter 5 Using Abstract Classes and Interfaces Using Default Methods 295 class Game implements Playable { public void play() { System.out.println("Good luck!"); } } When you run this program, the following will be displayed on the console: Good luck! Sorry, quitting is not allowed. read more..

  • Page - 320

    296 Book III: Object-Oriented Programming read more..

  • Page - 321

    Chapter 6: Using the Object and Class Classes In This Chapter ✓ Using the toString method ✓ Implementing the equals method ✓ Trying out the clone method ✓ Understanding the Class class I n this chapter, you find out how to use two classes of the Java API that are important to object-oriented programming: ✦ The Object class, which every other class read more..

  • Page - 322

    The Mother of All Classes: Object 298 If a subclass has an extends clause that specifies a superclass other than Object, the class still inherits Object. That’s because the inheritance hier- archy eventually gets to a superclass that doesn’t have an extends clause, and that superclass inherits Object and passes it down to all its subclasses. Suppose you have these classes: read more..

  • Page - 323

    Book III Chapter 6 Using the Object and Class Classes The Mother of All Classes: Object 299 designed to maintain collections of objects. One of the most commonly used of these classes is the ArrayList class, which has a method named add that accepts an Object as a parameter. This method adds the specified object to the collection. Because the parameter type is read more..

  • Page - 324

    The Mother of All Classes: Object 300 Note: Almost half of these methods ( notify, notifyAll, and the three wait methods) are related to threading. You find complete information about those five methods in Book V, Chapter 1. Here’s the rundown on the remaining six methods: ✦ clone: This method is commonly used to make copies of objects, and overriding it in your read more..

  • Page - 325

    Book III Chapter 6 Using the Object and Class Classes The toString Method 301 Each of the wrapper classes also defines a static toString method, which you can use like this: String s = Integer.toString(x); Sometimes, using the compiler shortcut that lets you use primitive types in string concatenation expressions is easier: String s = "" + x; Here the int variable x read more..

  • Page - 326

    The toString Method 302 This code creates a new Employee object; then the result of its toString method is printed to the console. When you run this program, the following line is printed on the console: Employee@82ba41 Note: The hash code — in this case, 82ba41 — will undoubtedly be differ- ent on your system. It turns out that the explicit call to toString read more..

  • Page - 327

    Book III Chapter 6 Using the Object and Class Classes The equals Method 303 public String toString() { return "Employee[" + this.firstName + " " + this.lastName + "]"; } } When you run this program, the following line is displayed on the console: read more..

  • Page - 328

    The equals Method 304 class Employee { private String lastName; private String firstName; public Employee(String lastName, String firstName) { this.lastName = lastName; this.firstName = firstName; } } Here the main method creates two Employee objects with identical data and then compares them. Alas, the read more..

  • Page - 329

    Book III Chapter 6 Using the Object and Class Classes The equals Method 305 Which object’s equals method you use shouldn’t matter. Thus the if state- ment shown here returns the same result: if (emp2.equals(emp1)) System.out.println("These employees are the same."); else System.out.println ("These are different employees."); Note that I read more..

  • Page - 330

    The equals Method 306 ✦ It is transitive. For any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, x.equals(z) should return true. ✦ It is consistent. For any non-null reference values x and y, multiple invo- cations of x.equals(y) consistently return true or consistently return false, provided that no read more..

  • Page - 331

    Book III Chapter 6 Using the Object and Class Classes The equals Method 307 4. Cast obj to a variable of your class; then compare the fields you want to base the return value on, and return the result. Here’s an example: Employee emp = (Employee) obj; return this.lastName.equals(emp.getLastName()) && this.firstname.equals(emp.getFirstName()); Notice that the read more..

  • Page - 332

    The equals Method 308 Listing 6-1 (continued) public String getFirstName() { return this.firstName; } public boolean equals(Object obj) ➝39 { // an object must equal itself if (this == obj) ➝42 return true; // no object equals null if (this == null) ➝46 read more..

  • Page - 333

    Book III Chapter 6 Using the Object and Class Classes The clone Method 309 The clone Method Cloning refers to the process of making an exact duplicate of an object. Unfortunately, this process turns out to be a pretty difficult task in an object-oriented language such as Java. You’d think that cloning would be as easy as this: Employee emp1 = new read more..

  • Page - 334

    The clone Method 310 Note that the clone method defined by the Object class returns an Object type. That makes perfect sense, because the Object class doesn’t know the type of the class in which you’ll be overriding the clone method. An incon- venient side effect of returning an Object is that whenever you call the clone method for a class that read more..

  • Page - 335

    Book III Chapter 6 Using the Object and Class Classes The clone Method 311 public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public Double getSalary() { return this.salary; } read more..

  • Page - 336

    The clone Method 312 ➝ 8 Creates a clone of the Employee object for Mr. Martinez. Notice that the return value must be cast to an Employee, because the return value of the clone method is Object. ➝ 9 Changes the last name for the second Employee object. ➝ 10 Prints the first Employee object. ➝ 11 Prints the second Employee object. read more..

  • Page - 337

    Book III Chapter 6 Using the Object and Class Classes The clone Method 313 Cloneable interface. Provided that you implement Cloneable, this excep- tion won’t ever happen, but because CloneNotSupportedException is a checked exception, you must catch it. Here’s an example of an Employee class with a clone method that uses super.clone() to clone itself: class Employee read more..

  • Page - 338

    The clone Method 314 clone method of each of the subobjects contained by the main object to create clones of those objects. (For a deep copy to work, of course, those objects must also support the clone methods.) Listing 6-3 shows an example. Here, an Employee class contains a public field named address, which holds an instance of the Address class. As you can read more..

  • Page - 339

    Book III Chapter 6 Using the Object and Class Classes The clone Method 315 System.out.println("Salary: " + e.getSalary()); System.out.println(); } } class Employee implements Cloneable ➝40 { private String lastName; private String firstName; private Double salary; public Address address; ➝46 public Employee(String lastName, read more..

  • Page - 340

    The clone Method 316 Listing 6-3 (continued) public Object clone() ➝85 { Employee emp; try { emp = (Employee) super.clone(); ➝90 emp.address = (Address)address.clone(); ➝91 } catch (CloneNotSupportedException e) ➝93 { return read more..

  • Page - 341

    Book III Chapter 6 Using the Object and Class Classes The clone Method 317 return super.clone(); ➝137 } catch (CloneNotSupportedException e) { return null; // will never happen } } public String getAddress() { return this.street + "\n" read more..

  • Page - 342

    The Class Class 318 The following paragraphs describe some of the highlights of this program: ➝ 5 Creates an employee named Anthony Martinez. ➝ 8 Sets the employee’s address. ➝ 11 Clones the employee (okay, just the object, not the co-worker). ➝ 13 Prints the two Employee objects after cloning. They should have identical data. ➝ 18 Changes read more..

  • Page - 343

    Book III Chapter 6 Using the Object and Class Classes The Class Class 319 You’ve already seen how you can get a Class object by using the getClass method. This method is defined by the Object class, so it’s available to every object. Here’s an example: Employee emp = new Employee(); Class c = emp.getClass(); Note that you have to initialize a variable with an read more..

  • Page - 344

    The Class Class 320 To find out whether an object is of a particular type, use the object’s getClass method to get the corresponding Class object. Then use the getName method to get the class name, and use a string comparison to check the class name. Here’s an example: if (emp.getClass().getName().equals("Employee")) System.out.println("This is an read more..

  • Page - 345

    Chapter 7: Using Inner Classes, Anonymous Classes, and Lambda Expressions In This Chapter ✓ Using inner classes ✓ Creating static inner classes ✓ Implementing anonymous classes ✓ Adding Lambda expressions I n this chapter, you find out how to use three advanced types of classes: inner classes, static inner classes, and anonymous inner classes. All three types are read more..

  • Page - 346

    Declaring Inner Classes 322 The class that contains the inner class is called an outer class. You can use a visibility modifier with the inner class to specify whether the class should be public, protected, or private. This visibility determines whether other classes can see the inner class. Understanding inner classes At the surface, an inner class is simply a class that’s read more..

  • Page - 347

    Book III Chapter 7 Using Inner Classes, Anonymous Classes, and Lambda Expressions Declaring Inner Classes 323 Listing 7-1 shows a version of this application that implements the Ticker class as an inner class. Listing 7-1: Tick Tock with an Inner Class import java.awt.event.*; import javax.swing.*; public class TickTockInner { private String tickMessage = "Tick..."; ➝6 read more..

  • Page - 348

    Declaring Inner Classes 324 The following paragraphs describe some of the highlights of this program: ➝ 6 The String variables named tickMessage and tockMessage (line 7) contain the messages to be printed on the console. Note that these variables are defined as fields of the outer class. As you’ll see, the inner class Ticker is able to access these fields read more..

  • Page - 349

    Book III Chapter 7 Using Inner Classes, Anonymous Classes, and Lambda Expressions Using Static Inner Classes 325 strictly required here, but if you leave it out, the timer continues to run for a few seconds after you click OK before the JVM figures out that it should kill the timer. ➝ 29 This line is the declaration for the inner class named Ticker. Note that read more..

  • Page - 350

    Using Anonymous Inner Classes 326 private void go() { // create a timer that calls the Ticker class // at one second intervals Timer t = new Timer(1000, new Ticker()); t.start(); // display a message box to prevent the // program from ending immediately read more..

  • Page - 351

    Book III Chapter 7 Using Inner Classes, Anonymous Classes, and Lambda Expressions Using Anonymous Inner Classes 327 it even works. When you get the hang of working with anonymous classes, you’ll wonder how you got by without them. An anonymous class is a class that’s defined on the spot, right at the point where you want to instantiate it. Because you code the body read more..

  • Page - 352

    Using Anonymous Inner Classes 328 When you run this program, the single line You hit it! is displayed on the console. Here are some things to ponder when you work with anonymous classes: ✦ You can’t create a constructor for an anonymous class, because the anonymous class doesn’t have a name. What would you call the con- structor, anyway? ✦ You can’t pass read more..

  • Page - 353

    Book III Chapter 7 Using Inner Classes, Anonymous Classes, and Lambda Expressions Using Anonymous Inner Classes 329 new ActionListener() ➝20 { ➝21 private boolean tick = true; public void actionPerformed( ➝24 ActionEvent event) read more..

  • Page - 354

    Using Lambda Expressions 330 the parameter list for the Timer constructor. The left parenthesis that’s paired with this right parenthesis is on line 19. Finally, the semicolon marks the end of the assignment statement that started on line 19. Using Lambda Expressions Java 8 introduces a new feature that in some ways is similar to anonymous classes, but with more concise read more..

  • Page - 355

    Book III Chapter 7 Using Inner Classes, Anonymous Classes, and Lambda Expressions Using Lambda Expressions 331 You can use a lambda expression anywhere you can use a normal Java expression. You’ll use them most in assignment statements or as passed parameters. The only restriction is that you can use a lambda expression only in a context that requires an instance of a read more..

  • Page - 356

    332 Book III: Object-Oriented Programming read more..

  • Page - 357

    Chapter 8: Packaging and Documenting Your Classes In This Chapter ✓ Creating packages for your classes ✓ Archiving your packages in JAR files ✓ Documenting your classes with JavaDocs T his chapter shows you what to do with the classes you create. Specifically, I show you how to organize classes into neat packages. Packages enable you to keep your classes separate read more..

  • Page - 358

    Working with Packages 334 An import statement can import all the classes in a package by using an asterisk wildcard. Here all the classes in the java.util package are imported: import java.util.*; Alternatively, you can import classes one at a time. Here just the ArrayList class is imported: import java.util.ArrayList; Note: You don’t have to use an import statement to read more..

  • Page - 359

    Book III Chapter 8 Packaging and Documenting Y our Classes Working with Packages 335 name — at least it has no name that you can use inside a program. The com.lowewriter.util package’s code can’t contain a statement like this one: import that_default_package.you_know.the_one_with_no_name Creating your own packages Creating your own packages to hold your classes is easy. Well, read more..

  • Page - 360

    Working with Packages 336 the name of your root). Then, in the com directory, create a directory named lowewriter. Then, in lowewriter, create a directory named util. Thus, the complete path to the directory that contains the classes for the com.lowewriter.util package is c:\javaclasses\com\ lowewriter\util. 4. Add the root directory for your package to the ClassPath read more..

  • Page - 361

    Book III Chapter 8 Packaging and Documenting Y our Classes Working with Packages 337 com.lowewriter.util so you and other like-minded programmers can use it in their programs. Here’s the source file for the Console class: package com.lowewriter.util; import java.util.Scanner; public class Console { static Scanner sc = new Scanner(System.in); public static boolean askYorN(String read more..

  • Page - 362

    Putting Your Classes in a JAR File 338 { while (Console.askYorN("Keep going?")) { System.out.println("D'oh!"); } } } Here the import statement imports all the classes in the com.lowewriter. util package. Then, the while loop in the main method repeatedly asks the user if read more..

  • Page - 363

    Book III Chapter 8 Packaging and Documenting Y our Classes Putting Your Classes in a JAR File 339 The basic format of the jar command is this: jar options jar-file [manifest-file] class-files... The options specify the basic action you want jar to perform and provide additional information about how you want the command to work. Table 8-1 lists the options. Table 8-1 Options read more..

  • Page - 364

    Putting Your Classes in a JAR File 340 If you have trouble running the jar command in Step 3, you may need to open the command prompt in Administrator mode. To do so, click the Start menu, type cmd, right-click cmd.exe at the top of the Start menu, and choose Run as Administrator. 2. Use a cd command to navigate to your package root. For example, if read more..

  • Page - 365

    Book III Chapter 8 Packaging and Documenting Y our Classes Putting Your Classes in a JAR File 341 Here I added the path c:\javaclasses\utils.jar to my ClassPath variable. Starting with Java 1.6, you can add all the jar files from a particular direc- tory to the ClassPath in one fell swoop. For example, imagine that your c:\javaclasses directory contains two jar files read more..

  • Page - 366

    Using JavaDoc to Document Y our Classes 342 Then run the jar command with the options cfm, the name of the archive to create, the name of the manifest file, and the path for the class files. Here’s an example: jar cfm game.jar com\lowewriter\game\game.mf com\lowewriter\game\*.class Now you can run the application directly from a command prompt by using the java command with read more..

  • Page - 367

    Book III Chapter 8 Packaging and Documenting Y our Classes Using JavaDoc to Document Y our Classes 343 The text in a JavaDoc comment can include HTML markup if you want to apply fancy formatting. You should avoid using heading tags ( <h1> and so on) because JavaDoc creates those, and your heading tags just confuse things. But you can use tags for boldface and read more..

  • Page - 368

    Using JavaDoc to Document Y our Classes 344 Listing 8-1: An Employee Class with JavaDoc Comments package com.lowewriter.payroll; /** Represents an employee. * @author Doug Lowe * @author www.LoweWriter.com * @version 1.5 * @since 1.0 */ public class Employee { private String lastName; private String firstName; private Double salary; /** Represents the employee's address. read more..

  • Page - 369

    Book III Chapter 8 Packaging and Documenting Y our Classes Using JavaDoc to Document Y our Classes 345 /** Gets the employee's first name. * @return A string representing the employee's first * name. */ public String getFirstName() { return this.firstName; } /** Sets the employee's first name. * @param read more..

  • Page - 370

    Using JavaDoc to Document Y our Classes 346 The javadoc command creates the documentation pages in the current directory, so you may want to switch to the directory where you want the pages to reside first. For more complete information about using this command, refer to the javadoc documentation at the Sun website. You can find it here: java.sun.com/j2se/javadoc Viewing JavaDoc read more..

  • Page - 371

    Book III Chapter 8 Packaging and Documenting Y our Classes Using JavaDoc to Document Y our Classes 347 To look at the documentation for a class, click the class name’s link. A page with complete documentation for the class comes up. For example, Figure 8-2 shows part of the documentation page for the Employee class. JavaDocs generated this page from the source read more..

  • Page - 372

    348 Book III: Object-Oriented Programming read more..

  • Page - 373

    Book IV Strings, Arrays, and Collections You can find an interesting programming challenge that requires use of many of the programming techniques covered in this minibook at www.dummies.com/ extras/javaaio. The challenge is to enhance the Tic-Tac-Toe program you’ve created for Books II and III so that it plays with even better strategy. You will also use an array for read more..

  • Page - 374

    Contents at a Glance Contents at a Glance Chapter 1: Working with Strings ...............................351 Reviewing Strings .............................................................................................................351 Using the String Class ......................................................................................................353 Using the StringBuilder and StringBuffer Classes read more..

  • Page - 375

    Chapter 1: Working with Strings In This Chapter ✓ Quickly reviewing what you already know about strings ✓ Examining string class methods ✓ Working with substrings ✓ Splitting strings ✓ Using the StringBuilder and StringBuffer classes ✓ Using the CharSequence interface S trings are among the most common types of objects in Java. Throughout this book are various techniques read more..

  • Page - 376

    Reviewing Strings 352 ✦ Strings can include escape sequences that consist of a slash followed by another character. The most common escape sequences are \n for new line and \t for tab. If you want to include a slash in a string, you must use the escape sequence \\. Here is a complete list of all the escape sequences you can use: Escape Sequence Explanation \n read more..

  • Page - 377

    Using the String Class 353 Book IV Chapter 1 W orking with Strings ✦ You can also use the += operator with strings, like this: line2 += "\nI've got a beautiful feeling"; ✦ When a primitive type is used in a concatenation expression, Java auto- matically converts the primitive type to a string. Thus Java allows the following: int empCount = 50; String msg = read more..

  • Page - 378

    Using the String Class 354 Method Description boolean contains(CharSequence) Returns true if this string contains the parameter value. The parameter can be a String, StringBuilder, or StringBuffer. boolean endsWith(String) Returns true if this string ends with the parameter string. boolean equals(String) Returns true if this string has the same value as the parameter string. boolean read more..

  • Page - 379

    Using the String Class 355 Book IV Chapter 1 W orking with Strings Method Description String replaceFirst(String old, String new) Returns a new string that’s based on the original string, but with the first occurrence of the first string replaced by the second parameter. Note that the first parameter can be a regular expression. String[] split(String) Splits the string into read more..

  • Page - 380

    Using the String Class 356 The most important thing to remember about the String class is that in spite of the fact that it has a bazillion methods, none of those methods let you alter the string in any way. A String object is immutable, which means that it can’t be changed. Although you can’t change a string after you create it, you can use methods of the read more..

  • Page - 381

    Using the String Class 357 Book IV Chapter 1 W orking with Strings return value from one of these methods. The following statement has no effect on s: s.trim(); Here the trim method trims the string — but then the program discards the result. The remedy is to assign the result of this expression back to s, like this: s = s.trim(); Extracting characters from a string You can read more..

  • Page - 382

    Using the String Class 358 Here the for loop checks the length of the string to make sure that the index variable i doesn’t exceed the string length. Then each character is extracted and checked with an if statement to see whether it is a vowel. The condi- tion expression in this if statement is a little complicated because it must check for five different read more..

  • Page - 383

    Using the String Class 359 Book IV Chapter 1 W orking with Strings int vowelCount = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if ( (c == 'A') || (c == 'a') || (c == 'E') || (c == 'e') read more..

  • Page - 384

    Using the String Class 360 Unfortunately, the use of the split method requires that you use an array, and arrays are covered in the next chapter. I’m going to plow ahead with this section anyway on a hunch that you already know a few basic things about arrays. (If not, you can always come back to this section after you read the next chapter.) The split method read more..

  • Page - 385

    Using the String Class 361 Book IV Chapter 1 W orking with Strings { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { System.out.print("Enter a string: "); String s = sc.nextLine(); String[] word = s.split("\\s+"); for (String w : word) read more..

  • Page - 386

    Using the StringBuilder and StringBuffer Classes 362 As with the split methods, the first parameter of replace methods can be a regular expression that provides a complex matching string. (For more information, see Book V, Chapter 3.) Once again, don’t forget that strings are immutable. As a result, the replace methods don’t actually modify the String object itself. read more..

  • Page - 387

    Using the StringBuilder and StringBuffer Classes 363 Book IV Chapter 1 W orking with Strings extensive string manipulation, however, Java offers two alternatives to the String class: the StringBuilder and StringBuffer classes. The StringBuilder and StringBuffer classes are mirror images. Both have the same methods and perform the same string manipulations. The only difference is that read more..

  • Page - 388

    Using the StringBuilder and StringBuffer Classes 364 Table 1-2 StringBuilder Methods Method Description append(primitiveType) Appends the string representation of the primitive type to the end of the string. append(Object) Calls the object’s toString method and appends the result to the end of the string. append(CharSequence) Appends the string to the end of the StringBuilder’s string read more..

  • Page - 389

    Using the StringBuilder and StringBuffer Classes 365 Book IV Chapter 1 W orking with Strings Method Description insert(int, CharSequence) Inserts the string at the point specified by the int argument. The second parameter can be a String, StringBuilder, or StringBuffer. int lastIndexOf(String) Returns the index of the last occur- rence of the specified string. If the string doesn’t read more..

  • Page - 390

    Using the CharSequence Interface 366 Viewing a StringBuilder example To illustrate how the StringBuilder class works, here’s a StringBuilder version of the MarkVowels program from earlier in this chapter: import java.util.Scanner; public class StringBuilderApp { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { read more..

  • Page - 391

    Using the CharSequence Interface 367 Book IV Chapter 1 W orking with Strings Toward that end, several of the methods of the String, StringBuilder, and StringBuffer classes use CharSequence as a parameter type. For those methods, you can pass a String, StringBuilder, or StringBuffer object. Note that a string literal is treated as a String object, so you can use a read more..

  • Page - 392

    368 Book IV: Strings, Arrays, and Collections read more..

  • Page - 393

    Chapter 2: Using Arrays In This Chapter ✓ Working with basic one-dimensional arrays ✓ Using array initializers to set the initial values of an array ✓ Using for loops with arrays ✓ Working with two-dimensional arrays ✓ Working with the Arrays class I could use a raise. . . . Oh, arrays. Sorry. Arrays are an important aspect of any programming language, and Java read more..

  • Page - 394

    Creating Arrays 370 The real power of arrays comes from the simple fact that you can use a variable or even a complete expression as an array index. So (for example) instead of coding x[5]to refer to a specific array element, you can code x[i]to refer to the element indicated by the index variable i. You see plenty of examples of index variables throughout this read more..

  • Page - 395

    Book IV Chapter 2 Using Arrays Initializing an Array 371 By itself, that statement doesn’t create an array; it merely declares a variable that can refer to an array. You can actually create the array in two ways: ✦ Use the new keyword followed by the array type, this time with the brackets filled in to indicate how many elements the array can hold. For example: read more..

  • Page - 396

    Using for Loops with Arrays 372 Here each element to be assigned to the array is listed in an array initializer. Here’s an example of an array initializer for an int array: int[] primes = { 2, 3, 5, 7, 11, 13, 17 }; Note: The length of an array created with an initializer is determined by the number of values listed in the initializer. An alternative way to read more..

  • Page - 397

    Book IV Chapter 2 Using Arrays Solving Homework Problems with Arrays 373 Solving Homework Problems with Arrays Every once in a while, an array and a for loop or two can help you solve your kids’ homework problems for them. I once helped my daughter solve a tough homework assignment for a seventh-grade math class. The problem was stated something like this: Bobo (these read more..

  • Page - 398

    Solving Homework Problems with Arrays 374 for (int skip = 1; skip <= 1000; skip++) ➝12 { System.out.println("Bobo is changing every " + skip + " lockers."); for (int locker = skip; locker < 1000; ➝16 locker += skip) read more..

  • Page - 399

    Book IV Chapter 2 Using Arrays Using the Enhanced for Loop 375 ➝ 18 This statement uses the not operator ( !) to reverse the setting of each locker. Thus, if the locker is open ( true), it’s set to closed ( false), and vice versa. ➝ 27 Yet another for loop spins through all the lockers and counts the ones that are open. It also adds the locker read more..

  • Page - 400

    Using Arrays with Methods 376 This loop prints the following lines to the console: Sunday Monday Tuesday Wednesday Thursday Friday Saturday In other words, it prints each of the strings in the array on a separate line. Using Arrays with Methods You can write methods that accept arrays as parameters and return arrays as return values. You just use an empty set of brackets to read more..

  • Page - 401

    Book IV Chapter 2 Using Arrays Using Two-Dimensional Arrays 377 Using Two-Dimensional Arrays The elements of an array can be any type of object you want, including another array. In the latter case, you have a two-dimensional array, some- times called an array of arrays. Two-dimensional arrays are often used to track data in column-and-row format, much the way that a spreadsheet read more..

  • Page - 402

    Using Two-Dimensional Arrays 378 To create the array, you use the new keyword and provide lengths for each set of brackets, as in this example: sales = new double[5][4]; Here the first dimension specifies that the sales array has five elements. This array represents the rows in the table. The second dimension specifies that each of those elements has an array of type read more..

  • Page - 403

    Book IV Chapter 2 Using Arrays Using Two-Dimensional Arrays 379 Assuming that the sales array has already been initialized, this code produces the following output on the console: North South East West 2004 $23,853.00 $22,838.00 $36,483.00 $31,352.00 2005 read more..

  • Page - 404

    Using Two-Dimensional Arrays 380 Here I added a comment to the end of each line to show the year that the line initializes. Notice that the left brace for the entire initializer is at the beginning of the second line, and the right brace that closes the entire initializer is at the end of the last line. Then the initializer for each year is contained in its own read more..

  • Page - 405

    Book IV Chapter 2 Using Arrays Using Two-Dimensional Arrays 381 Notice that the length of each subarray is determined with the expression teams[i].length. This for loop prints one name on each line, with a blank line between teams, like this: Margaret Houlihan Frank Burns Max Klinger Radar O'Reilly Igor Straminsky Henry Blake Johnny Mulcahy Benjamin Pierce John McIntyre Jonathan Tuttle If read more..

  • Page - 406

    382 Working with a Fun but Complicated Example: A Chessboard You can nest initializers as deep as necessary, too. For example: int[][][] threeD = { { {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} } }; Here a read more..

  • Page - 407

    Book IV Chapter 2 Using Arrays Working with a Fun but Complicated Example: A Chessboard 383 Figure 2-1: A classic chessboard. Here’s a sample of what the console looks like if you enter e4 for the knight’s position: Welcome to the Knight Move calculator. Enter knight's position: e4 The knight is at square e4 From here the knight can move to: c5 d6 f6 g5 g3 f2 d2 c3 read more..

  • Page - 408

    Working with a Fun but Complicated Example: A Chessboard 384 As you can see, the program indicates that the knight’s legal moves from e4 are c5, d6, f6, g5, g3, f2, d2, and c3. Also, the graphic representation of the board indicates where the knight is and where he can go. Listing 2-2: Playing Chess in a For Dummies Book import java.util.Scanner; public class KnightMoves read more..

  • Page - 409

    Book IV Chapter 2 Using Arrays Working with a Fun but Complicated Example: A Chessboard 385 for (int move = 0; move < moves.length; move ++) ➝59 { int x, y; x = moves[move][0]; // the x for this move y = moves[move][1]; // the y for this move read more..

  • Page - 410

    Working with a Fun but Complicated Example: A Chessboard 386 if (p.x == 3) file = "d"; if (p.x == 4) file = "e"; if (p.x == 5) file = "f"; if (p.x == 6) file = "g"; if (p.x == 7) file = "h"; return file + (p.y + 1); read more..

  • Page - 411

    Book IV Chapter 2 Using Arrays Working with a Fun but Complicated Example: A Chessboard 387 // this class represents x, y coordinates on the board class Pos ➝183 { public int x; public int y; public Pos(int x, int y) { this.x = x; this.y = y; } } You have to put your thinking cap on to read more..

  • Page - 412

    Working with a Fun but Complicated Example: A Chessboard 388 method accepts a board position and x and y values to indicate where the knight can be moved. If the resulting move is legal, it returns a new Pos object that indicates the position the move leads to. If the move is not legal (that is, it takes the knight off the board), the calculateNewPos method returns read more..

  • Page - 413

    Book IV Chapter 2 Using Arrays Using the Arrays Class 389 ➝ 167 The getYorN method simply displays a prompt on-screen and asks the user to enter Y or N. It returns true if the user enters Y or false if the user enters N. If the user enters anything else, this method prompts the user again. ➝ 183 The Pos class simply defines two public fields, read more..

  • Page - 414

    Using the Arrays Class 390 Method Description boolean equals(array1, array2) Returns true if the two arrays have the same element values. This method checks equality only for one-dimensional arrays. static void fill(array, value) Fills the array with the specified value. The value and array must be of the same type and can be any primitive type or an object. static read more..

  • Page - 415

    Book IV Chapter 2 Using Arrays Using the Arrays Class 391 Unfortunately, this code won’t work. What happens is that the expression is evaluated once to get a random number; then all 1,000 elements in the array are set to that random number. Copying an array In Java 1.6, the Arrays class has some useful new methods. Using the new copyOf and copyOfRange methods, you can read more..

  • Page - 416

    Using the Arrays Class 392 If you do, arrayNew has fewer than three elements: 42 55 You can also change the number 3 to something larger: int arrayNew[] = Arrays.copyOf(arrayOriginal, 8 ); Then arrayNew has more than three elements: 42 55 21 0 0 0 0 0 The copyOfRange method is even more versatile. If you execute the instructions int arrayOriginal[] = {42, 55, 21, 16, read more..

  • Page - 417

    Book IV Chapter 2 Using Arrays Using the Arrays Class 393 Here the for loop compares each element in the array with your lucky number. This code works fine for small arrays, but what if the array had 1,000,000 elements instead of 6? In that case, it would take a while to look at each element. If the array is sorted in sequence, the binarySearch method can find read more..

  • Page - 418

    Using the Arrays Class 394 int[] lotto = new int[6]; for (int i = 0; i < 6; i++) lotto[i] = (int)(Math.random() * 100) + 1; System.out.println(Arrays.toString(lotto)); Here’s a sample of the console output created by this code: [4, 90, 65, 84, 99, 81] Note that the toString method works only for one-dimensional arrays. To print the contents of a two-dimensional read more..

  • Page - 419

    Chapter 3: Using the ArrayList Class In This Chapter ✓ Working with the ArrayList class ✓ Creating an array list ✓ Introducing generics ✓ Adding elements to an array list ✓ Deleting elements from or modifying elements in an array list S ome people love to collect things: nick-knacks, baseball cards, postage stamps, dolls — you name it, someone collects it. If I were read more..

  • Page - 420

    Understanding the ArrayList Class 396 Java 1.5 introduced a major new language feature called generics that is aimed specifically at making collections easier to work with. Specifically, the gener- ics feature lets you create list objects, such as ArrayList or LinkedList, that are bound to a specific data type, such as strings or integers. Because generics are an integral part read more..

  • Page - 421

    Book IV Chapter 3 Using the ArrayList Class Understanding the ArrayList Class 397 ✦ The ArrayList class actually uses an array internally to store the data you add to the array list. The ArrayList class takes care of managing the size of this array. When you add an item to the array list, and the underlying array is full, the ArrayList class automatically read more..

  • Page - 422

    Understanding the ArrayList Class 398 Constructor Explanation containsAll(Collection c) Returns a boolean that indicates whether this array list contains all the objects that are in the specified collection. ensureCapacity(int minCapacity) Increases the array list’s capacity to the specified value. (If the capacity is already greater than the specified value, this method does read more..

  • Page - 423

    Book IV Chapter 3 Using the ArrayList Class Creating an ArrayList Object 399 Constructor Explanation set(int index, Object elem) Sets the specified element to the specified object. The element that was previously at that position is returned as the method’s return value. size() Returns the number of elements in the list. toArray() Returns the elements of the array list as an read more..

  • Page - 424

    Adding Elements 400 ✦ If you’re using Java 1.5 or later, you can also specify the type of elements the array list is allowed to contain. This statement creates an array list that holds String objects: ArrayList<String> signs = new ArrayList<String>(); The advantage of specifying a type when you declare an array list is that the compiler complains if you read more..

  • Page - 425

    Book IV Chapter 3 Using the ArrayList Class Accessing Elements 401 Here are some important points to keep in mind when you add elements to array lists: ✦ If an array list is already at its capacity when you add an element, the array list automatically expands its capacity. Although this capacity is flexible, it’s also inefficient. Whenever possible, you should anticipate read more..

  • Page - 426

    Printing an ArrayList 402 Depending on the contents of the array list, the output from this loop may look something like this: Item 0: One Item 1: Two Item 2: Three Item 3: Four Printing an ArrayList The toString method of the ArrayList class (as well as other collection classes) is designed to make it easy to quickly print out the contents of the list. It returns the read more..

  • Page - 427

    Book IV Chapter 3 Using the ArrayList Class Using an Iterator 403 An iterator object implements the Iterator interface, which is defined as part of the java.util package. As a result, to use an iterator, you must import either java.util.Iterator or java.util.*. The Iterator interface defines just three methods, as listed in Table 3-2. These methods are all you need to access read more..

  • Page - 428

    Updating Elements 404 To use an iterator, you first call the array list’s iterator method to get the iterator. Then you use the iterator’s hasNext and next methods to retrieve each item in the collection. The normal way to do that is with a while loop. Here’s an example: ArrayList<String> nums = new ArrayList<String>(); nums.add("One"); read more..

  • Page - 429

    Book IV Chapter 3 Using the ArrayList Class Updating Elements 405 Here an array list is created with three strings, and the contents of the array list are printed to the console. Then each of the three strings is replaced by another string, and the contents print to the console again. When you run this code, the following is what you see printed on the console: [One, read more..

  • Page - 430

    Deleting Elements 406 Here’s what this code produces on the console: [Gomez Addams, Andy Taylor, James Kirk] [Gomez Addams, Robert Petrie, James Kirk] Notice that the second employee’s name was changed, even though the pro- gram doesn’t use the set method to replace the changed Employee object in the collection. That’s because the array list merely stores references to read more..

  • Page - 431

    Book IV Chapter 3 Using the ArrayList Class Deleting Elements 407 Here’s what this code produces on the console: [Gomez Addams, Andy Taylor, James Kirk] [Gomez Addams, James Kirk] As you can see, the program was able to remove Andy Taylor from the list without knowing his index position. Here are a few important details to keep in mind: ✦ The clear and remove read more..

  • Page - 432

    408 Book IV: Strings, Arrays, and Collections read more..

  • Page - 433

    Chapter 4: Using the LinkedList Class In This Chapter ✓ Introducing linked lists ✓ Comparing linked lists with array lists ✓ Creating linked lists ✓ Adding items to a linked list ✓ Retrieving items from a linked list ✓ Updating and deleting items in a linked list T he ArrayList class, which I cover in the preceding chapter, is a collec- tion class that’s read more..

  • Page - 434

    Understanding the LinkedList Class 410 working with programs that were written before Java 1.5 became available. (For a complete explanation of how the generics feature works, you can read Book IV, Chapter 5.) Also, be aware that lambda expressions, introduced with Java 8, provide an alternative method for working with collections, including the LinkedList class. For more information read more..

  • Page - 435

    Book IV Chapter 4 Using the LinkedList Class Understanding the LinkedList Class 411 ✦ Linked lists are especially well suited for creating two common types of lists: Stacks: A stack is a list in which items can be added to and retrieved from only the front of the list. Queues: A queue is a list in which items are always added to the back of the list and read more..

  • Page - 436

    Understanding the LinkedList Class 412 Constructor Explanation addAll(int index, Collection c) Adds all the elements of the specified collection to this linked list at the specified index position. addFirst (Object element) Inserts the specified object at the begin- ning of the list. If you specified a type when you created the linked list, the object must be of the correct read more..

  • Page - 437

    Book IV Chapter 4 Using the LinkedList Class Understanding the LinkedList Class 413 Constructor Explanation lastIndexOf (Object elem) Returns the index position of the last occur- rence of the specified object in the linked list. If the object isn’t in the list, it returns -1. offer (Object elem) Adds the specified object to the end of the list. This method returns a read more..

  • Page - 438

    Understanding the LinkedList Class 414 Constructor Explanation remove(Object elem) Removes an object from the list. Note that if more than one element refers to the object, this method removes only one of them. It returns a boolean that indicates whether the object was in the list. removeAll (Collection c) Removes all the objects in the specified collection from this linked read more..

  • Page - 439

    Book IV Chapter 4 Using the LinkedList Class Adding Items to a LinkedList 415 In some cases, however, the methods are identical, such as the remove and removeFirst methods. In fact, if you’re crazy enough to look at the source code for the LinkedList class, you’ll find that the remove method consists of a single line: a call to the removeFirst method. Creating read more..

  • Page - 440

    Adding Items to a LinkedList 416 The addLast method works the same way, but the addFirst method adds items to the front of the list. Consider these statements: LinkedList<String> officers = new LinkedList<String>(); officers.addFirst("Blake"); officers.addFirst("Burns"); officers.addFirst("Houlihan"); officers.addFirst("Pierce"); officers.addFirst("McIntyre"); for read more..

  • Page - 441

    Book IV Chapter 4 Using the LinkedList Class Retrieving Items from a LinkedList 417 Here are some other thoughts to consider when you ponder how to add elements to linked lists: ✦ If you specified a type for the list when you created it, the items you add must be of the correct type. The compiler kvetches if they aren’t. ✦ Like arrays and everything else read more..

  • Page - 442

    Updating LinkedList Items 418 ✦ element: Identical to the getFirst method. This strangely named method exists because it’s defined by the Queue interface, and the LinkedList class implements Queue. ✦ peek: Similar to getFirst but doesn’t throw an exception if the list is empty. Instead, it just returns null. (The Queue interface also defines this method.) read more..

  • Page - 443

    Book IV Chapter 4 Using the LinkedList Class Removing LinkedList Items 419 officers.add("Houlihan"); officers.add("Pierce"); officers.add("McIntyre"); System.out.println(officers); // replace Tuttle with Murdock officers.set(2, "Murdock"); System.out.println("\nTuttle is replaced:"); System.out.println(officers); The output from this code looks like this: [Blake, Burns, Tuttle, read more..

  • Page - 444

    420 Book IV: Strings, Arrays, and Collections read more..

  • Page - 445

    Chapter 5: Creating Generic Collection Classes In This Chapter ✓ Discovering why the generics feature was invented ✓ Using generics in your own classes ✓ Working with wildcards in a generic class ✓ Examining a pair of classes that demonstrate generics I n the previous two chapters, you’ve seen how you can specify the type for an ArrayList or a LinkedList so read more..

  • Page - 446

    Why Generics? 422 Why Generics? Before Java 1.5, collection classes could hold any type of object. For example, the add method for the ArrayList class had this declaration: public boolean add(Object o) { // code to implement the add method } Thus, you could pass any type of object to the add method — and the array list gladly accepted it. When you retrieved read more..

  • Page - 447

    Book IV Chapter 5 Creating Generic Collection Classes Creating a Generic Class 423 Creating a Generic Class Generics let you create classes that can be used for any type specified by the programmer at compile time. To accomplish that, the Java designers intro- duced a new feature to the language, called formal type parameters. To create a class that uses a formal read more..

  • Page - 448

    A Generic Stack Class 424 Here E is specified as the return type. That means that if E is Employee, this method returns Employee objects. One final technique you need to know before moving on: You can use the formal type parameter within your class to create objects of any other class that accepts formal type parameters. For example, the clone method of the read more..

  • Page - 449

    Book IV Chapter 5 Creating Generic Collection Classes A Generic Stack Class 425 ✦ peek: This method lets you peek at the top item on the stack. In other words, it returns the top item without removing it. If the stack is empty, it returns null. ✦ hasItems: This method returns a boolean value of true if the stack has at least one item in it. ✦ read more..

  • Page - 450

    A Generic Stack Class 426 The following paragraphs highlight the important details in this class: ➝ 3 The class declaration specifies the formal type parameter <E>. Thus users of this class can specify the type for the stack’s elements. ➝ 5 This class uses a private LinkedList object list to keep the items stored in the stack. The LinkedList is read more..

  • Page - 451

    Book IV Chapter 5 Creating Generic Collection Classes A Generic Stack Class 427 System.out.println("Popping everything:"); while (gs.hasItems()) System.out.println(gs.pop()); System.out.println("There are now " + gs.size() + " items in the stack.\n"); read more..

  • Page - 452

    Using Wildcard-Type Parameters 428 Using Wildcard-Type Parameters Suppose you have a method that’s declared like this: public void addItems(ArrayList<Object> list) { // body of method not shown } Thought question: Does the following statement compile? addItems(new ArrayList<String>()); Answer: Nope. That’s surprising because String is a subtype of Object. So you’d think that read more..

  • Page - 453

    Book IV Chapter 5 Creating Generic Collection Classes A Generic Queue Class 429 want the addItems method to accept an ArrayList of type E or any of its subclasses. To do that, you’d declare the addItems method like this: public void addItems(ArrayList<? extends E> list) Here the wildcard type parameter <? extends E> simply means that the ArrayList can be of read more..

  • Page - 454

    A Generic Queue Class 430 { list.addLast(item); } public E dequeue() ➝12 { return list.poll(); } public boolean hasItems() ➝17 { return !list.isEmpty(); } public int size() ➝22 { return list.size(); } read more..

  • Page - 455

    Book IV Chapter 5 Creating Generic Collection Classes A Generic Queue Class 431 The following program exercises the GenQueue class: public class GenQueueTest { public static void main(String[] args) { GenQueue<Employee> empList; empList = new GenQueue<Employee>(); GenQueue<HourlyEmployee> hList; read more..

  • Page - 456

    Using the Diamond Operator 432 class HourlyEmployee extends Employee { public double hourlyRate; public HourlyEmployee(String last, String first) { super(last, first); } } This program begins by creating a GenQueue object that can hold Employee objects. This queue is assigned to a variable named empList. Next, the program creates another read more..

  • Page - 457

    Book IV Chapter 5 Creating Generic Collection Classes Using the Diamond Operator 433 Java 7 introduced a new feature called the diamond operator that lets you skip the type when you call the constructor, like this: ArrayList<String> nums = new ArrayList<>(); Here’s another example: ArrayList<String> nums; nums = new ArrayList<>(); The diamond operator simply deduces the read more..

  • Page - 458

    434 Book IV: Strings, Arrays, and Collections read more..

  • Page - 459

    Chapter 6: Using Bulk Data Operations with Collections In This Chapter ✓ Understanding basic stream operations ✓ Examining the stream interface ✓ Filtering and sorting streams ✓ Computing sums, averages, and other values O ne of the most common things to do with a collection is to iterate over it, performing some type of operation on all of its elements. For read more..

  • Page - 460

    Looking At a Basic Bulk Data Operation 436 collection’s elements and let Java take care of the messy details required to spread the work over multiple threads. At the heart of the bulk data operations feature is a new type of object called a stream, defined by the stream interface. A stream is simply a sequence of elements of any data type which can be processed read more..

  • Page - 461

    Book IV Chapter 6 Using Bulk Data Operations with Collections Looking At a Basic Bulk Data Operation 437 public String toString() { return name; } } As you can see, the Spell class has three public fields that represent the spell’s name, type ( SPELL, CHARM, or CURSE), and description, as well as a constructor that lets you read more..

  • Page - 462

    Looking Closer at the Stream Interface 438 Suppose you want to list just the spells, not the charms or curses. Using a traditional foreach loop, you’d do it like this: for (Spell spell : spells) { if (spell.type == Spell.SpellType.SPELL) System.out.println(spell.name); } Here an if statement selects just the spells so that the charms and curses aren’t read more..

  • Page - 463

    Book IV Chapter 6 Using Bulk Data Operations with Collections Looking Closer at the Stream Interface 439 Table 6-1 The Stream and Related Interfaces Methods that Return Streams Explanation Stream distinct() Returns a stream consisting of distinct elements of the input stream. In other words, duplicates are removed. Stream limit(long maxSize) Returns a stream having no more than read more..

  • Page - 464

    Looking Closer at the Stream Interface 440 void forEachOrdered (Consumer<? super T> action) Executes the action against each ele- ment of the input stream, ensuring that the elements of the input stream are processed in order. long count() Returns the number of elements in the stream. Optional<T> max(Comparator<? super T> comparator) Returns the largest element in the read more..

  • Page - 465

    Book IV Chapter 6 Using Bulk Data Operations with Collections Looking Closer at the Stream Interface 441 true, the element is passed on to the result stream. If it returns false, the element is not passed on. The easiest way to implement a filter predicate is to use a Lambda expres- sion that specifies a conditional expression. For example, the following Lambda expression read more..

  • Page - 466

    Using Parallel Streams 442 For example, the average method calculates the average value of a stream of integers, longs, or doubles and returns the result as an OptionalDouble. If the stream was empty, the average is undefined, so the OptionalDouble contains no value. You can determine if the OptionalDouble contains a value by calling its isPresent method, which returns read more..

  • Page - 467

    Book IV Chapter 6 Using Bulk Data Operations with Collections Using Parallel Streams 443 To demonstrate this point, consider this simple example: System.out.println("First Parallel stream: "); spells.parallelStream() .forEach(s -> System.out.println(s)); System.out.println("\nSecond Parallel stream: "); spells.parallelStream() .forEach(s -> System.out.println(s)); When you execute this read more..

  • Page - 468

    Book IV: Strings, Arrays, and Collections 444 read more..

  • Page - 469

    You can find an interesting programming challenge that requires use of many of the programming techniques covered in this minibook at www.dummies.com/ extras/javaaio. This challenge tasks you with creating a program that solves the classic Towers of Hanoi game. Book V Programming Techniques read more..

  • Page - 470

    Contents at a Glance Contents at a Glance Chapter 1: Programming Threads ..............................447 Understanding Threads ...................................................................................................448 Creating a Thread .............................................................................................................449 Implementing the Runnable Interface read more..

  • Page - 471

    Chapter 1: Programming Threads In This Chapter ✓ Examining threads ✓ Creating threads from the Thread class ✓ Working with the Runnable interface ✓ Creating threads that cooperate ✓ Executing threads ✓ Making methods cooperate ✓ Using a lock ✓ Interrupting threads R emember the guy from the old Ed Sullivan Show who used to spin plates? Somehow, he managed to keep read more..

  • Page - 472

    Understanding Threads 448 The listings in this chapter, as well as throughout the book, are available at www.dummies.com/extras/javaaio. Understanding Threads A thread is a single sequence of executable code within a larger program. All the programs shown so far in this book have used just one thread — the main thread that starts automatically when you run the program — but read more..

  • Page - 473

    Book V Chapter 1 Programming Threads Creating a Thread 449 Creating a Thread Suppose you’re developing software for NASA, and you’re in charge of the program that controls the final 31 seconds of the countdown for a manned spacecraft. Your software has to coordinate several key events that occur when the clock reaches certain points: ✦ T minus 16 seconds: Flood launch read more..

  • Page - 474

    Creating a Thread 450 Table 1-1 Constructors and Methods of the Thread Class Constructor Explanation Thread() Creates an instance of the Thread class. This constructor is the basic Thread constructor without parameters. Thread(String name) Creates a Thread object and assigns the specified name to the thread. Thread(Runnable target) Turns any object that implements an API interface read more..

  • Page - 475

    Book V Chapter 1 Programming Threads Creating a Thread 451 Extending the Thread class The easiest way to create a thread is to write a class that extends the Thread class. Then all you have to do to start a thread is create an instance of your thread class and call its start method. Listing 1-1 is a version of the CountDownClock class that extends the Thread read more..

  • Page - 476

    Implementing the Runnable Interface 452 Creating and starting a thread After you define a class that defines a Thread object, you can create and start the thread. Here’s the main class for the first version of the countdown application: public class CountDownApp { public static void main(String[] args) { Thread clock = new CountDownClock(); read more..

  • Page - 477

    Book V Chapter 1 Programming Threads Implementing the Runnable Interface 453 Using the Runnable interface To use the Runnable interface to create and start a thread, you have to do the following: 1. Create a class that implements Runnable. 2. Provide a run method in the Runnable class. 3. Create an instance of the Thread class and pass your Runnable object read more..

  • Page - 478

    Implementing the Runnable Interface 454 Listing 1-2: The LaunchEvent Class (Version 1) public class LaunchEvent implements Runnable ➝1 { private int start; private String message; public LaunchEvent(int start, String message) ➝6 { this.start = start; this.message = message; } public void run() read more..

  • Page - 479

    Book V Chapter 1 Programming Threads Implementing the Runnable Interface 455 Listing 1-3: The CountDownApp Class (Version 2) public class CountDownApp { public static void main(String[] args) { Thread clock = new CountDownClock(); ➝5 Runnable flood, ignition, liftoff; ➝7 flood = new LaunchEvent(16, "Flood the pad!"); read more..

  • Page - 480

    Implementing the Runnable Interface 456 T minus 14 T minus 13 T minus 12 T minus 11 T minus 10 T minus 9 T minus 8 T minus 7 T minus 6 Start engines! T minus 5 T minus 4 T minus 3 T minus 2 T minus 1 Liftoff! T minus 0 As you can see, the LaunchEvent messages are interspersed with the CountDownClock messages. Thus, the launch events are triggered at the correct read more..

  • Page - 481

    Book V Chapter 1 Programming Threads Creating Threads That Work T ogether 457 Creating Threads That Work T ogether Unfortunately, the countdown application presented in the preceding sec- tion has a major deficiency: The CountDownClock and LaunchEvent threads depend strictly on timing to coordinate their activities. After these threads start, they run independently of one another. As a read more..

  • Page - 482

    Creating Threads That Work T ogether 458 events.add(new LaunchEvent(0, "Liftoff!", clock)); clock.start(); ➝19 for (Runnable e : events) ➝21 new Thread(e).start(); } } interface TimeMonitor ➝26 { int getTime(); } class CountDownClock extends Thread read more..

  • Page - 483

    Book V Chapter 1 Programming Threads Creating Threads That Work T ogether 459 public LaunchEvent(int start, String message, TimeMonitor monitor) { this.start = start; this.message = message; this.tm = monitor; } public void run() { boolean eventDone = false; read more..

  • Page - 484

    Using an Executor 460 ➝ 33 A private field named t is used to store the current value of the countdown clock. That way, the current clock value can be accessed by the constructor, the run method, and the getTime method. ➝ 35 The constructor for the CountDownClock class accepts the start- ing time for the countdown as a parameter. Thus, this countdown read more..

  • Page - 485

    Book V Chapter 1 Programming Threads Using an Executor 461 Listing 1-5: A New CountDownClock public class CountDownClockNew implements Runnable { int t; public CountDownClockNew(int t) { this.t = t; } public void run() { System.out.println("T minus " + t); } } Listing 1-6: A New read more..

  • Page - 486

    Synchronizing Methods 462 pool.schedule(new CountDownClockNew(t), (long) (20 - t), TimeUnit.SECONDS); pool.schedule(flood, 3L, TimeUnit.SECONDS); pool.schedule(ignition, 13L, TimeUnit.SECONDS); pool.schedule(liftoff, 19L, TimeUnit.SECONDS); pool.shutdown(); } } In the read more..

  • Page - 487

    Book V Chapter 1 Programming Threads Synchronizing Methods 463 This code tells Java to place a lock on the object so that no other methods can call any other synchronized methods for the object until this method finishes. In other words, it temporarily disables multithreading for the object. (I discuss locking in the section “Creating a Lock,” later in this chapter.) read more..

  • Page - 488

    Synchronizing Methods 464 T minus 10 T minus 9 T minus 7 T minus 7 T minus 6 T minus 5 T minus 4 T minus 3 T minus 2 T minus 2 T minus 1 T minus 0 The two threads execute their loops simultaneously, so after one thread dis- plays its T minus 20, the other thread displays its own T minus 20. The same thing happens for T minus 19, T minus 18, and so on. read more..

  • Page - 489

    Book V Chapter 1 Programming Threads Synchronizing Methods 465 Listing 1-10: Using the synchronized Keyword class CountDownClockSync extends Thread { private int start; public CountDownClockSync(int start) { this.start = start; } synchronized public void run() { for (int t = start; t >= 0; t--) read more..

  • Page - 490

    Synchronizing Methods 466 Even methods that consist of just one line of code are at risk. Consider this method: int sequenceNumber = 0; public int getNextSequenceNumber() { return sequenceNumber++; } You’d think that because this method has just one statement, some other thread could not interrupt it in the middle. Alas, that’s not the case. This method must get read more..

  • Page - 491

    Book V Chapter 1 Programming Threads Creating a Lock 467 Creating a Lock A few years back, Java version 1.5 introduced many new threading fea- tures. One such feature was the introduction of locks. A lock can take the place of Java’s synchronized keyword, but a lock is much more versatile. Listings 1-11 and 1-12 illustrate the use of a lock. Listing 1-11: Creating read more..

  • Page - 492

    Coping with Threadus Interruptus 468 catch (InterruptedException e) {} } lock.unlock(); } } Listing 1-12 is remarkably similar to Listing 1-10. The only significant dif- ference is the replacement of the synchronized keyword by calls to ReentrantLock methods. At the start of Listing 1-12, read more..

  • Page - 493

    Book V Chapter 1 Programming Threads Coping with Threadus Interruptus 469 Unfortunately, finding out whether a thread has been interrupted isn’t as easy as it sounds. InterruptedException is thrown when another thread calls the interrupt method on this thread while the thread is not executing. That’s why the methods that can cause the thread to give up control to read more..

  • Page - 494

    Coping with Threadus Interruptus 470 To simplify the code a bit, I assume that things aren’t going well at NASA, so every launch event results in a failure that indicates a need to abort the countdown. Thus, whenever the start time for a LaunchEvent arrives, the LaunchEvent class attempts to abort the countdown. It goes without saying that in a real launch-control read more..

  • Page - 495

    Book V Chapter 1 Programming Threads Coping with Threadus Interruptus 471 boolean aborted = false; ➝40 for (; t >= 0; t--) { System.out.println("T minus " + t); try { Thread.sleep(1000); read more..

  • Page - 496

    Coping with Threadus Interruptus 472 public void run() { boolean eventDone = false; boolean aborted = false; ➝92 while (!eventDone) { try { Thread.sleep(10); } read more..

  • Page - 497

    Book V Chapter 1 Programming Threads Coping with Threadus Interruptus 473 ➝ 54 If the aborted field has been set to true, it means that the thread has been interrupted, so the message Stopping the clock! is displayed, and a break statement exits the loop. Thus the thread is terminated. ➝ 67 The abortCountDown method is synchronized. That happens because any read more..

  • Page - 498

    474 Book V: Programming Techniques read more..

  • Page - 499

    Chapter 2: Network Programming In This Chapter ✓ IP addresses, DNS names, and other fun stuff ✓ The InetAddress class ✓ The Socket class ✓ The ServerSocket class ✓ A simple client/server program ✓ A server program that uses threads T he term network programming can mean a lot of different things. Applets are a form of network programming — as ar e Java Server read more..

  • Page - 500

    Understanding Network Programming 476 Examples of client and server programs abound: ✦ The World Wide Web uses web servers that provide services. The clients in the World Wide Web are web browsers, such as Internet Explorer and Navigator. The protocol used to communicate between web servers and browsers is called HTTP. ✦ E-mail is made possible by a protocol called read more..

  • Page - 501

    Book V Chapter 2 Network Programming Understanding Network Programming 477 Host names, DNS, and URLs A host name is a name that’s associated with a particular IP address. Host names are created according to the DNS naming standard. If it weren’t for DNS, you’d buy books from 205.251.242.54 instead of from www.amazon.com, you’d sell your used furniture at 66.135.205.14 read more..

  • Page - 502

    Getting Information about Internet Hosts 478 To connect to a network server program running on the same computer you’re running telnet on, just use localhost as the host name. Here’s a command that connects to a server program using port 1234: telnet localhost 1234 After telnet fires up, anything you type is sent to the port, and anything received from the port is read more..

  • Page - 503

    Book V Chapter 2 Network Programming Getting Information about Internet Hosts 479 The InetAddress class As you know, an IP address is simply a number that corresponds to a particular host computer on the Internet. The designers of Java could simply have repre- sented IP addresses as long numbers. Instead, they created a powerful class called InetAddress that represents an IP read more..

  • Page - 504

    Getting Information about Internet Hosts 480 Here are a few additional points about this class: ✦ This class doesn’t have a constructor. Instead, the normal way to create it is to call one of its static methods, such as getByName. ✦ The isReachable, getAllByName, and getByName methods throw exceptions. ✦ Several of these methods perform DNS queries to determine their read more..

  • Page - 505

    Book V Chapter 2 Network Programming Getting Information about Internet Hosts 481 Listing 2-1: The HostLookup Application import java.util.Scanner; import java.net.*; ➝2 public class HostLookup { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { System.out.println( "Welcome to the IP lookup read more..

  • Page - 506

    Getting Information about Internet Hosts 482 { System.out.println("Unknown host."); } } while (doAgain()); ➝26 } private static boolean doAgain() { System.out.println(); String s; while (true) { read more..

  • Page - 507

    Book V Chapter 2 Network Programming Creating Network Server Applications 483 Creating Network Server Applications One popular form of network programming is creating client and server programs that work together to perform specific tasks. These programs communicate by sending information over the network. The format of this information is governed by a protocol, which is merely an read more..

  • Page - 508

    Creating Network Server Applications 484 Method Description void Close() Closes the socket. void connect (InetSocketAddress endpoint) Connects the socket to the specified address. InetAddress getInetAddress() Gets the address to which the socket is connected. InputStream getInputStream() Gets an input stream that can be used to receive data sent through this socket. OutputStream read more..

  • Page - 509

    Book V Chapter 2 Network Programming Introducing BART 485 Table 2-3 Constructors and Methods of the ServerSocket Class Constructor Description ServerSocket() Creates a server socket that isn’t bound to any port. ServerSocket(int port) Creates a server socket and binds it to the specified port. Then the server socket lis- tens for connection attempts on this port. Method Description read more..

  • Page - 510

    Introducing BART 486 I call the server the BartServer and the protocol used to communicate with the BartServer BART — short for Blackboard Assignment Retrieval Transaction, because it allows you to randomly retrieve blackboard assign- ments. The protocol itself is simple: 1. When you connect to the BartServer, it displays a greeting line and a line of instructions. 2. If read more..

  • Page - 511

    Book V Chapter 2 Network Programming Introducing BART 487 Listing 2-2: The Bar tQuote Class import java.util.ArrayList; public class BartQuote { ArrayList<String> q = new ArrayList<String>(); ➝5 public BartQuote() ➝7 { q.add("I will not waste chalk."); q.add("I will not skateboard in the halls."); read more..

  • Page - 512

    Introducing BART 488 ➝ 33 The getQuote method returns a sentence randomly selected from the array list. Math.random is used to calculate the random number. (For more information about Math.random, refer to Book II, Chapter 3.) The BartServer program The BartServer program is the program you run on a server computer to provide randomly selected blackboard sentences for read more..

  • Page - 513

    Book V Chapter 2 Network Programming Introducing BART 489 String input = in.nextLine(); ➝39 if (input.equalsIgnoreCase("bye")) break; else if (input.equalsIgnoreCase("get")) { read more..

  • Page - 514

    Introducing BART 490 method to create a string that shows the client’s address. This string is saved to the client variable. ➝ 28 The BartServer program uses a Scanner object to read data sent from the client over the socket. In this line, it uses the socket’s getInputStream method to get a standard input stream for the socket. Next, it uses this input read more..

  • Page - 515

    Book V Chapter 2 Network Programming Introducing BART 491 Serving /127.0.0.1 Serving /127.0.0.1 Closed connection to /127.0.0.1 This program is pretty simple as network-server programs go. Still, it illus- trates the basic techniques of network-server programming. Many server programs consist mostly of a big while loop that gets input from the client, inspects the input to see what read more..

  • Page - 516

    Introducing BART 492 Listing 2-4: The Bar tClient Program import java.net.*; import java.util.*; import java.io.*; public class BartClient { public static void main(String[] args) { int port = 1234; System.out.println("Welcome to the Bart Client\n"); Socket s = getSocket(port); ➝13 try read more..

  • Page - 517

    Book V Chapter 2 Network Programming Introducing BART 493 host = sc.nextLine(); ➝62 try { ip = InetAddress.getByName(host); ➝65 s = new Socket(ip, port); ➝66 return s; ➝67 read more..

  • Page - 518

    Working with BartServer 2.0 494 ➝ 36 Having got what it came for (a blackboard sentence), the client program sends a bye command to the server. The server sends back a rude farewell message, but the client program isn’t inter- ested in it, so it doesn’t even bother to read it. ➝ 37 The connection to the server is closed. ➝ 41 Now that the client read more..

  • Page - 519

    Book V Chapter 2 Network Programming Working with BartServer 2.0 495 Figure 2-2: BartClients galore! Listing 2-5: Bar tServer 2.0 import java.net.*; import java.io.*; import java.util.*; public class BartServer2 { public static void main(String[] args) { int port = 1234; BartQuote bart = new BartQuote(); try read more..

  • Page - 520

    Working with BartServer 2.0 496 catch (Exception e) { System.out.println("System exception!"); } } } class BartThread implements Runnable ➝36 { private Socket s; private BartQuote bart; public BartThread(Socket socket, BartQuote bart) ➝41 { read more..

  • Page - 521

    Book V Chapter 2 Network Programming Working with BartServer 2.0 497 Most of this code is the same as the code in version 1.0, so I just highlight the key changes: ➝ 19 A while loop is used to service connection requests through the accept method of the ServerSocket object. ➝ 25 Each time a new client connects, a thread is created using the BartThread read more..

  • Page - 522

    498 Book V: Programming Techniques read more..

  • Page - 523

    Chapter 3: Using Regular Expressions In This Chapter ✓ Introducing regular expressions ✓ Trying out regular expressions with a helpful program ✓ Creating simple expressions that match patterns of characters ✓ Using regular expression features such as custom classes, quantifiers, and groups ✓ Using regular expressions with the String class ✓ Using the Pattern and Matcher classes read more..

  • Page - 524

    500 Creating a Program for Experimenting with Regular Expressions often obscure. So be warned — the syntax for regular expressions takes a little getting used to. After you get your mind around the basics, however, you’ll find that simple regular expressions aren’t that tough to create and can be very useful. Also be aware that this chapter covers only a portion of all you read more..

  • Page - 525

    Book V Chapter 3 Using Regular Expressions 501 Creating a Program for Experimenting with Regular Expressions System.out.println("Welcome to the " + "Regex Tester\n"); do { do { System.out.print("\nEnter regex: "); r read more..

  • Page - 526

    Performing Basic Character Matching 502 Here’s a sample run of this program. For now, don’t worry about the details of the regular expression string. Just note that it should match any three-letter word that begins with f; ends with r; and has a, i, or o in the middle. Welcome to the Regex Tester Enter regex: f[aio]r Enter string: for Match. Enter string: fir read more..

  • Page - 527

    Book V Chapter 3 Using Regular Expressions 503 Performing Basic Character Matching Matching single characters The simplest regex patterns match a string literal exactly, as in this example: Enter regex: abc Enter string: abc Match. Enter string: abcd Does not match. Here the pattern abc matches the string abc but not abcd. Using predefined character classes A character class read more..

  • Page - 528

    Performing Basic Character Matching 504 The \d class represents a digit and is often used in regex patterns to validate input data. Here’s a simple regex pattern that validates a U.S. Social Security number, which must be entered in the form xxx-xx-xxxx: Enter regex: \d\d\d-\d\d-\d\d\d\d Enter string: 779-54-3994 Match. Enter string: 550-403-004 Does not match. Here the regex read more..

  • Page - 529

    Book V Chapter 3 Using Regular Expressions Performing Basic Character Matching 505 Here the pattern specifies that the string can be two groups of any three characters separated by one white-space character. In the first string that’s entered, the groups are separated by a space; in the second group, they’re separated by a tab. The \s class also has a counterpart: \S. read more..

  • Page - 530

    Performing Basic Character Matching 506 Match. Enter string: bot Match. Enter string: but Match. Enter string: bmt Does not match. Here the pattern specifies that the string must start with the letter b, followed by a class that can include a, e, i, o, or u, followed by t. In other words, it accepts three-letter words that begin with b, end with t, and have a vowel in read more..

  • Page - 531

    Book V Chapter 3 Using Regular Expressions Performing Basic Character Matching 507 You can also use more than one range in a class, like this: Enter regex: [a-zA-Z][0-5] Enter string: r2 Match. Enter string: R2 Match. Here the first character can be lowercase a–z or uppercase A–Z. You can use ranges to build a class that accepts only characters that appear in real read more..

  • Page - 532

    Performing Basic Character Matching 508 Table 3-2 Quantifiers Regex Matches the Preceding Element ? Zero times or one time * Zero or more times + One or more times {n} Exactly n times {n,} At least n times {n,m} At least n times but no more than m times To use a quantifier, you code it immediately after the element you want it to apply to. Here’s a version read more..

  • Page - 533

    Book V Chapter 3 Using Regular Expressions Performing Basic Character Matching 509 Using escapes In regular expressions, certain characters have special meaning. What if you want to search for one of those special characters? In that case, you escape the character by preceding it with a backslash. Here’s an example: Enter regex: \(\d{3}\) \d{3}-\d{4} Enter string: (559) 555-1234 read more..

  • Page - 534

    Performing Basic Character Matching 510 Here’s an example that finds U.S. phone numbers that can have an optional area code: Enter regex: (\(\d{3}\)\s?)?\d{3}-\d{4} Enter string: 555-1234 Match. Enter string: (559) 555-1234 Match. Enter string: (559)555-1239 Match. This regex pattern is a little complicated, but if you examine it element by element, you should be able to figure it out. read more..

  • Page - 535

    Book V Chapter 3 Using Regular Expressions Using Regular Expressions in Java Programs 511 Using the pipe symbol The vertical bar ( |) symbol defines an or operation, which lets you create patterns that accept any of two or more variations. Here’s an improvement of the pattern for validating droid names: Enter regex: (\w\d-\w\d)|(\w-\d\w\w) Enter string: r2-d2 Match. Enter string: read more..

  • Page - 536

    Using Regular Expressions in Java Programs 512 Understanding the String problem Before getting into the classes for working with regular expressions, I want to clue you in about a problem that Java has in dealing with strings that con- tain regular expressions. As you’ve seen throughout this chapter, regex pat- terns rely on the backslash character to mark different elements of a read more..

  • Page - 537

    Book V Chapter 3 Using Regular Expressions Using Regular Expressions in Java Programs 513 Here’s a static method that validates droid names: private static boolean validDroidName(String droid) { String regex = "(\\w\\d-\\w\\d)|(\\w-\\d\\w\\w)"; return droid.matches(regex); } Here the name of the droid is passed via a parameter, and the method returns a boolean that read more..

  • Page - 538

    Using Regular Expressions in Java Programs 514 First, you use the compile method to create a Pattern object. ( Pattern is one of those weird classes that doesn’t have constructors. Instead, it relies on the static compile method to create instances.) Because the compile method throws PatternSyntaxException, you must use a try/catch statement to catch this exception when read more..

  • Page - 539

    Chapter 4: Using Recursion In This Chapter ✓ Introducing recursion ✓ Calculating factors with recursion ✓ Listing directories with recursion ✓ Sorting with recursion R ecursion is a basic programming technique in which a method calls itself to solve some problem. A method that uses this technique is called recursive. Many programming problems can be solved only by read more..

  • Page - 540

    Calculating the Classic Factorial Example 516 f = f * i; return f; } This method uses a for loop to count from 1 to the number, keeping track of the product as it goes. Here’s a snippet of code that calls this method and displays the result: int n = 5; long fact; fact = factorial(n); System.out.println("The factorial of "+ n + " is " read more..

  • Page - 541

    Book V Chapter 4 Using Recursion Displaying Directories 517 This method returns exactly the same result as the version in the preceding section, but it uses recursion to calculate the factorial. One way to visualize how recursion works is to imagine that you have five friends: Jordan, Jeremy, Jacob, Justin, and Bob. Your friends aren’t very smart, but they’re very much alike. read more..

  • Page - 542

    Displaying Directories 518 Listing 4-1, at the end of this section, shows a program that uses a recursive method to list all the directories that are found starting from a given path. I use indentation to show the directory structure. Here’s the console output for the directories I used to organize the docu- ments for this book: Welcome to the Directory Lister Enter a path: C:\Java read more..

  • Page - 543

    Book V Chapter 4 Using Recursion Displaying Directories 519 ✦ The isDirectory method returns a boolean that indicates whether the current File object is a directory. If this method returns false, you can assume that the File object is a file. ✦ The getName method returns the name of the file. Listing 4-1: The Directory Listing Application import java.io.File; ➝1 read more..

  • Page - 544

    Displaying Directories 520 private static boolean askAgain() { System.out.print("Another? (Y or N) "); String reply = sc.nextLine(); if (reply.equalsIgnoreCase("Y")) return true; return false; } } The following paragraphs point out the highlights of how this program works: read more..

  • Page - 545

    Book V Chapter 4 Using Recursion Writing Your Own Sorting Routine 521 ➝ 41 Next, the listDirectories method is called recursively to list the contents of the f directory. Two spaces are added to the inden- tation string, however, so that any directories in the f directory are indented two spaces to the right of the current directory. If you’re having trouble read more..

  • Page - 546

    Writing Your Own Sorting Routine 522 doctoral degrees on more-sophisticated ways to pick a pivot point that results in faster sorting. I like to stick with using the first element in the array. 2. Rearrange the values in the array so that all the values that are less than the pivot point are on the left side of the array and all the values that are greater than read more..

  • Page - 547

    Book V Chapter 4 Using Recursion Writing Your Own Sorting Routine 523 Using the sort method The actual code that drives a Quicksort routine is surprisingly simple: public static void sort(int low, int high) { if (low >= high) return; int p = partition(low, high); sort (low, p); sort (p+1, high); } This method sorts the portion read more..

  • Page - 548

    Writing Your Own Sorting Routine 524 forward until it encounters a value that’s greater than the pivot value. Then j starts at the opposite end of the array and moves backward until it finds a value that’s less than the pivot point. At that point, the partition method has a value that’s greater than the pivot point on the left side of the array and a value read more..

  • Page - 549

    Book V Chapter 4 Using Recursion Writing Your Own Sorting Routine 525 The first for loop increments the i index variable until it finds a value that’s greater than the pivot point. This for loop finds the first value that might need to be moved to the other side of the array. Next, the second for loop decrements the j index variable until it finds a value read more..

  • Page - 550

    Writing Your Own Sorting Routine 526 Listing 4-2: A Sor ting Program public class QuickSortApp { public static void main(String[] args) { int LEN = 100; int[] unsorted = new int[LEN]; for (int i = 0; i<LEN; i++) ➝7 unsorted[i] = (int)(Math.random() * 100) + 1; read more..

  • Page - 551

    Book V Chapter 4 Using Recursion Writing Your Own Sorting Routine 527 int i = low - 1; int j = high + 1; while (i < j) { for (i++; a[i] < pivot; i++); for (j--; a[j] > pivot; j--); if (i < j) swap(i, j); } read more..

  • Page - 552

    Writing Your Own Sorting Routine 528 ➝ 47 The partition method is explained in detail in the preceding section. ➝ 64 The swap method simply exchanges the two indicated values. Remember the cool XOR technique for exchanging two integer values without the need for a temporary variable? You can improve the performance of your sort ever so slightly by replacing read more..

  • Page - 553

    Chapter 5: Working with Dates and T imes In This Chapter ✓ Understanding human and computer dates and times ✓ Using java.time classes to represent dates and times ✓ Comparing dates and times ✓ Performing calculations with dates and times ✓ Formatting dates and times D oes anybody really know what time it is? Does anybody really care about time? So mused Robert Lamm of read more..

  • Page - 554

    Pondering How Time is Represented 530 keeping track of time. Humans measure time using a system of progressively longer units, starting with seconds and increasing to minutes, hours, days, weeks, months, years, decades, and centuries. Our human time units are intuitively familiar to us, but their precise defini- tions are more complicated than you might guess. All kinds of factors read more..

  • Page - 555

    Picking the Right Date and T ime Class for Your Application 531 Book V Chapter 5 W orking with Dates and T imes people, one in Los Angeles, the other in New York. Obviously, the time that you agree upon for the call must take into account the time zone of each participant. Thus you might agree to make the call at 1 p.m. local time for the West Coast participant and read more..

  • Page - 556

    Using the now Method to Create a Date-Time Object 532 Class What It Represents YearMonth A year and month, such as December, 2015. No day, time, or time zone values are associated with the year and month. Year A year, such as 2038. No month, day, time, or time zone values are associated with the year. Instant A single point of time, represented internally as the number read more..

  • Page - 557

    Using the parse Method to Create a Date-Time Object 533 Book V Chapter 5 W orking with Dates and T imes System.out.println("\nMonthDay: " + MonthDay.now().toString()); System.out.println("\nYearMonth: " + YearMonth.now().toString()); System.out.println("\nInstant: " read more..

  • Page - 558

    Using the of Method to Create a Date-Time Object 534 If the string is not in the correct format, the parse method throws a DateTimeParseException. Whenever you use the parse method, you should enclose it in a try block and catch this exception, as in this example: LocalDateTime dt; try { dt = LocalDateTime.parse("2014-12-15T03:45PM"); } catch (DateTimeParseException read more..

  • Page - 559

    Using the of Method to Create a Date-Time Object 535 Book V Chapter 5 W orking with Dates and T imes Class Method LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute) of(int year, int month, int dayOfMonth, int hour, int minute, int second) of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) of(int year, Month month, read more..

  • Page - 560

    Using the of Method to Create a Date-Time Object 536 Using the Month enumeration Several of the methods listed in Table 5-2 let you specify the month as a Month object. Month is an enumeration that represents the twelve months of the year, as follows: Month.JANUARY Month.MAY Month.SEPTEMBER Month.FEBRUARY Month.JUNE Month.OCTOBER Month.MARCH Month.JULY Month.NOVEMBER Month.APRIL Month.AUGUST read more..

  • Page - 561

    Looking Closer at the LocalDate Class 537 Book V Chapter 5 W orking with Dates and T imes zdate = ZonedDateTime.of(2014, 12, 15, 0, 0, 0, 0, ZoneId.of("America/Los_Angeles")); Using the ZoneOffset class The of method OffsetTime and OffsetDateTime classes use an additional class named ZoneOffset to indicate the offset from UTC. You can create a ZoneOffset by read more..

  • Page - 562

    Looking Closer at the LocalDate Class 538 Table 5-3 shows the most commonly used methods of the LocalDate class. For your convenience, this table includes the methods used to create LocalDate objects, even though those methods have already been covered earlier in this chapter. Table 5-3 Methods of the LocalDate Class Method Explanation Methods that create a LocalDate object read more..

  • Page - 563

    Extracting Information About a Date 539 Book V Chapter 5 W orking with Dates and T imes Method Explanation Methods that perform date calculations LocalDate plusDays(long days) Returns a copy of the LocalDate with the specified number of days added. LocalDate plusNMonths(long days) Returns a copy of the LocalDate with the specified number of months added. LocalDate read more..

  • Page - 564

    Comparing Dates 540 If you need to know how many days into the year a particular date is, you can use this code: LocalDate date = LocalDate.parse("2016-04-09"); System.out.println(date.getDayOfYear()); This example will print the number 100, as April 9 is the 100th day of 2016. The getDayOfWeek method returns a value of type DayOfWeek, which is an enumeration with the read more..

  • Page - 565

    Calculating with Dates 541 Book V Chapter 5 W orking with Dates and T imes Similarly, you must use either the isBefore or the isAfter method to determine whether one date falls before or after another date. Note that you can use built-in operators with methods that return integer results. Thus, the following code will work just as you would expect: if read more..

  • Page - 566

    Calculating with Dates 542 Some date calculations can be a bit more complex. For example, consider a business that prepares invoices on the 15th of each month. The following snippet of code displays the number of days from the current date until the next invoicing date: LocalDate today = LocalDate.now(); LocalDate invDate = LocalDate.of(today.getYear(), today.getMonthValue(), 15); read more..

  • Page - 567

    Formatting Dates 543 Book V Chapter 5 W orking with Dates and T imes Note that ChronoUnit is in the java.time.temporal package, so be sure to include the following statement at the top of any program that uses ChronoUnit: import java.time.temporal.*; Formatting Dates If you use the toString() method to convert a LocalDate to a string, you get a string such as 2014-10-31. read more..

  • Page - 568

    Formatting Dates 544 Here’s a simple program that prints the current date in several different formats: import java.util.*; import java.time.*; import java.time.format.*; public class FormatDateTime { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); printDate(now, "YYYY-MM-dd"); read more..

  • Page - 569

    Looking at a Fun Birthday Calculator 545 Book V Chapter 5 W orking with Dates and T imes Looking at a Fun Birthday Calculator Now that you’ve seen the techniques for working with Date-Time objects, it’s time to look at a complete programming example. Listing 5-1 presents a program that prompts the user to enter his or her birthday and then prints a variety of interesting read more..

  • Page - 570

    Looking at a Fun Birthday Calculator 546 System.out.println("Today is " ➝21 + LocalDate.now().format(fullFormat) + "."); System.out.println(); System.out.print("Please enter your birthdate " + "(yyyy-mm-dd): "); read more..

  • Page - 571

    Looking at a Fun Birthday Calculator 547 Book V Chapter 5 W orking with Dates and T imes if (reply.equalsIgnoreCase("Y")) { return true; } return false; } } The following paragraphs explain the most important lines in this program: ➝ 2 The program uses classes read more..

  • Page - 572

    548 Book V: Programming Techniques read more..

  • Page - 573

    Chapter 6: Using BigDecimals In This Chapter ✓ Understanding the problem with double arithmetic in Java ✓ Solving the double problem with the BigDecimal class ✓ Creating objects with BigDecimal ✓ Doing arithmetic with BigDecimal objects ✓ Discovering other things to do with BigDecimal Y ou would think that arithmetic would be one area in which any pro- gramming language read more..

  • Page - 574

    Seeing Why Java Can’t Add 550 double tenPennies = 0; for (int i = 0; i < 10; i++) // add up 10 pennies tenPennies += penny; System.out.println("A dime is " + dime); System.out.println("Ten pennies is " + tenPennies); if read more..

  • Page - 575

    Book V Chapter 6 Using BigDecimals Seeing Why Java Can’t Add 551 Here, Java’s default behavior is to format the number so that the inaccuracy is hidden. Thus, the output from this program is simply 0.1. You can see the inaccuracy, however, if you use the NumberFormat class to format the number with ten significant digits, like this: float val = 0.1f; NumberFormat nf = read more..

  • Page - 576

    Seeing Why Java Can’t Add 552 All is well with the first two entries, but the third one has an embarrassing arithmetic error: 70 plus 3 is not 74. Listing 6-2: Bad Tax! import java.text.*; import java.util.*; public class BadTax { static Scanner sc = new Scanner(System.in); static NumberFormat cf = NumberFormat.getCurrencyInstance(); read more..

  • Page - 577

    Book V Chapter 6 Using BigDecimals Creating BigDecimal Objects 553 BigDecimal to the Rescue! If you can’t use double for decimal values when you need accurate results, what can you use? Fortunately, the Java designers have provided a class that solves the problem for you. The BigDecimal class accurately represents a decimal number and provides methods you can use to perform read more..

  • Page - 578

    Creating BigDecimal Objects 554 Although you can create BigDecimal values from a double or float value, I recommend against it. The whole point of using BigDecimal is to avoid the accuracy errors that are inherent with double and float values, and the only way to do that is to avoid using double and float altogether. As the old computer saying reminds you, read more..

  • Page - 579

    Book V Chapter 6 Using BigDecimals Doing BigDecimal Arithmetic 555 If the initial value is an integer, you can safely pass it to the constructor. Rem- ember that integers don’t have the same accuracy problems that doubles and floats do. Also, as you see later in the chapter, you can convert a BigDecimal to a double solely for the purpose of using the read more..

  • Page - 580

    Doing BigDecimal Arithmetic 556 Method Explanation BigDecimal divide(BigDecimal val) Divides this BigDecimal by the specified BigDecimal and returns the result. The method may throw ArithmeticException. BigDecimal[] divideAndRemainder (BigDecimal val) Divides this BigDecimal by the specified BigDecimal. The result and the remainder are returned as a two-element BigDecimal array. read more..

  • Page - 581

    Book V Chapter 6 Using BigDecimals Doing BigDecimal Arithmetic 557 After these statements execute, the value of c is 3. You can also use the remainder method to get the remainder from a division: c = a.remainder(b); Here the value of c is 2.5. A common mistake among new users of the BigDecimal class is forgetting to assign the result of an arithmetic operation. You read more..

  • Page - 582

    Rounding BigDecimal Values 558 Rounding BigDecimal Values Multiplication and division introduce the need for rounding. Suppose that your sales tax rate is 5 percent. The tax calculation on a sale of $32.55 would be $1.6275, but not too many people know how to make change for ¾ of a penny. As a result, this sales tax calculation should be rounded up to $1.63. The read more..

  • Page - 583

    Book V Chapter 6 Using BigDecimals Rounding BigDecimal Values 559 int scale0 = num0.scale(); int scale1 = num1.scale(); int scale2 = num2.scale(); int scale3 = num3.scale(); System.out.println("Scale of " + num0 + " is " + scale0); System.out.println("Scale of " + num1 + " is " + scale1); System.out.println("Scale of " + num2 + " is " + scale2); read more..

  • Page - 584

    Rounding BigDecimal Values 560 Reducing the scale with this version of the setScale method always runs the risk of cutting important digits. If value1 had been set to 1.6125, the last two digits would be cut off. The BigDecimal class doesn’t like to let that happen, so it throws an ArithmeticException in that case. You can use the other version of setScale to read more..

  • Page - 585

    Book V Chapter 6 Using BigDecimals Comparing BigDecimal Values 561 Getting back to the sales tax calculation, here’s how you can avoid charging someone $1.6275 on a $32.55 purchase: salesTax = subTotal.multiply(taxRate); salesTax = salesTax.setScale(2, RoundingMode.HALF_UP); invoiceTotal = subTotal.add(salesTax); First, you multiply the subtotal by the tax rate. Assuming that the scale of both read more..

  • Page - 586

    Comparing BigDecimal Values 562 Table 6-5 Comparison Methods of the BigDecimal Class Method Explanation int compareTo(BigDecimal val) Compares this BigDecimal with the specified BigDecimal. Returns –1, 0, or +1 if this BigDecimal is less than, equal to, or greater than the specified BigDecimal. boolean equals(Object val) Returns a boolean that indicates whether this BigDecimal read more..

  • Page - 587

    Book V Chapter 6 Using BigDecimals Converting BigDecimals to Strings 563 Here’s a list of how these expressions match up: Comparison You Want to Make Equivalent compareTo Expression value 1 == value2 value1.compareTo(value2) == 0 value 1 != value2 value1.compareTo(value2) != 0 value 1 > value2 value1.compareTo(value2) > 0 value 1 >= value2 value1.compareTo(value2) >= 0 value 1 < value2 read more..

  • Page - 588

    Revisiting Sales Tax 564 Here’s a snippet of code that converts a BigDecimal object named salesTax to a double and uses it with the NumberFormat class: NumberFormat cf = NumberFormat.getCurrencyInstance(); double taxD = salesTax.doubleValue(); System.out.println(cf.format(taxD)); You can also use the toString method to format a BigDecimal as a string, but this method doesn’t read more..

  • Page - 589

    Book V Chapter 6 Using BigDecimals Revisiting Sales Tax 565 Listing 6-3: Good Tax! import java.text.*; import java.math.*; ➝2 import java.util.*; public class GoodTax { static Scanner sc = new Scanner(System.in); static NumberFormat cf = NumberFormat.getCurrencyInstance(); public static void main (String[] args) { BigDecimal read more..

  • Page - 590

    Revisiting Sales Tax 566 The following paragraphs describe some of the high points of this program: ➝ 2 The BigDecimal class is in the java.math package, so this import statement is required to use it. ➝ 12 This line declares three of the BigDecimal variables used by the program. ➝ 13 This line declares the fourth BigDecimal variable and initializes read more..

  • Page - 591

    You can find an interesting programming challenge that requires use of many of the programming techniques covered in this minibook at www.dummies.com/ extras/javaaio. In this challenge, you enhance the Tic-Tac-Toe program you’ve created for several of the previous minibooks by adding a graphical user interface. Book VI Swing read more..

  • Page - 592

    Contents at a Glance Contents at a Glance Chapter 1: Swinging into Swing ...............................569 Understanding Some Important Swing Concepts .......................................................569 I’ve Been Framed! ...........................................................................................................571 Using the JPanel Class read more..

  • Page - 593

    Chapter 1: Swinging into Swing In This Chapter ✓ Examining some basic Swing concepts ✓ Fussing with frames ✓ Creating a simple Swing program ✓ Putting panels in your frames ✓ Looking at labels ✓ Beginning with buttons ✓ Leaping into layout S o far in this book, all the programs have been console-based, like some- thing right out of the 1980s. Console-based Java read more..

  • Page - 594

    Understanding Some Important Swing Concepts 570 Figure 1-1: A typical Swing window. Viewing the Swing class hierarchy The Swing API provides many classes for creating various types of user- interface elements. In this chapter, I look at three of those classes: JFrame, JPanel, and JLabel. These three classes are part of a larger collection of classes that are related through read more..

  • Page - 595

    Book VI Chapter 1 Swinging into Swing Understanding Some Important Swing Concepts 571 The following paragraphs briefly describe the classes shown in this figure: ✦ Object: All classes ultimately derive from Object, so it’s no surprise that this class is at the top of the tree. ✦ Component: The Component class represents an object that has a visual representation read more..

  • Page - 596

    I’ve Been Framed! 572 I’ve Been Framed! The top-level component of most Swing-based applications is called a frame and is defined by the JFrame class. By itself, a frame doesn’t do much, but to do anything else in Swing, you must first create a frame. Figure 1-3 shows a frame that does nothing but display the message Hello, World! in its title bar. read more..

  • Page - 597

    Book VI Chapter 1 Swinging into Swing I’ve Been Framed! 573 void setLayout (LayoutManager layout) Sets the layout manager used to con- trol how components are arranged when the frame is displayed. The default is the BorderLayout manager. void setLocation (int x, int y) Sets the x and y positions of the frame onscreen. The top-left corner of the screen is 0, read more..

  • Page - 598

    I’ve Been Framed! 574 The purpose of this seemingly pointless little program is to illustrate one solution to the first problem you encounter when you work with Swing: The main method is a static method, but Swing frames are objects, so you have to figure out how to get your program out of a static context. This program does that by creating the application as a read more..

  • Page - 599

    Book VI Chapter 1 Swinging into Swing I’ve Been Framed! 575 ➝ 10 When an instance of the HelloFrame class is created in line 7, the constructor that starts on this line is executed. The main job of the constructor for a frame class is to set the options for the frame and create any GUI components that are displayed in the frame. ➝ 12 The first read more..

  • Page - 600

    Using the JPanel Class 576 If you want to center the frame onscreen, call the setLocationRelativeTo method and pass null as the parameter, like this: frame.setLocationRelativeTo(null); This method is designed to let you position a frame relative to some other component that’s already displayed. But if you pass null as the parameter, the method centers the frame onscreen. If read more..

  • Page - 601

    Book VI Chapter 1 Swinging into Swing Using the JPanel Class 577 Panels are defined by the JPanel class. Like the JFrame class, the JPanel class has a bevy of methods. Table 1-2 lists the most commonly used con- structors and methods for the JPanel class. Table 1-2 Interesting JPanel Constructors and Methods Constructor Description JPanel() Creates a new panel. JPanel(boolean read more..

  • Page - 602

    Using Labels 578 { this.setSize(200,100); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("Hello, World!"); JPanel panel = new JPanel(); // code to add components to the panel goes here this.setVisible(true); } Another common technique involves creating a separate class for the panel. This class should extend JPanel. read more..

  • Page - 603

    Book VI Chapter 1 Swinging into Swing Using Labels 579 To create a label, you use the JLabel class. Table 1-3 shows its most com- monly used constructors and methods. Table 1-3 Tolerable JLabel Constructors and Methods Constructor Description JLabel() Creates a new label with no initial text. JLabel(String text) Creates a new label with the specified text. Method Description String read more..

  • Page - 604

    Creating Buttons 580 Figure 1-4 shows what this frame looks like when the program is run. Figure 1-4: A frame with a panel, which has a label. Creating Buttons Next to labels, the Swing component you use most is the JButton compo- nent, which creates a button that the user can click. Figure 1-5 shows a frame with a single button. In Book VI, Chapter read more..

  • Page - 605

    Book VI Chapter 1 Swinging into Swing Creating Buttons 581 String getText() Returns the text displayed by the button. void setBorderPainted (boolean value) Shows or hides the button’s border. The default setting is true (the border is shown). void setContentAreaFilled (boolean value) Specifies whether the button’s back- ground should be filled or left empty. The default setting read more..

  • Page - 606

    Controlling the Layout of Components 582 Most of the other methods listed in Table 1-4 simply affect how a button looks. To disable a button so that the user can’t click it, call setEnabled(false). To remove the dark border from the edges of a button, call setBorderPainted (false). To remove the background from a button so all that’s displayed is the text, call read more..

  • Page - 607

    Chapter 2: Handling Events In This Chapter ✓ Understanding important event concepts ✓ Working with event-handling classes and interfaces ✓ Responding to button clicks ✓ Using inner classes for event handling ✓ Providing an Exit button ✓ Dealing with the Close button ✓ Taking another look at a button-click program I n Book VI, Chapter 1, I show you how to create Swing frames that read more..

  • Page - 608

    Examining Events 584 Java provides several types of event objects, represented by various classes that inherit AWTEvent. Table 2-1 lists the most commonly used event classes. In addition, this table lists the listener interface for each event object. The listener interface is used to create an object that can listen for the event and handle it when it’s generated. Table 2-1 Commonly Used read more..

  • Page - 609

    Book VI Chapter 2 Handling Events Examining Events 585 Most of these event classes are contained in the package java.awt. The only thing that’s not in java.awt is DocumentEvent (which happens to be an interface, not a class, in the package javax.swing.event). Strictly speaking, event handling is provided by AWT, not by Swing. The events listed in Table 2-1 can be divided read more..

  • Page - 610

    Examining Events 586 Listener Interface Method Description WindowListener void windowActivated (WindowEvent e) Called when the window is activated. void windowClosed (WindowEvent e) Called when the window has been closed. void windowClosing (WindowEvent e) Called when the user attempts to close the window. void windowDeactivated (WindowEvent e) Called when the window is read more..

  • Page - 611

    Book VI Chapter 2 Handling Events Handling Events 587 Listener Interface Method Description void mouseExited (MouseEvent e) Called when the mouse cursor leaves a component. void mousePressed (MouseEvent e) Called when the user presses the mouse button. void mouseReleased (MouseEvent e) Called when the user releases the mouse button. FocusListener void focusGained (FocusEvent e) read more..

  • Page - 612

    Handling Events 588 Note that this code appears in the constructor of the frame class, so in the last line, this refers to the frame. 2. Create a class that implements the listener interface for the event you want to handle. To handle action events, for example, you should create a class that implements the ActionListener interface. The easiest way is to read more..

  • Page - 613

    Book VI Chapter 2 Handling Events Creating a ClickMe Program 589 Creating a ClickMe Program To see how all these elements work together in a complete program, Figure 2-1 shows three incarnations of a frame created by a program called ClickMe. This program displays a frame with a single button that initially says Click Me! When the user clicks the button, the button’s read more..

  • Page - 614

    Creating a ClickMe Program 590 this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); this.setTitle("I'm Listening"); JPanel panel1 = new JPanel(); button1 = new JButton("Click Me!"); ➝21 button1.addActionListener(this); ➝22 panel1.add(button1); read more..

  • Page - 615

    Book VI Chapter 2 Handling Events Using Inner Classes to Listen for Events 591 ➝ 22 This line adds the current object as an action listener for the button1 button. ➝ 29 A field named clickCount is used to keep track of how many times the button has been clicked. This field is initialized to zero when the object is created. ➝ 31 The actionPerformed read more..

  • Page - 616

    Using Inner Classes to Listen for Events 592 public ClickMeInner() { this.setSize(300,150); this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); this.setTitle("I'm Listening"); ClickListener cl = new ClickListener(); ➝20 JPanel panel1 = new JPanel(); button1 = new JButton("Click read more..

  • Page - 617

    Book VI Chapter 2 Handling Events Using Lambda Expressions to Handle Events 593 ➝ 24 This statement adds c1 as an action listener for the button. Note that because this frame has only one button, I could just as easily have omitted line 20 and coded line 24 like this: button1.addActionListener(new ClickListener()); Because most real-world applications have more than read more..

  • Page - 618

    Using Lambda Expressions to Handle Events 594 } private JButton button1; public ClickMeLambda() { this.setSize(300,150); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("I'm Listening"); JPanel panel1 = new JPanel(); button1 = new JButton("Click Me!"); read more..

  • Page - 619

    Book VI Chapter 2 Handling Events Adding an Exit Button 595 button1.setText("I've been clicked!"); else button1.setText("I've been clicked " + clickCount + " times!"); } ); However, this type of coding can quickly become unwieldy. So, as a read more..

  • Page - 620

    Catching the WindowClosing Event 596 exitButton.addActionListener(e -> exitButtonClick() ); panel1.add(exitButton); Finally, you add the exitButtonClick() method: public void exitButtonClick() { if (clickCount > 0) System.exit(0); else { JOptionPane.showMessageDialog( ClickMe3.this, "You must read more..

  • Page - 621

    Book VI Chapter 2 Handling Events Catching the WindowClosing Event 597 setDefaultCloseOperation from EXIT_ON_CLOSE to DO_NOTHING_ON_ CLOSE, like this: this.setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE); This way, the default action of the JFrame class is to ignore the Close button. Then you can install a window listener to handle the Close button any way you want. Next, you read more..

  • Page - 622

    Revisiting the ClickMe Program 598 public void windowClosing(WindowEvent e) { exitButton.doClick(); } } Table 2-3 Adapter Classes for Event Listeners Listener Interface Adapter Class WindowListener WindowAdapter KeyListener KeyAdapter MouseListener MouseAdapter FocusListener FocusAdapter That saves some code. You can save even more code by skipping the Closer read more..

  • Page - 623

    Book VI Chapter 2 Handling Events Revisiting the ClickMe Program 599 work together. This version of the program adds an Exit button but doesn’t allow the user to quit until he or she has clicked the Click Me! button at least once, and it treats the Close button as though the user had clicked Exit. Listing 2-4: The ClickMe Application with an Exit But ton import read more..

  • Page - 624

    Revisiting the ClickMe Program 600 { clickCount++; if (clickCount == 1) button1.setText("I've been clicked!"); else button1.setText("I've been clicked " + clickCount + " times!"); } public void read more..

  • Page - 625

    Chapter 3: Getting Input from the User In This Chapter ✓ Working with text fields and areas ✓ Creating check boxes ✓ Setting radio buttons ✓ Defining borders ✓ Playing with sliders ✓ Using some of these components in a sample program I n the first two chapters of Book VI, I show you how to use two basic Swing user-interface components — labels and read more..

  • Page - 626

    Using Text Fields 602 Table 3-1 Handy JTextField Constructors and Methods Constructor Description JTextField() Creates a new text field. JTextField(int cols) Creates a new text field with the specified width. JTextField(String text, int cols) Creates a new text field with the specified width and initial text value. Method Description String getText() Gets the text value entered read more..

  • Page - 627

    Book VI Chapter 3 Getting Input from the User Using Text Fields 603 The following paragraphs describe a few additional details you need to know about using text fields: ✦ When you use a text field, you usually also want to place a label nearby to tell the user what type of text to enter in the field. ✦ You can create a read-only text field by calling read more..

  • Page - 628

    Using Text Fields 604 The code for this program is shown in Listing 3-1. Listing 3-1: Saying “Good Morning” with a Text Field import javax.swing.*; import java.awt.event.*; public class Namer extends JFrame ➝4 { public static void main(String [] args) { new Namer(); } private JButton buttonOK; private JTextField textName; ➝13 read more..

  • Page - 629

    Book VI Chapter 3 Getting Input from the User Using Text Fields 605 else { JOptionPane.showMessageDialog( Namer.this, "Good morning " + name, "Salutations", JOptionPane.INFORMATION_MESSAGE); } read more..

  • Page - 630

    Using Text Fields 606 can’t be converted. As a result, you need to call the parseInt method in a try/catch block to catch this exception. Table 3-2 Methods That Convert Strings to Numbers Wrapper Class parse Method Integer parseInt(String) Short parseShort(String) Long parseLong(String) Byte parseByte(String) Float parseFloat(String) Double parseDouble(String) If your program uses more than read more..

  • Page - 631

    Book VI Chapter 3 Getting Input from the User Using Text Fields 607 { JOptionPane.showMessageDialog(Number.this, "You entered " + Integer.parseInt(textCount.getText()), "Your Number", JOptionPane.INFORMATION_MESSAGE); } read more..

  • Page - 632

    Using Text Areas 608 result.isValid = true; return result; } catch (NumberFormatException e) { JOptionPane.showMessageDialog(f, "Entry Error", msg, JOptionPane.ERROR_MESSAGE); read more..

  • Page - 633

    Book VI Chapter 3 Getting Input from the User Using Text Areas 609 To create a text area like the one shown in Figure 3-2, you must actually use two classes. First, you use the JTextArea class to create the text area. Unfortunately, text areas by themselves don’t have scroll bars, so you have to add the text area to a second component called a scroll pane, read more..

  • Page - 634

    Using Text Areas 610 Method Description void append(String text) Adds the specified text to the end of the text area’s text value. int getLineCount() Gets the number of lines currently in the text value. String getText() Gets the text value entered in the field. void insert(String str, int pos) Inserts the specified text at the specified position. void requestFocus() Asks for read more..

  • Page - 635

    Book VI Chapter 3 Getting Input from the User Using Text Areas 611 Notice that in addition to the getText method, the JTextArea class has methods that let you add text to the end of the text area’s current value ( append), insert text into the middle of the value ( insert), and replace text ( replace). You use these methods to edit the value of the text area. read more..

  • Page - 636

    Using Check Boxes 612 The usual way to create a scroll pane is to use the second constructor. You use the first parameter of this constructor to specify the component to which you want to add scroll bars. To add scroll bars to a textNovel text area, for example, you specify textNovel as the first parameter. The second parameter tells the scroll pane whether to read more..

  • Page - 637

    Book VI Chapter 3 Getting Input from the User Using Check Boxes 613 Table 3-5 Notable JCheckBox Constructors and Methods Constructor Description JCheckBox() Creates a new check box that is initially unchecked. JCheckBox(String text) Creates a new check box that displays the specified text. JCheckBox(String text, boolean selected) Creates a new check box with the specified text. The read more..

  • Page - 638

    Using Check Boxes 614 anchovies = new JCheckBox("Anchovies"); panel1.add(anchovies); Notice that I didn’t specify the initial state of these check boxes in the constructor. As a result, they’re initially unchecked. If you want to create a check box that is initially checked, call the constructor like this: Pepperoni = new JCheckBox("Pepperoni", true); In an event read more..

  • Page - 639

    Book VI Chapter 3 Getting Input from the User Using Radio Buttons 615 ✦ Item event: Generated whenever the state of the check box is changed, whether as a result of being clicked by the user or because the program called the setSelected method. Suppose that your restaurant has anchovies on the menu, but you refuse to actually make pizzas with anchovies on them. read more..

  • Page - 640

    Using Radio Buttons 616 Table 3-6 Various JRadioButton Constructors and Methods Constructor Description JRadioButton() Creates a new radio button with no text. JRadioButton(String text) Creates a new radio button with the specified text. Method Description void addActionListener (ActionListener listener) Adds an ActionListener to listen for action events. void addItemListener (ItemListener read more..

  • Page - 641

    Book VI Chapter 3 Getting Input from the User Using Borders 617 Then call the add method of the ButtonGroup to add each radio button to the group: group1.add(small); group1.add(medium); group1.add(large); Button groups have nothing to do with how radio buttons appear in the frame. The buttons can appear anywhere on the frame, even in different panels. (I show you how to read more..

  • Page - 642

    Using Borders 618 Figure 3-5: A frame with borders. You can apply a border to any object that inherits JComponent, but the usual technique is to apply the border to a panel and add to that panel any components you want to appear within the border. To create a border, call one of the static methods listed in Table 3-7. Each of these methods creates a read more..

  • Page - 643

    Book VI Chapter 3 Getting Input from the User Using Borders 619 The BorderFactory class is in the javax.swing package, but the Border interface that defines the resulting border objects is in javax.swing.border. Thus you need to include this import statement at the beginning of the class (in addition to importing javax.swing.*) if you plan to use borders: import read more..

  • Page - 644

    Using Sliders 620 Using Sliders As Figure 3-6 shows, a slider is a component that lets a user pick a value from a set range (say, from 0 to 50) by moving a knob. A slider is a convenient way to get numeric input from the user when the input falls within a set range of values. Figure 3-6: A frame with a slider. To create a slider control, you use read more..

  • Page - 645

    Book VI Chapter 3 Getting Input from the User Using Sliders 621 void setInvert(boolean value) If true, inverts the slider’s direction so that the maximum value is on the left and the minimum value is on the right. void setMajorTickSpacing (int value) Sets the interval for major tick marks. The marks aren’t shown unless setPaintTicks(true) is called. void read more..

  • Page - 646

    Using Sliders 622 To set a different initial value, use this constructor: slider = new JSlider(0, 0, 50); Here the slider ranges from 0 to 50, and the initial value is 0. You usually want to add at least some adornments to the slider to make it more usable. The slider shown in Figure 3-6 has minimum and maximum tick-mark values with labels visible. Here’s the read more..

  • Page - 647

    Book VI Chapter 3 Getting Input from the User Designing a Pizza-Ordering Program 623 contains the code you want executed when the slider control changes, then pass it via a Lambda expression to the slider control’s addChangeListener method. For more information about Lambda expressions, refer to Book III, Chapter 7. Here’s an example of a method you might call when the read more..

  • Page - 648

    Designing a Pizza-Ordering Program 624 Listing 3-2: The Pizza Order Program import javax.swing.*; import java.awt.event.*; import javax.swing.border.*; public class Pizza extends JFrame { public static void main(String [] args) { new Pizza(); } private JButton buttonOK; ➝12 private JRadioButton small, medium, large; private JCheckBox pepperoni, read more..

  • Page - 649

    Book VI Chapter 3 Getting Input from the User Designing a Pizza-Ordering Program 625 pepperoni = new JCheckBox("Pepperoni"); ➝52 topPanel.add(pepperoni); mushrooms = new JCheckBox("Mushrooms"); topPanel.add(mushrooms); anchovies = new JCheckBox("Anchovies"); topPanel.add(anchovies); read more..

  • Page - 650

    Designing a Pizza-Ordering Program 626 Here are the highlights of how this program works: ➝ 12 The components that are added to the frame are declared as class variables. ➝ 23 This line creates mainPanel, the first of three panels that the pro- gram uses. This panel contains the other two panels, which use borders to group their components visually. ➝ 25 read more..

  • Page - 651

    Book VI Chapter 3 Getting Input from the User Designing a Pizza-Ordering Program 627 ➝ 90 This if statement finishes the msg string by adding no toppings if the user didn’t pick any toppings or the tops string if the user did pick toppings. ➝ 95 This line uses JOptionPane to show a message box that displays the user’s order. ➝ 99 read more..

  • Page - 652

    628 Book VI: Swing read more..

  • Page - 653

    Chapter 4: Choosing from a List In This Chapter ✓ Combo boxes ✓ Lists ✓ Spinners ✓ Trees A whole category of Swing components is designed to let the user choose one or more items from a list. This chapter presents four such controls. The first three —  JList, JComboBox, and JSpinner — are straightforward. The fourth —  JTree — is a bit more complicated read more..

  • Page - 654

    Using Combo Boxes 630 Table 4-1 Common JComboBox Constructors and Methods Constructor Description JComboBox() Creates an empty combo box. JComboBox(Object[] items) Creates a combo box and fills it with the values in the array. JComboBox(Vector[] items) Creates a combo box and fills it with the values in the vector. Method Description void addActionListener (ActionListener listener) Adds an read more..

  • Page - 655

    Using Combo Boxes 631 Book VI Chapter 4 Choosing from a List Creating combo boxes Creating a combo box is easy. You have three constructors to choose among, the first of which creates an empty combo box: JComboBox combo1 = new JComboBox(); Then you can use the addItem to add items to the combo box: combo1.addItem("Bashful"); combo1.addItem("Doc"); read more..

  • Page - 656

    Using Combo Boxes 632 To remove items from the combo box, use one of the remove methods. If you know the index position of the item you want to remove, call the remove ItemAt method and pass the index number as a parameter. Otherwise, if you have the object you want to remove, call removeItem and pass the object. To remove all the items in a combo box, read more..

  • Page - 657

    Using Lists 633 Book VI Chapter 4 Choosing from a List Handling combo box events When the user selects an item from a combo box, an action event is generated. In most applications, you simply ignore this event because you usually don’t need to do anything immediately when the user selects an item. Instead, the selected item is processed when the user clicks a read more..

  • Page - 658

    Using Lists 634 Lists are almost always used in conjunction with scroll panes (covered in Book VI, Chapter 3) to allow the user to scroll the contents of the list. Figure 4-2 shows a sample frame with a list component. Figure 4-2: A frame with a list. Lists and combo boxes have several important differences: ✦ A list doesn’t have a text field that lets the user edit the selected read more..

  • Page - 659

    Using Lists 635 Book VI Chapter 4 Choosing from a List Constructor Description JList(Object[] items) Creates a list and fills it with the values in the array. JList(Vector[] items) Creates a list and fills it with the values in the vector. void clearSelection() Clears all selections. Method Description int getSelectedIndex() Returns the index of the first selected item, or –1 if read more..

  • Page - 660

    Using Lists 636 Creating a list To create a list and specify its items, you pass an array to the JList con- structor. Then you call the setVisibleRowCount method to set the number of rows you want to be visible, add the list to a scroll pane, and add the scroll pane to a panel that you can later add to the frame. Here’s an example: String[] toppings = read more..

  • Page - 661

    Using Lists 637 Book VI Chapter 4 Choosing from a List objects that includes each item selected by the user. When you retrieve these objects, you have to cast each one to the appropriate type; Java doesn’t provide any way to cast the entire array. You can call the following method from an action listener for the list box shown in Figure 4-2 earlier in this chapter: public read more..

  • Page - 662

    Using Lists 638 component. Then you pass the list model object to the JList constructor. The list model is responsible for managing the list that’s displayed by the JList component. As a result, you can use the list model’s methods to add or remove items, and then the JList component automatically updates itself to reflect the list changes. Table 4-3 shows the most read more..

  • Page - 663

    Using Spinners 639 Book VI Chapter 4 Choosing from a List for (String value : values) model.addElement(value); Here the elements from the values array are added to the list model. When you create the list control, pass the list model to the JList constructor, like so: list = new JList(model); You can remove an element from the list model by calling the remove or read more..

  • Page - 664

    Using Spinners 640 Method Description void addChangeListener (ChangeListener listener) Adds a ChangeListener to listen for change events. int getValue() Gets the value. void setToolTipText (String ext) Sets the tooltip text that’s displayed if the user rests the mouse over the slider for a few moments. Constructors for SpinnerModel Classes Description SpinnerNumberModel (int init, int read more..

  • Page - 665

    Using Trees 641 Book VI Chapter 4 Choosing from a List Table 4-4 lists constructors for two classes that implement Spinner. The first, SpinnerNumberModel, creates numeric spinner controls that let you control the initial value, the minimum and maximum values, and the step value that’s added or subtracted each time the user clicks one of the arrows. Here’s how you can use the read more..

  • Page - 666

    Using Trees 642 Figure 4-4: A frame with a tree. Tree controls are probably the most difficult of all Swing controls to work with. To cover them completely, I’d have to devote a full chapter of 30 pages or more. In the few short pages that remain in this chapter, then, I’m just going to present the basics: how to create a tree component such as read more..

  • Page - 667

    Using Trees 643 Book VI Chapter 4 Choosing from a List Building a tree Before you can actually create a tree control, you must build the tree it dis- plays. The easiest way to do that is to use the DefaultMutableTreeNode class, the details of which are shown in Table 4-5. Table 4-5 The DefaultMutableTreeNode Class Constructor Description DefaultMutableTreeNode() Creates an empty tree read more..

  • Page - 668

    Using Trees 644 In this section, I build a tree that lists spinoff shows from three popular television shows of the past: ✦ The Andy Griffith Show, which had two spinoffs: Gomer Pyle, U.S.M.C., and Mayberry R.F.D. ✦ All in the Family, which directly spawned four spinoffs: The Jeffersons, Maude, Gloria, and Archie Bunker’s Place. In addition, two of these read more..

  • Page - 669

    Using Trees 645 Book VI Chapter 4 Choosing from a List This method accepts a string and another node as parameters, and returns a node whose user object is set to the String parameter. The returned node is also added to the parent node as a child. Thus you can call this method to both create a new node and place the node in the tree. The next step is creating read more..

  • Page - 670

    Using Trees 646 Creating a JTree component You use the JTree class to create a tree component that displays the nodes of a tree. Table 4-6 shows the key constructors and methods of this class. Table 4-6 Ordinary Constructors and Methods of the JTree Class Constructor Description void JTree() Creates an empty tree (not very useful, if you ask me). void JTree(TreeNode root) Creates a tree read more..

  • Page - 671

    Using Trees 647 Book VI Chapter 4 Choosing from a List Here the getSelectionModel method is called to get a TreeSelectionModel object that determines how the user can select nodes in the tree. This class provides a method named setSelectionMode that lets you set the selection mode. To limit the tree to a single node selection, you must pass this method the read more..

  • Page - 672

    Using Trees 648 object as a parameter. The easiest way to implement this interface is to use a Lambda expression to simply call a method that contains the code you want to run when the user selects a node. Here’s an example of such a method; it simply sets the value of a label named showName to the value of the user object of the selected item: public void read more..

  • Page - 673

    Using Trees 649 Book VI Chapter 4 Choosing from a List private JTree tree1; ➝13 private DefaultTreeModel model; private JLabel showName; public SpinOffs() { this.setSize(250,400); this.setTitle("Famous Spinoffs"); this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); read more..

  • Page - 674

    Using Trees 650 public DefaultMutableTreeNode makeShow( ➝65 String title, DefaultMutableTreeNode parent) { DefaultMutableTreeNode show; show = new DefaultMutableTreeNode(title); parent.add(show); return show; } public void tree1Changed() ➝74 { read more..

  • Page - 675

    Chapter 5: Using Layout Managers In This Chapter ✓ Flow layout ✓ Border layout ✓ Box layout ✓ Grid layout ✓ GridBag layout ✓ Group layout C ontrolling the layout of components in a frame is one of the most diffi- cult aspects of working with Swing. In fact, it can be downright exasper- ating. Sometimes the components almost seem to have minds of their own. They read more..

  • Page - 676

    Working with Layout Managers 652 ✦ Flow: This layout manager is the default for panels. It lays out compo- nents one after the other until it runs out of room; then it starts a new row of components. ✦ Border: This layout manager is the default for frames. It divides the con- tainer into five regions: North, South, East, West, and Center. When you add a read more..

  • Page - 677

    Book VI Chapter 5 Using Layout Managers Using Flow Layout 653 In addition to these six layout managers, Java provides a few others, including Card and Spring. The Card layout manager lets you create tabbed layouts, but it has been largely replaced by other components that do the same thing more effectively. The Spring layout manager uses a weird concept called springs read more..

  • Page - 678

    Using Flow Layout 654 Table 5-1 FlowLayout Constructors Constructor Description FlowLayout() Creates a Flow layout manager with centered alignment and no gaps. FlowLayout(int align) Creates a Flow layout manager with the specified alignment. The align parameter can be FlowLayout. LEFT, FlowLayout.CENTER, or FlowLayout.RIGHT. FlowLayout(int align, int hgap, int vgap) Creates a Flow layout read more..

  • Page - 679

    Book VI Chapter 5 Using Layout Managers Using Border Layout 655 Using Border Layout The Border layout manager carves a frame or panel into five regions: North, South, East, West, and Center, as shown in Figure 5-3. When you add a com- ponent to the frame or panel, you can specify which of these regions the component goes in. Figure 5-3: How Border layout carves things read more..

  • Page - 680

    Using Box Layout 656 SOUTH Defines the South region (at the bottom of the container). WEST Defines the West region (on the left side of the container). EAST Defines the East region (on the right side of the container). CENTER Defines the Center region (in the middle of the container). When you add a component to a panel or frame that uses the Border layout manager, read more..

  • Page - 681

    Book VI Chapter 5 Using Layout Managers Using Box Layout 657 Although you can apply the Box layout directly to a panel, it’s much more common to use the Box class, which is similar to a panel but defaults to Box layout rather than to Flow layout. In addition, the Box class has several static methods that are useful for laying out components in the box. read more..

  • Page - 682

    Using Box Layout 658 box1.add(new JButton("Cancel")); box1.add(new JButton("Close")); The real power of Box layouts is their use of struts, rigid areas, and glue: ✦ Struts: A strut inserts a specified amount of space between components. You can create a strut by calling the createHorizontalStrut or createVerticalStrut method, depending on which type of strut you read more..

  • Page - 683

    Book VI Chapter 5 Using Layout Managers Using Grid Layout 659 If you add this Box layout to the South region of a frame, the buttons appear as shown in Figure 5-4. Figure 5-4: Using Box layout to arrange buttons. Using Grid Layout The Grid layout is designed for panels that need to have a set number of components all equally sized and arranged in a read more..

  • Page - 684

    Using GridBag Layout 660 to expand to however many rows or columns are necessary to hold all the components you add to the panel. The following code creates a Grid layout panel that resembles a phone (shown in Figure 5-1 earlier in this chapter): JPanel panel1 = new JPanel(); panel1.setLayout(new GridLayout(0,3)); panel1.add(new JButton("7")); panel1.add(new JButton("8")); read more..

  • Page - 685

    Book VI Chapter 5 Using Layout Managers Using GridBag Layout 661 Sketching out a plan Before you create a GridBag panel, you should draw a sketch showing how you want the components to appear in the panel. Then slice the panel into rows and columns, and number the rows and columns starting with zero in the top-left corner. Figure 5-5 shows such a sketch, prepared in my read more..

  • Page - 686

    Using GridBag Layout 662 Adding components to a GridBag layout Before you can add components to a panel using GridBag layout, you must specify GridBag as the panel’s layout manager. You do that by calling the setLayout method, passing a new GridBagLayout object as a parameter, as follows: JPanel panel1 = new JPanel(); panel1.setLayout(new GridBagLayout()); When a panel uses the read more..

  • Page - 687

    Book VI Chapter 5 Using Layout Managers Using GridBag Layout 663 A few of these fields need some extra explanation: ✦ The weightx and weighty fields give the GridBag layout manager a hint about how to adjust the size of the columns and rows. If you set one of these values to 0, the size of the row or column remains fixed. A common technique is to set both read more..

  • Page - 688

    Using GridBag Layout 664 Method 1: Recycle a constraint object The first method is to create a single constraint object and reuse it for all the components in the panel. Then you simply change the fields that need to be changed for each component. Here’s code that adds all three text fields by using a single constraint object: GridBagConstraints gc = new read more..

  • Page - 689

    Book VI Chapter 5 Using Layout Managers Using GridBag Layout 665 Then you can call this method to add a component to the panel. You must pass the panel and the component, its x and y positions, and its width and height. Here’s how you add the Name text field: addItem(panel1, name, 0, 1, 2, 1, GridBagConstraints.WEST); Viewing a GridBag layout example Listing read more..

  • Page - 690

    Using GridBag Layout 666 JPanel panel1 = new JPanel(); panel1.setLayout(new GridBagLayout()); ➝23 addItem(panel1, new JLabel("Name:"), ➝25 0, 0, 1, 1, GridBagConstraints.EAST); addItem(panel1, new JLabel("Phone:"), 0, 1, 1, 1, GridBagConstraints.EAST); read more..

  • Page - 691

    Book VI Chapter 5 Using Layout Managers Using GridBag Layout 667 Box topBox = Box.createVerticalBox(); ➝72 pepperoni = new JCheckBox("Pepperoni"); mushrooms = new JCheckBox("Mushrooms"); anchovies = new JCheckBox("Anchovies"); topBox.add(pepperoni); read more..

  • Page - 692

    Using Group Layout 668 ➝ 43 These lines use a vertical Box object to create the radio buttons that let the user select the size. ➝ 59 These lines use a vertical Box object to create the radio buttons that let the user select the crust style. ➝ 72 These lines use a vertical Box object to create the check boxes that let the user select read more..

  • Page - 693

    Book VI Chapter 5 Using Layout Managers Using Group Layout 669 The ant encounters a parallel group within a sequential group. The code to describe the groups looks like this: GroupLayout.SequentialGroup leftToRight = layout.createSequentialGroup(); leftToRight.addComponent(buttonD); GroupLayout.ParallelGroup columnMiddle = read more..

  • Page - 694

    Using Group Layout 670 Listing 5-2: A Frame with a Group Layout import javax.swing.GroupLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class UseGroupLayout3 { public static void main(String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel(); read more..

  • Page - 695

    Book VI Chapter 5 Using Layout Managers Using Group Layout 671 A reader from Minnesota asks: “What happens if you change the code in Listing 5-2? What if you modify one of the ants’ descriptions so that the two descriptions don’t agree?” The answer is: Nothing good happens. Yes, the two ants’ descriptions seem to be redundant; but no, you can’t eliminate one of read more..

  • Page - 696

    672 Book VI: Swing read more..

  • Page - 697

    You can find an interesting programming challenge that requires use of many of the programming techniques covered in this minibook at www.dummies.com/ extras/javaaio. The challenge for this book is to enhance the Swing version of the Tic-Tac-Toe program created for previously so that it runs as an applet. Book VII Web Programming read more..

  • Page - 698

    Contents at a Glance Contents at a Glance Chapter 1: Creating Applets ...................................675 Understanding Applets ....................................................................................................675 Working with the JApplet Class .....................................................................................676 Looking at a Sample Applet read more..

  • Page - 699

    Chapter 1: Creating Applets In This Chapter ✓ Looking at applets ✓ Creating an applet ✓ Creating HTML to display applets ✓ Testing applets with the applet viewer A n applet is not a small piece of fruit. Rather, it’s a Java application that’s designed to run in a browser window on an Internet user’s com- puter. When an Internet user visits a web page that read more..

  • Page - 700

    Working with the JApplet Class 676 ✦ Standalone Swing methods need a way to let the user shut them down. Typically, Swing applications include an Exit button or an Exit menu command; applets don’t. An applet remains alive as long as the page that contains it is displayed. ✦ Applets aren’t displayed in windows; they’re displayed in a region of a web page. As a read more..

  • Page - 701

    Working with the JApplet Class 677 Book VII Chapter 1 Creating Applets Table 1-1 Useful JApplet Constructors and Methods Constructor Description JApplet() Creates a new applet. You usually don’t need to call the JApplet constructor because it’s called automatically when the browser loads the applet. Method Description void add(Component c) Adds the specified component to the applet. read more..

  • Page - 702

    Looking at a Sample Applet 678 Looking at a Sample Applet To see how a complete applet works, Listing 1-1 shows the complete code for an applet that lets the user order a pizza in one of three sizes (Small, Medium, and Large) with one of three toppings (Pepperoni, Mushrooms, and Anchovies). Figure 1-1 shows this applet in action on a web page. Listing 1-1: The Pizza Order Applet read more..

  • Page - 703

    Looking at a Sample Applet 679 Book VII Chapter 1 Creating Applets pepperoni = new JCheckBox("Pepperoni"); topPanel.add(pepperoni); mushrooms = new JCheckBox("Mushrooms"); topPanel.add(mushrooms); anchovies = new JCheckBox("Anchovies"); topPanel.add(anchovies); read more..

  • Page - 704

    Creating an HTML Page for an Applet 680 Figure 1-1: The pizza applet in action. This listing is an applet version of a Swing program presented in Book VI, Chapter 3. For the details on how the Swing components work, you can refer to that chapter. Here I just want to point out a few details that are specific to applets: ➝ 5 The class extends JApplet read more..

  • Page - 705

    Testing an Applet 681 Book VII Chapter 1 Creating Applets The basic form of the APPLET tag is this: <APPLET code="classname" width=width height=height> Text to display if applet can't be loaded </APPLET> Here’s the HTML file that I used to display the page shown in Figure 1-1, earlier in this chapter: <html> <head> <title>The read more..

  • Page - 706

    682 Book VII: Web Programming read more..

  • Page - 707

    Chapter 2: Creating Servlets In This Chapter ✓ Looking at servlets ✓ Downloading, installing, and configuring Tomcat ✓ Creating simple servlets ✓ Working with forms to get data from the user S ervlets are among the most popular ways to develop web applications today. Many of the best-known websites are powered by servlets, including Gmail, Amazon, Linkedin, and eBay. read more..

  • Page - 708

    Using Tomcat 684 3. The server computer receives the file request, retrieves the requested file, and sends the file back to you in the form of an HTTP response message. 4. The web browser receives the file, interprets the HTML that it contains, and displays the result onscreen. The most important thing to note about normal web interactions is that they’re static. read more..

  • Page - 709

    Book VII Chapter 2 Creating Servlets Using Tomcat 685 Installing and configuring Tomcat Installing Tomcat isn’t rocket science, but it’s not as easy as making toast, either. Here are the steps you can follow to set up Tomcat 8: 1. Download the Tomcat Zip file from the Apache website (http://tomcat.apache.org). Although Apache also offers an executable setup file for read more..

  • Page - 710

    Using Tomcat 686 Figure 2-1: Starting Tomcat. You know that Tomcat has started when you see a line such as the following, indicating how long the startup took: INFO: Server startup in 1186 ms If the Tomcat window appears for a few seconds, and then an exception message flies by quickly and the window closes, the most likely problem is that you already have read more..

  • Page - 711

    Book VII Chapter 2 Creating Servlets Creating a Simple Servlet 687 The page shown in Figure 2-2 appears. If it doesn’t, r efer to the section “Install- ing and configuring Tomcat,” earlier in this chapter, and double-check each step to make sure you did it correctly. Figure 2-2: Testing Tomcat. Creating a Simple Servlet Okay, enough of the configuration stuff; now you can read more..

  • Page - 712

    Creating a Simple Servlet 688 Extending the HttpServlet class To create a servlet, you write a class that extends the HttpServlet class. Table 2-1 lists six methods you can override in your servlet class. Table 2-1 The Ht tpServlet Class Method When Called Signature doDelete HTTP DELETE request public void doDelete(Http ServletRequest request, HttpServletResponse response) throws IOException, read more..

  • Page - 713

    Book VII Chapter 2 Creating Servlets Creating a Simple Servlet 689 ✦ An HttpServletResponse object representing the response that is sent back to the user. You use the response parameter to compose the output that is sent back to the user. You find out how to do that in the next section. Printing to a web page One of the main jobs of most servlets is writing HTML read more..

  • Page - 714

    Creating a Simple Servlet 690 { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>HelloWorld</title>"); out.println("</head>"); read more..

  • Page - 715

    Book VII Chapter 2 Creating Servlets Creating a Simple Servlet 691 For your reference, Table 2-2 summarizes all the HTML tags that I use in this book. Table 2-2 Just Enough HTML to Get By HTML tag Description <html>, </html> Marks the start and end of an HTML document. <head>, </head> Marks the start and end of the head section of an HTML document. read more..

  • Page - 716

    Running a Servlet 692 Running a Servlet So exactly how do you run a servlet? First, you must compile the .java file to create a .class file; then you must move the .class file into a directory from which Tomcat can run the servlet. For testing purposes, you can move the servlet’s class file to c:\tomcat\webapps\Examples\WEB-INF\classes and then type an address read more..

  • Page - 717

    Book VII Chapter 2 Creating Servlets Improving the HelloWorld Servlet 693 Listing 2-2: The HelloServlet Servlet import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException read more..

  • Page - 718

    Getting Input from the User 694 case 5: return "Whasssuuuup?"; case 6: return "Hark!"; } return null; } } Getting Input from the User If a servlet is called by an HTTP GET or POST request that read more..

  • Page - 719

    Book VII Chapter 2 Creating Servlets Getting Input from the User 695 The action attribute in the form tag of this form specifies that /servlet/ InputServlet is called when the form is submitted, and the method attribute indicates that the form is submitted via a POST rather than a GET request. The form itself consists of an input text field named name and a Submit read more..

  • Page - 720

    Using Classes in a Servlet 696 out.println("<body>"); out.println("<h1>"); out.println("Hello " + name); out.println("</h1>"); out.println("</body>"); out.println("</html>"); } public void doPost(HttpServletRequest read more..

  • Page - 721

    Book VII Chapter 2 Creating Servlets Using Classes in a Servlet 697 for the purposes of this chapter, is c:\tomcat\webapps\ROOT\WEB-INF\ classes. To illustrate a servlet that uses several classes, Figure 2-5 shows the output from a servlet that lists movies read from a text file. This servlet uses three classes: ✦ Movie: A class that represents an individual movie. ✦ MovieIO: read more..

  • Page - 722

    Using Classes in a Servlet 698 { this.title = title; this.year = year; this.price = price; } } Listing 2-6 shows the MovieIO class. This class uses the file I/O features that are presented in Book VIII, Chapter 2 to read data from a text file. The text file uses tabs to separate the fields and read more..

  • Page - 723

    Book VII Chapter 2 Creating Servlets Using Classes in a Servlet 699 private static BufferedReader getReader( String name) { BufferedReader in = null; try { File file = new File(name); in = new BufferedReader( read more..

  • Page - 724

    Using Classes in a Servlet 700 Listing 2-7: The ListMovie Servlet Class import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class ListMovies extends HttpServlet { public void doGet(HttpServletRequest request, ➝8 HttpServletResponse response) throws IOException, ServletException { read more..

  • Page - 725

    Book VII Chapter 2 Creating Servlets Using Classes in a Servlet 701 The following paragraphs describe what its methods do: ➝ 8 The doGet method calls the getMovieList method to get a string that contains a list of all the movies, separated by break ( <br>) tags. Then it uses a series of out.println statements to write HTML that displays this list. ➝ read more..

  • Page - 726

    702 Book VII: Web Programming read more..

  • Page - 727

    Chapter 3: Using JavaServer Pages In This Chapter ✓ Seeing how servlets work ✓ Dealing with page directives ✓ Trying out expressions ✓ Putting scriptlets to work ✓ Devising declarations ✓ Comprehending classes I n Book VII, Chapter 2, you discover how to create servlets that write HTML data directly to a page by using the PrintWriter object accessed through response.out. Although read more..

  • Page - 728

    Understanding JavaServer Pages 704 The first time a user requests a JSP file, the file is run through a translator program that converts the file to a Java servlet program and compiles it. All the HTML from the original JSP file is converted to out.print statements that send the HTML to the response, and the Java statements from the JSP file are incorporated into the read more..

  • Page - 729

    Book VII Chapter 3 Using JavaServer Pages Using Page Directives 705 Using Page Directives A page directive is a JSP element that sets options that determine how the JSP is converted to a servlet. The basic format of a page directive is this: <%@ page attribute=value %> The attribute can be any of the attributes listed in Table 3-1. (A few attributes besides these are read more..

  • Page - 730

    Using Expressions 706 You can place page directives anywhere you want in a JSP document, but I suggest that you place them at or near the top so they will be easy to find. Using Expressions A JSP expression is any Java expression that evaluates to a string. Actually, the expression doesn’t have to evaluate directly. Here’s how you can use the java.util.Date class read more..

  • Page - 731

    Book VII Chapter 3 Using JavaServer Pages Using Expressions 707 The implicit object you use most in expressions is request. In particular, you use its getParameter method to get values entered by the user in forms. Here’s an expression that displays the value entered in an input field titled Name: <%= request.getParameter("Name")%> The value of the Name field is read more..

  • Page - 732

    Using Scriptlets 708 Note: Expressions can also call methods that you add to the JSP with dec- laration elements. You see examples of how to do that in the section “Using Declarations,” later in this chapter. Using Scriptlets As mentioned earlier in the chapter, a scriptlet is a statement or group of state ments that’s inserted directly into the servlet at the point read more..

  • Page - 733

    Book VII Chapter 3 Using JavaServer Pages Using Scriptlets 709 These lines create a string variable named msg and then use out.println to write the string to the response output. As a result, the formatted date is inserted between <h1>Today is </h1> and <h1>Have a nice day!</h1>. Figure 3-2 shows a page generated by this JSP. Figure 3-2: DateJSP. jsp in read more..

  • Page - 734

    Using Declarations 710 Here’s a scriptlet named LoopyJSP.jsp that repeats a line 12 times on the page by including the line in the block of a for loop: <html> <head> <title>Can't you see I'm trying to work here?</title> </head> <body> <% for (int i = 0; i < 12; i++) { %> All work read more..

  • Page - 735

    Book VII Chapter 3 Using JavaServer Pages Using Declarations 711 Here’s a servlet that declares a static class field named count that’s incre- mented each time the page is displayed: <html> <%@ page import="java.text.*" %> <%@ page import="java.util.*" %> <head> <title>Counter JSP</title> </head> <body> read more..

  • Page - 736

    Using Classes 712 <%! private String getDate() { DateFormat df = DateFormat.getDateInstance(DateFormat.FULL); Date today = new Date(); return df.format(today); } %> The declaration at the end of this document declares a method that returns the current date as a string. Then the expression <%= getDate() %> is used to insert the date read more..

  • Page - 737

    Book VII Chapter 3 Using JavaServer Pages Using Classes 713 Listing 3-1: ListMovies.jsp <!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN"> <%@ page import="com.lowewriter.movie.*" %> ➝3 <%@ page import="java.util.*" %> <html> <head> <title>List Movies: The Servlet</title> </head> <body> <h1>Some of My read more..

  • Page - 738

    Using Classes 714 Following is an explanation of the key lines in this JSP: ➝ 3 The JSP includes two page directives that import the com. lowewriter.movie and java.util packages. ➝ 12 An expression is used to call the getMovieList method, which returns the list of movies to be displayed as a string. ➝ 18 The getMovieList method is defined in a read more..

  • Page - 739

    Book VII Chapter 3 Using JavaServer Pages Using Classes 715 Listing 3-3: MovieIO.java package com.lowewriter.movie; import java.io.*; import java.util.*; public class MovieIO { public static ArrayList<Movie> getMovies() { ArrayList<Movie> movies = new ArrayList<Movie>(); BufferedReader in = read more..

  • Page - 740

    Using Classes 716 try { line = in.readLine(); } catch (IOException e) { System.out.println("I/O Error"); System.exit(0); } if (line == null) return read more..

  • Page - 741

    You can find an interesting programming challenge that requires use of many of the programming techniques covered in this minibook at www.dummies.com/ extras/javaaio. The challenge for this book is to enhance the Swing version of the Tic-Tac-Toe program created earlier so that it allows the player to save an in-progress game to a disk file and later restore a saved read more..

  • Page - 742

    Contents at a Glance Contents at a Glance Chapter 1: Working with Files .................................719 Using the File Class ..........................................................................................................719 Using Command-Line Parameters .................................................................................725 Choosing Files in a Swing Application read more..

  • Page - 743

    Chapter 1: Working with Files In This Chapter ✓ Examining the File class ✓ Understanding command-line parameters ✓ Introducing the JFileChooser class I n this chapter, you discover the ins and outs of working with files and directories. I don’t show you how to read or write files (for that info, you should flip to Book VIII, Chapter 2), but you do find out how to find files on read more..

  • Page - 744

    Using the File Class 720 Knowing the class constructors and methods Table 1-1 lists the main constructors and methods of the File class. Table 1-1 The File Class Constructor Description File(String pathname) Creates a file with the specified pathname. Field Description String separator Separates components of a pathname on this system; usually is \ or /. Method Description boolean canRead() Determines whether read more..

  • Page - 745

    Book VIII Chapter 1 W orking with Files Using the File Class 721 long lastModified() Returns the time when the file was last modified, expressed in milliseconds since 0:00:00 a.m., January 1, 1970. long length() Returns the size of the file in bytes. String[] list() Returns an array of String objects with the name of each file and direc- tory in this directory. Each string read more..

  • Page - 746

    Using the File Class 722 Creating a File object To create a File object, you call the File constructor, passing a string rep- resenting the filename as a parameter. Here’s an example: File f = new File("hits.log"); Here the file’s name is hits.log, and it lives in the current directory, which usually is the directory from which the Java Virtual Machine (JVM) read more..

  • Page - 747

    Book VIII Chapter 1 W orking with Files Using the File Class 723 Note that the createNewFile method returns a boolean that indicates whether the file was created successfully. If the file already exists, create NewFile returns false, so you don’t have to use the exists method before you call createNewFile. When you create a file with the createNewFile method, the file read more..

  • Page - 748

    Using the File Class 724 The following snippet is a little more selective because it lists only files, not subdirectories, and doesn’t list hidden files: File dir = new File(path); if (dir.isDirectory()) { File[] files = dir.listFiles(); for (File f : files) { if (f.isFile() && !f.isHidden()) read more..

  • Page - 749

    Book VIII Chapter 1 W orking with Files Using Command-Line Parameters 725 Deleting a file To delete a file, create a File object for the file and then call the delete method, as in this example: File f = new File("hits.log"); if (f.delete()) System.out.println("File deleted."); else System.out.println("File not deleted."); If the file is a read more..

  • Page - 750

    Using Command-Line Parameters 726 Suppose that you run a Java program named Test from a command program like this: C:\>java Test the quick brown fox In this case, the Java program is passed four parameters: the, quick, brown, and fox. You can access these parameters via the args array. Suppose that the main method of the Test class is written like this: public static read more..

  • Page - 751

    Book VIII Chapter 1 W orking with Files Choosing Files in a Swing Application 727 Choosing Files in a Swing Application For the most part, you don’t want to mess around with command-line param- eters in Swing applications. Instead, you want to use the JFileChooser class to let users pick the files they want to work with. This class lets you display Open and Save dialog boxes read more..

  • Page - 752

    Choosing Files in a Swing Application 728 The JFileChooser class has many additional methods that you can use to tailor its appearance and behavior in just about any way imaginable. Table 1-2 lists the commonly used constructors and methods of this powerful class. Table 1-2 The JFileChooser Class Constructor Description JFileChooser() Creates a file chooser that begins at the read more..

  • Page - 753

    Book VIII Chapter 1 W orking with Files Choosing Files in a Swing Application 729 void setFileSelectionMode(int mode) Determines whether the user can select files, directories, or both. The parameter can be specified as JFileChooser.FILES_ ONLY, DIRECTORIES_ONLY, or FILES_AND_DIRECTORIES. int showOpenDialog(Component parent) Displays an Open dialog box. The return values are the same as read more..

  • Page - 754

    Choosing Files in a Swing Application 730 ✦ JFileChooser.DIRECTORIES_ONLY: With this option, the user can select only directories, not files. One common use for this option is to let the user choose a default location for files used by your application without actually opening a file. ✦ JFileChooser.FILES_AND_DIRECTORIES: This option lets the user select either a file or a read more..

  • Page - 755

    Book VIII Chapter 1 W orking with Files Choosing Files in a Swing Application 731 You can call this method from an action event handler when the user clicks a button, selects a menu command, or otherwise indicates that he or she wants to open a file. Using file filters The file-chooser dialog box includes a Files of Type drop-down list filter that the user can use to read more..

  • Page - 756

    Choosing Files in a Swing Application 732 Here the string Java files (*.java) is displayed in the Files of Type drop-down list. The accept method does the work of a file filter. The file chooser calls this method for every file it displays. The file is passed as a parameter. The accept method returns a boolean that indicates whether the file is displayed. The accept read more..

  • Page - 757

    Book VIII Chapter 1 W orking with Files Using Path Objects 733 If you want, you can remove the All Files filter by calling the method set AcceptAllFileFilterUsed, like this: fc.setAcceptAllFileFilterUsed(false); Then only the file filters that you add to the file chooser appear in the Files of Type drop-down list. Using Path Objects Java 1.7 introduces a new type of object read more..

  • Page - 758

    Using Path Objects 734 Method Description void delete() Deletes the file or directory. The method throws an exception if the file or directory doesn’t exist or couldn’t be deleted. void deleteIfExists() Deletes the file or directory if it exists. The method doesn’t throw an excep- tion if the file or directory doesn’t exist. boolean exists() Returns true if the file read more..

  • Page - 759

    Book VIII Chapter 1 W orking with Files Using Path Objects 735 Like a File object, a Path object represents a file that may or may not actu- ally exist on the hard drive. You can test to see whether a file exists like this: Path p = Paths.get(path); if (!p.exists()) System.out.println ("The input file does not exist!"); To create a new read more..

  • Page - 760

    Using a File Visitor to Walk a File T ree 736 This example displays a listing of the contents of the C:\ directory, much as typing DIR C:\ at a command prompt would. You could change the preceding example to list just the text files (files with the extension .txt) by changing the first statement after the try statement to this: DirectoryStream<Path> stream read more..

  • Page - 761

    Book VIII Chapter 1 W orking with Files Using a File Visitor to Walk a File T ree 737 2. In the file visitor, override one or more methods that are defined by the SimpleFileVisitor class. These methods are where you write the code that you want to execute for every file visited when the directory tree is walked. You always want to override at least three of the read more..

  • Page - 762

    Using a File Visitor to Walk a File T ree 738 public FileVisitResult visitFile(Path file, #23 BasicFileAttributes attr) { System.out.println(file.toString()); return FileVisitResult.CONTINUE; #27 } public FileVisitResult visitFileFailed(Path file, read more..

  • Page - 763

    Book VIII Chapter 1 W orking with Files Using a File Visitor to Walk a File T ree 739 ➝ 30 Overrides the visitFileFailed method, which is called when- ever a file can’t be accessed. In this program, the visitFile Failed method simply prints an error message. ➝ 36 Overrides the preVisitDirectoryFailed method, which is called whenever a directory can’t be read more..

  • Page - 764

    740 Book VIII: Files and Databases read more..

  • Page - 765

    Chapter 2: Working with File Streams In This Chapter ✓ Knowing your Java streams ✓ Reading and writing text streams ✓ Reading and writing binary streams I /O, I/O, it’s off to work I go. Or so goes the classic song, which pretty much sums up the whole purpose of computers. Without I/O (input/output), computers — and the programs that run on them — would be read more..

  • Page - 766

    Reading Character Streams 742 You can roughly divide the world of Java stream I/O into two camps: ✦ Character streams: Character streams read and write text characters that represent strings. You can connect a character stream to a text file to store text data on a hard drive. Typically, text files use special characters called delimiters to separate elements of read more..

  • Page - 767

    Book VIII Chapter 2 W orking with File Streams Reading Character Streams 743 constructor of the BufferedReader class, which provides more effi- cient access to the file. (This class extends the abstract class Reader, which is the base class for a variety of classes that can read character data from a stream.) ✦ BufferedReader: This class “wraps” ar ound the FileReader read more..

  • Page - 768

    Reading Character Streams 744 In the following sections, you find out how to read a file named movies.txt that contains one line each for ten of my favorite movies. Each line of the file contains the title of the movie, a tab, the year when the movie was released, another tab, and the price I paid for it. Here are the contents of the file: It's a Wonderful Life read more..

  • Page - 769

    Book VIII Chapter 2 W orking with File Streams Reading Character Streams 745 After you read a line of data from the file, you can use Java’s string-handling features to pull individual bits of data out of the line. In particular, you can use the split method to separate the line into the individual strings that are separated by tabs. Then you can use the read more..

  • Page - 770

    Reading Character Streams 746 { File file = new File(name); in = new BufferedReader( new FileReader(file) ); } catch (FileNotFoundException e) { System.out.println( read more..

  • Page - 771

    Book VIII Chapter 2 W orking with File Streams Reading Character Streams 747 this.price = price; } } } If you run this program, the following output is displayed on the console: 1946: It's a Wonderful Life ($14.95) 1974: Young Frankenstein ($16.95) 1977: Star Wars ($17.95) 1987: The Princess Bride ($16.95) 1989: Glory ($14.95) read more..

  • Page - 772

    Writing Character Streams 748 is reached, this method returns null. The statement that reads the line from the file is enclosed in a try/catch block that exits the program if an I/O error occurs. ➝ 70 The Movie class is a private inner class that defines the movie objects. To keep the class simple, it uses public fields and a single constructor that read more..

  • Page - 773

    Book VIII Chapter 2 W orking with File Streams Writing Character Streams 749 BufferedWriter(Writer out) Creates a buffered writer from the specified writer. Typically, you pass this constructor a FileWriter object. FileWriter(File file) Creates a file writer from the specified File object and throws IOException if an error occurs. FileWriter(File file, boolean append) Creates read more..

  • Page - 774

    Writing Character Streams 750 Connecting a PrintWriter to a text file To connect a character stream to an output file, you first create a File object for the file, as I describe in Book VIII, Chapter 1. Then you call the PrintWriter constructor to create a PrintWriter object that you can use to write to the file. This constructor wraps around a BufferedWriter read more..

  • Page - 775

    Book VIII Chapter 2 W orking with File Streams Writing Character Streams 751 File file = new File("movies.txt"); PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter(file) ), true); ////mode flush If all these nested constructors make your head spin, you can always con- struct each object separately and read more..

  • Page - 776

    Writing Character Streams 752 Also, when you’re finished writing data to the file, you can close the file by calling the close method, like this: out.close(); Writing the movies.txt file Listing 2-2 shows a complete program that writes lines to a text file. The data written is taken from an array that’s hard-coded into the file, but you can easily imagine how to obtain read more..

  • Page - 777

    Book VIII Chapter 2 W orking with File Streams Writing Character Streams 753 movies[9] = new Movie("Star Trek Into Darkness", 1997, 19.95); return movies; } private static PrintWriter openWriter(String name) ➝43 { try { read more..

  • Page - 778

    Reading Binary Streams 754 ➝ 5 The main method begins by calling a method named getMovies, which returns an array of Movie objects to be written to the file. (The Movie class is defined as an inner class later in the program.) Then it calls openWriter, which creates a PrintWriter object that the program can use to write data to the file. Next, it read more..

  • Page - 779

    Book VIII Chapter 2 W orking with File Streams Reading Binary Streams 755 ✦ DataInputStream: This class is the one you actually work with to read data from the stream. The other Stream classes read a byte at a time. This class knows how to read basic data types, including primitive types and strings. Table 2-3 lists the vital constructors and methods of these read more..

  • Page - 780

    Reading Binary Streams 756 Constructors Description double readDouble() Reads a double value from the input stream. It throws EOFException and IOException. float readFloat() Reads a float value from the input stream. It throws EOFException and IOException. int readInt() Reads an int value from the input stream. It throws EOFException and IOException. long readLong() Reads a long read more..

  • Page - 781

    Book VIII Chapter 2 W orking with File Streams Reading Binary Streams 757 a DataInputStream object to provide the methods that read various data types. The constructor for such a beast looks like this: File file = new File("movies.dat"); DataInputStream in = new DataInputStream( new BufferedInputStream( new FileInputStream(file) ) ); If all read more..

  • Page - 782

    Reading Binary Streams 758 catch (EOFException e) { eof = true; } catch (IOException e) { System.out.println("An I/O error " + "has occurred!"); System.exit(0); } } Here the boolean variable eof is set to true when EOFException is read more..

  • Page - 783

    Book VIII Chapter 2 W orking with File Streams Reading Binary Streams 759 Listing 2-3: Reading from a Binary File import java.io.*; import java.text.NumberFormat; public class ReadBinaryFile { public static void main(String[] args) ➝6 { NumberFormat cf = NumberFormat.getCurrencyInstance(); DataInputStream in = read more..

  • Page - 784

    Reading Binary Streams 760 try { title = in.readUTF(); year = in.readInt(); price = in.readDouble(); } catch (EOFException e) { return null; } catch read more..

  • Page - 785

    Book VIII Chapter 2 W orking with File Streams Writing Binary Streams 761 it uses a while loop to call a method named readMovie to get a movie object. If the Movie object isn’t null, the movie’s data is printed to the console. Finally, when the loop ends, a method named closeFile is called to close the file. ➝ 28 The getStream method creates a read more..

  • Page - 786

    Writing Binary Streams 762 Constructor Description FileOutputStream(File file) Creates a file writer from the file. It throws FileNotFoundException if an error occurs. FileOutputStream(File file, boolean append) Creates a file writer from the file. It throws FileNotFoundException if an error occurs. If the second parameter is true, data is added to the end of the file if read more..

  • Page - 787

    Book VIII Chapter 2 W orking with File Streams Writing Binary Streams 763 Constructor Description void writeInt(int value) Writes an int value to the output stream. It throws IOException. void writeLong(long value) Writes a long value to the output stream. It throws IOException. void writeShort(short value) Writes a short value to the output stream. It throws IOException. void read more..

  • Page - 788

    Writing Binary Streams 764 Writing to a binary stream After you successfully connect a DataOutputStream to a file, writing data to it is simply a matter of calling the various write methods to write different data types to the file. The following code writes the data for a Movie object to the file: out.writeUTF(movie.title); out.writeInt(movie.year); out.writeDouble(movie.price); These read more..

  • Page - 789

    Book VIII Chapter 2 W orking with File Streams Writing Binary Streams 765 movies[0] = new Movie("It's a Wonderful Life", 1946, 14.95); movies[1] = new Movie("Young Frankenstein", 1974, 16.95); movies[2] = new Movie("Star Wars", 1977, read more..

  • Page - 790

    Writing Binary Streams 766 try { out.close(); } catch (IOException e) { System.out.println("I/O Exception closing file."); System.exit(0); } } private static class Movie ➝92 read more..

  • Page - 791

    Chapter 3: Database for $100, Please In This Chapter ✓ Understanding some basic database concepts ✓ Taking a quick look at SQL ✓ Creating tables ✓ Selecting data ✓ Joining data ✓ Updating and deleting data S QL stands for Structured Query Language. SQL is the lingua franca (that’s not a type of pasta but a type of tongue) of relational databases. It’s read more..

  • Page - 792

    Understanding (and Pronouncing) SQL 768 ✦ A database that is accessed via SQL: IBM invented SQL to provide a practical way to access data stored in relational databases. ✦ Any database system developed since about 1980, with the exception of a few cutting-edge object-oriented databases: Marketers quickly figured out that the way to sell database programs was to read more..

  • Page - 793

    Creating a SQL Database 769 Book VIII Chapter 3 Database for $100, Please Table 3-1 Common SQL Statements SQL Statement Description Data Manipulation select Retrieves data from one or more tables. This statement is the one you use most often. insert Inserts one or more rows into a table. delete Deletes one or more rows from a table. update Updates existing rows in a table. read more..

  • Page - 794

    Creating a SQL Database 770 installer that’s appropriate for your Windows version, and then follow the onscreen instructions.) Script statements end with semicolons, which is about the only thing that SQL scripts have in common with Java scripts. Be aware, however, that the semicolon isn’t required when you use SQL statements in a Java program. The semicolon is required read more..

  • Page - 795

    Creating a SQL Database 771 Book VIII Chapter 3 Database for $100, Please ➝ 1 It’s common for a script that creates a database to begin with a drop database statement to delete any existing database with the same name. During testing, it’s common to delete and re-create the database, so you want to include this statement in your scripts. ➝ 2 This read more..

  • Page - 796

    Querying a Database 772 Note that the first time you run this script, you see an error message indicating that the movies database can’t be dropped because it doesn’t exist. You can safely ignore this error. Querying a Database As the name Structured Query Language suggests, queries are what SQL is all about. A query is an operation performed against one or more read more..

  • Page - 797

    Querying a Database 773 Book VIII Chapter 3 Database for $100, Please mysql> select title, year from movie order by year; +-------------------------+------+ | title | year | +-------------------------+------+ | It's a Wonderful Life | 1946 | | Young Frankenstein | 1974 | | Star Wars | 1977 | | The read more..

  • Page - 798

    Querying a Database 774 Here the select statement selects all the rows in which the year column is less than or equal to 1980. The results are ordered by the year column. Excluding rows Perhaps you want to retrieve all rows except those that match certain criteria. Here’s a query that ignores movies made in the 1970s (which is probably a good idea): mysql> select read more..

  • Page - 799

    Querying a Database 775 Book VIII Chapter 3 Database for $100, Please +--------------------+------+ | title | year | +--------------------+------+ | The Princess Bride | 1987 | +--------------------+------+ 1 row in set (0.01 sec) Using column functions What if you want a count of the total number of movies in the movie table or a count of the read more..

  • Page - 800

    Querying a Database 776 If the select statement includes a where clause, only the rows that match the criteria are included in the calculation. This statement finds out how many movies in the table were made before 1970: mysql> select count(*) from movie where year < 1970; +----------+ | count(*) | +----------+ | 1 | +----------+ 1 row in set (0.00 sec) The result read more..

  • Page - 801

    Querying a Database 777 Book VIII Chapter 3 Database for $100, Please +----------+-----------+--------------------+ | lastname | firstname | title | +----------+-----------+--------------------+ | Haskell | Eddie | Star Wars | | Haskell | Eddie | Glory | | Cleaver | Wally read more..

  • Page - 802

    Updating and Deleting Rows 778 This result set has a problem, however: Eddie Haskell and Wally Cleaver are listed twice. Wouldn’t it be nice if you could eliminate the duplicate rows? Your wish is granted in the next paragraph. You can eliminate duplicate rows by adding the distinct keyword in the select statement, as follows: mysql> select distinct lastname, firstname from read more..

  • Page - 803

    Updating and Deleting Rows 779 Book VIII Chapter 3 Database for $100, Please | 5 | Glory | 1989 | 14.95 | | 6 | The Game | 1997 | 14.95 | | 7 | Shakespeare in Love | 1998 | 19.95 | | 8 | Zombieland | 2009 | 18.95 | | 9 | The King's Speech read more..

  • Page - 804

    Updating and Deleting Rows 780 mysql> update movie set price = 18.95 where id = 8; Query OK, 1 row affected (0.44 sec) Rows matched: 1 Changed: 1 Warnings: 0 You can use a quick select statement to verify that the price was changed, as follows: mysql> select id, price from movie; +----+-------+ | id | price | +----+-------+ | 1 | 14.95 | | 2 | 16.95 | | 3 | 17.95 | read more..

  • Page - 805

    Updating and Deleting Rows 781 Book VIII Chapter 3 Database for $100, Please Here’s a select statement to verify that this update worked: mysql> select id, price from movie; +----+-------+ | id | price | +----+-------+ | 1 | 16.45 | | 2 | 18.65 | | 3 | 19.75 | | 4 | 18.65 | | 5 | 16.45 | | 6 | 16.45 | | 7 | 21.95 | | 8 | 20.85 | | read more..

  • Page - 806

    782 Book VIII: Files and Databases read more..

  • Page - 807

    Chapter 4: Using JDBC to Connect to a Database In This Chapter ✓ Configuring JDBC drivers ✓ Creating a connection ✓ Executing SQL statements ✓ Retrieving result data ✓ Updating and deleting data J DBC — Java Database Connectivity — is a Java featur e that lets you connect to almost any relational database system, execute SQL commands, and process the results, all from read more..

  • Page - 808

    Connecting to a Database 784 To do that, use the forName method of the Class class, specifying the package and class name of the driver. To register the MySQL connector, use this statement: Class.forName("com.mysql.jdbc.Driver"); To register the standard ODBC driver, use this statement instead: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Note that the forName method read more..

  • Page - 809

    Querying a Database 785 Book VIII Chapter 4 Using JDBC to Connect to a Database Putting it all together, here’s a method that returns a Connection object that connects to the movies database in MySQL: private static Connection getConnection() { Connection con = null; try { Class.forName("com.mysql.jdbc.Driver"); String url = read more..

  • Page - 810

    Querying a Database 786 Table 4-1 lists the methods of the Connection class and the Statement interface you use to execute queries. (You find out about the many methods of the ResultSet interface later in this chapter, in the section “Navigating through the result set.”) Table 4-1 Connection and Statement Methods Connection Class Method Description void close() Closes the connection. read more..

  • Page - 811

    Querying a Database 787 Book VIII Chapter 4 Using JDBC to Connect to a Database Executing a select statement The following snippet executes a select statement and gets the result set: Statement s = con.createStatement(); String select = "Select title, year, price " + "from movie order by year"; ResultSet rows = s.executeQuery(select); Here the result set is stored read more..

  • Page - 812

    Querying a Database 788 Table 4-3 Get Methods of the ResultSet Inter face Method Description BigDecimal getBigDecimal(String columnName) Gets the value of the specified column as a BigDecimal. BigDecimal getBigDecimal(int columnIndex) Gets the value of the specified column as a BigDecimal. boolean getBoolean(String columnName) Gets the value of the specified column as a boolean. read more..

  • Page - 813

    Querying a Database 789 Book VIII Chapter 4 Using JDBC to Connect to a Database Here’s a bit of code that gets the title, year, and price for the current row: String title = row.getString("title"); int year = row.getInt("year"); double price = row.getDouble("price"); The following code does the same thing, assuming the columns appear in order: String title read more..

  • Page - 814

    Querying a Database 790 { Movie m = getMovie(movies); String msg = Integer.toString(m.year); msg += ": " + m.title; msg += " (" + cf.format(m.price) + ")"; read more..

  • Page - 815

    Querying a Database 791 Book VIII Chapter 4 Using JDBC to Connect to a Database return con; } private static Movie getMovie(ResultSet movies) ➝70 { try { String title = movies.getString("Title"); int year = movies.getInt("Year"); read more..

  • Page - 816

    Updating SQL Data 792 ➝ 46 The getConnection method creates a Connection object to the database. Note that the user ID and password are hard-coded into this method. In a real application, you get this information from the user or from a configuration file. ➝ 70 The getMovie method extracts the title, year, and price from the current row and uses these read more..

  • Page - 817

    Using an Updatable RowSet Object 793 Book VIII Chapter 4 Using JDBC to Connect to a Database The getConnection method called at the start of this method is the same getConnection method in Listing 4-1. After a connection is created, a Statement object is created, and an insert statement is constructed using the values passed via the parameters. For example, if you pass id 3, last read more..

  • Page - 818

    Using an Updatable RowSet Object 794 Table 4-4 Methods for Scrollable Result Sets Method Description boolean absolute (int row) Moves the cursor to the given row number in this ResultSet object. void afterLast() Moves the cursor to the end of this ResultSet object, just after the last row. void beforeFirst() Moves the cursor to the front of this ResultSet object, just before read more..

  • Page - 819

    Using an Updatable RowSet Object 795 Book VIII Chapter 4 Using JDBC to Connect to a Database Deleting a row To delete a row from a result set, use one of the navigation methods in Table 4-4 to move to the row you want to delete, and then use the deleteRow method to delete the row. Here’s code that deletes the third row in the result set: try { read more..

  • Page - 820

    Using an Updatable RowSet Object 796 Update by Column Name Update by Column Index void updateDate(String columnName, Date value) void updateDate(int columnIndex, Date value) void updateDouble(String columnName, double value) void updateDouble(int columnIndex, double value) void updateFloat(String columnName, float value) void updateFloat(int columnIndex, float value) void updateInt(String columnName, read more..

  • Page - 821

    Chapter 5: Working with XML In This Chapter ✓ Understanding XML ✓ Defining structure with DTD ✓ Looking at DOM and SAX ✓ Reading a document into memory ✓ Navigating a document ✓ Getting attribute and element values I n this chapter, you find out how to work with Extensible Markup Language (XML) — the best thing to happen to computing since the invention of the vacuum tube read more..

  • Page - 822

    Defining XML 798 When XML is stored in a file, the file is usually given the extension .xml. Tags Like Hypertext Markup Language (HTML), XML uses tags to mark the data. Here’s a bit of XML that describes a book: <Book> <Title>Java All-In-One For Dummies</Title> <Author>Lowe</Author> </Book> This chunk of XML defines an element called Book, read more..

  • Page - 823

    Book VIII Chapter 5 W orking with XML Defining XML 799 Although XML superficially resembles HTML, you find two key differences: ✦ The tags used in HTML indicate the format of data that displays, whereas tags in an XML document indicate the meaning of the data. HTML has tags such as <B> and <I> that indicate whether data is bold or italic, for example. read more..

  • Page - 824

    Using a DTD 800 Listing 5-1: The movies.xml File <?xml version='1.0'?> <Movies> <Movie year="1946"> <Title>It's a Wonderful Life</Title> <Price>14.95</Price> </Movie> <Movie year="1974"> <Title>Young Frankenstein</Title> <Price>16.95</Price> </Movie> <Movie year="1977"> read more..

  • Page - 825

    Book VIII Chapter 5 W orking with XML Using a DTD 801 The main purpose of the DTD is to spell out the structure of an XML document so that users of the document know how to interpret it. Another, equally important use of the DTD is to validate the document to make sure that it doesn’t have any structural errors. If you create a Movies XML document read more..

  • Page - 826

    Using a DTD 802 Content Description #PCDATA Text data is allowed. ANY Any child elements are allowed. EMPTY No child elements of any type are allowed. The first ELEMENT tag in the DTD I show in Listing 5-2, for example, says that a Movies element consists of zero or more Movie elements. The second ELEMENT tag says that a Movie element consists of a Title element read more..

  • Page - 827

    Book VIII Chapter 5 W orking with XML Processing XML in Two W ays: DOM and SAX 803 Element The Attribute Value . . .  IDREF Must be the same as an ID value used elsewhere in the document. IDREFS Is a list of IDREF values separated by white space. Table 5-3 At tribute Defaults Default Optional or Required? #REQUIRED Required. #IMPLIED Optional. value Optional. This value is used read more..

  • Page - 828

    Reading a DOM Document 804 ✦ SAX: Stands for Simple API for XML. SAX is a read-only technique for processing XML that lets you read the elements of an XML document from a file and react to them as they come. Because SAX doesn’t require you to store an entire XML document in memory at one time, it’s often used for very large XML documents. In this section, read more..

  • Page - 829

    Book VIII Chapter 5 W orking with XML Reading a DOM Document 805 containing a filename as a parameter and returns a document object as its return value. Along the way, you find out what each class and method does. Here’s a method that reads an XML file into a DOM document: private static Document getDocument(String name) { try { read more..

  • Page - 830

    Reading a DOM Document 806 them to be ignored automatically. (If you don’t set this option, a node is created for each comment in the document, and because you can’t pre- dict when or where comments appear, your program has to check every node it processes to make sure that the node isn’t a comment.) ✦ The setIgnoringElementContentWhitespace method causes the read more..

  • Page - 831

    Book VIII Chapter 5 W orking with XML Reading DOM Nodes 807 Document doc = getDocument("movies.xml"); Here the movies.xml file is read, and a DOM document is created and assigned to the doc variable. Also note that you must provide three import statements to use the getDocument method, as follows: import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.*; read more..

  • Page - 832

    Reading DOM Nodes 808 Node getLastChild() Gets the last child of this node. int getNodeType() Gets an int that indicates the type of the node. The value can be one of the fields listed later in this table. String getNodeValue() Gets the value of this node, if the node has a value. Node getNextSibling() Gets the next sibling node. Node getPrevSibling() Gets the preceding read more..

  • Page - 833

    Book VIII Chapter 5 W orking with XML Reading DOM Nodes 809 ✦ Text: The text content of an element isn’t contained in the element itself, but in a Text node that’s stored as a child of the element. The Text inter- face has a few interesting methods you may want to look up, but for most applications, you just use the getNodeValue method inherited read more..

  • Page - 834

    Reading DOM Nodes 810 all the elements. Then you can use a for loop to access each element individually. Here’s a snippet of code that lists the name of each element: Element root = doc.getDocumentElement(); NodeList movies = root.getChildNodes(); for (int i = 0; i < movies.getLength(); i++) { Node movie = movies.item(i); System.out.println(movie.getNodeName()); } read more..

  • Page - 835

    Book VIII Chapter 5 W orking with XML Putting It All Together: A Program That Lists Movies 811 getAttribute method. The getNextSibling method returns a Node, however, not an Element. As a result, the compiler doesn’t let you assign the node to the movie variable unless you first cast it to an Element. Getting child element values You may be surprised to find that the read more..

  • Page - 836

    Putting It All Together: A Program That Lists Movies 812 1946: It's a Wonderful Life ($14.95) 1974: Young Frankenstein ($16.95) 1977: Star Wars ($17.95) 1987: The Princess Bride ($16.95) 1989: Glory ($14.95) 1997: The Game ($14.95) 1998: Shakespeare in Love ($19.95) 2009: Zombieland ($18.95) 2010: The Kings Speech ($17.95) 2013: Star Trek Into Darkness ($19.95) Listing 5-3: Reading an XML read more..

  • Page - 837

    Book VIII Chapter 5 W orking with XML Putting It All Together: A Program That Lists Movies 813 factory.setIgnoringElementContentWhitespace(true); factory.setValidating(true); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new InputSource(name)); read more..

  • Page - 838

    Putting It All Together: A Program That Lists Movies 814 Because all the code in this program appears elsewhere in this chapter, the following paragraphs just provide a simple description of what each method in this program does: ➝ 1 Wow, that’s a lot of packages to import. Too bad that Java’s designers couldn’t have put all these XML classes in one big read more..

  • Page - 839

    You can find an interesting programming challenge that requires use of many of the programming techniques covered in this minibook at www.dummies.com/ extras/javaaio. The challenge for this minibook requires you to take a trip back into the 1930s and create a program that actually simulates the operation of one of the very first hypothetical computers, known as a Turing read more..

  • Page - 840

    Contents at a Glance Contents at a Glance Chapter 1: Fun with Fonts and Colors ...........................815 Working with Fonts ...........................................................................................................817 Working with Color ...........................................................................................................823 Chapter 2: Drawing Shapes ...................................831 Getting a read more..

  • Page - 841

    Chapter 1: Fun with Fonts and Colors In This Chapter ✓ Setting the font of a text control ✓ Finding out what fonts are available ✓ Playing with colors ✓ Working with system colors ✓ Setting foreground and background colors I n this chapter, I look at ways of dressing up the text that appears in Swing controls. In particular, I show you how to change the read more..

  • Page - 842

    Working with Fonts 818 Here, the font style is plain, and the size is 14 points. Realizing that the Font class constructor doesn’t really create a font is impor- tant. Instead, this constructor creates a Font object that represents a font installed on your computer. Creating a Font object with the name Comic Strip, for example, doesn’t create a font named Comic read more..

  • Page - 843

    Book IX Chapter 1 Fun with Fonts and Colors Working with Fonts 819 Using font styles Fonts can have one of four styles: plain, bold, italic, and bold italic. To set the font style, use the following three constants as the second parameter of the Font class constructor: Font.BOLD Font.ITALIC Font.PLAIN Here’s how you create a Font object for 24-point JSL Ancient Bold: read more..

  • Page - 844

    Working with Fonts 820 JButton b1 = new JButton("Jolly"); b1.setFont(null); panel1.add(b1); JButton b2 = new JButton("Roger"); b2.setFont(null); panel1.add(b2); In this example, both buttons have their fonts set to null, so they both pick up the font of their parent, panel1. Getting a list of available fonts If you want to let the user pick a font, get a list of all read more..

  • Page - 845

    Book IX Chapter 1 Fun with Fonts and Colors Working with Fonts 821 Figure 1-1: The Fonts program in action. Listing 1-1: A Program That Plays with Fonts import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Fonts extends JFrame { public static void main(String [] args) { new Fonts(); } private read more..

  • Page - 846

    Working with Fonts 822 Listing 1-1 (continued) boldCheck = new JCheckBox("Bold"); ➝50 boldCheck.addActionListener(e –> updateText()); controlPanel.add(boldCheck); italCheck = new JCheckBox("Ital"); ➝54 italCheck.addActionListener(e –> updateText() ); controlPanel.add(italCheck); read more..

  • Page - 847

    Book IX Chapter 1 Fun with Fonts and Colors Working with Color 823 ➝ 35 A panel is used to hold the two combo-box and two check box controls. ➝ 37 These lines create the font combo box (called Family) and add it to the panel. ➝ 42 These lines create the Size combo box and add it to the panel. The combo box is filled from an array of read more..

  • Page - 848

    Working with Color 824 Here a color with full red, full green, and no blue is created, resulting in bright yellow. If all three constituent colors are 0, the resulting color is black. If all three are 255, the result is white. And if all three values are the same, falling some- where between 0 and 255, the result is a shade of gray. Because color numbers can be read more..

  • Page - 849

    Book IX Chapter 1 Fun with Fonts and Colors Working with Color 825 ✦ If you call the Color constructor with a parameter that’s less than 0 or greater than 255, IllegalArgumentException is thrown. As a result, check the parameter values before calling the constructor. ✦ The Color class provides an alternative constructor that lets you set the constituent read more..

  • Page - 850

    Working with Color 826 Field Description static SystemColor info Background color used for tooltips static SystemColor infoText Text color used for tooltips static SystemColor menu Background color used for menus static SystemColor menuText Text color used for menus static SystemColor textHighlight Background color used for highlighted text static SystemColor textHighlightText Text color used read more..

  • Page - 851

    Book IX Chapter 1 Fun with Fonts and Colors Working with Color 827 As with fonts, you can force a component to use the color of its container by setting the color to null, like this: textLabel.setForeground(null); Then if you add textLabel to a panel, the label uses the panel’s foreground color. Using a color chooser The JColorChooser class creates a standardized dialog read more..

  • Page - 852

    Working with Color 828 ✦ The RGB tab lets the user specify the red, green, and blue values for the color. ✦ The CMYK tab lets the user specify color as a combination of cyan, magenta, yellow, and black. Note: Before Java 1.7, the Choose a Color dialog box had just three tabs for choosing colors: Swatches, HSB, and RGB. (The HSB tab was the same as the read more..

  • Page - 853

    Book IX Chapter 1 Fun with Fonts and Colors Working with Color 829 public class ColorChooser extends JFrame { public static void main(String [] args) { new ColorChooser(); } private JLabel sampleText; ➝12 private JButton chooseButton; public ColorChooser() { this.setSize(300,100); read more..

  • Page - 854

    830 Book IX: Fun and Games read more..

  • Page - 855

    Chapter 2: Drawing Shapes In This Chapter ✓ Creating basic shapes such as lines, rectangles, and ellipses ✓ Setting the fill color and stroke thickness ✓ Creating shapes you can see through ✓ Creating gradient fills ✓ Rotating shapes ✓ Drawing text onscreen W ere you one of those kids who, way back in school, passed away the boring hours of algebra class by read more..

  • Page - 856

    Drawing Shapes 832 The graphics context object is created from a class called Graphics2D. Just to be ornery, however, the paint method is passed an object of the Graphics class, from which Graphics2D is derived. As a result, the very first thing you need to do in your paint method is cast the Graphics parameter to a Graphics2D object, like this: public void read more..

  • Page - 857

    Book IX Chapter 2 Drawing Shapes Drawing Shapes 833 Tweaking a drawn shape Here are some ways to tweak a shape: ✦ Change the color before you draw the shape. Call the setColor method, like this: g2.setColor(Color.RED); Here the color is changed to RED. ✦ Change the thickness of the line used to draw the shape. Call setStroke, and pass it a new instance of read more..

  • Page - 858

    Drawing Shapes 834 I use the basic structure of this program throughout this chapter to illustrate how graphics programming works. In particular, whenever you see code examples that call methods on an object named g2, you can assume that the code appears inside a paint method, such as the one shown in this listing. Listing 2-1: The SimpleShape Program import javax.swing.*; read more..

  • Page - 859

    Book IX Chapter 2 Drawing Shapes Creating Shapes 835 The following paragraphs hit the important points of this program: ➝ 1 The program imports three packages: java.swing, java.awt, and java.geom. Most programs that draw graphics need at least these three classes, and some features may require you to import additional classes. ➝ 5 The SimpleShape class extends JFrame. It read more..

  • Page - 860

    Creating Shapes 836 Table 2-1 Classes That Represent Basic Shapes Class Constructor Description Arc2D.Float(float x, float y, float w, float h, float start, float extent, int type) Creates an arc, which is a segment of an ellipse defined by the first four parameters. start is the starting angle of the arc in degrees, extent is the angular extent of the read more..

  • Page - 861

    Book IX Chapter 2 Drawing Shapes Creating Shapes 837 Figure 2-2: A bunch of shapes. Creating lines The most basic type of shape is a line, created with the Line2D.Float class. To create a line, you specify the x and y coordinates of the start and end of the line, as in this example: Shape line1 = new Line2D.Float(0, 0, 100, 200); This code creates a read more..

  • Page - 862

    Creating Shapes 838 Here the rectangle starts at (10, 10). Its width is 60, and its height is 80. Java 2D also provides a RoundRectangle2D class that lets you create rectangles with rounded corners. The constructor for this class takes two additional parameters that specify the width and height of the arc used to draw the corners. Here’s the rounded rectangle in read more..

  • Page - 863

    Book IX Chapter 2 Drawing Shapes Creating Shapes 839 Creating arcs Another useful type of shape is an arc, which is a segment of an ellipse. To create an arc, you supply the bounding rectangle that contains the ellipse. Here are the parameters you need to specify: ✦ The starting angle for the arc: This angle is expressed in degrees. 0 is due east (or 3:00 read more..

  • Page - 864

    Creating Shapes 840 constructor, so the code that creates the shapes is executed only once. Then, in the paint method, an enhanced for loop is used to draw each shape in the ArrayList. This technique is especially handy for programs that let the user draw shapes. Each time the user draws a new shape, you just add the shape to the ArrayList. Then, whenever the read more..

  • Page - 865

    Book IX Chapter 2 Drawing Shapes Filling Shapes 841 // an ellipse s = new Ellipse2D.Float(110, 110, 80, 40); shapes.add(s); // another ellipse s = new Ellipse2D.Float(210, 110, 40, 80); shapes.add(s); read more..

  • Page - 866

    Filling Shapes 842 There’s more to filling than solid colors, however. In the following sections, you find out how to create fills that are partially transparent and fills that gradually fade from one color to another. Drawing transparently Java 2D lets you create transparent shapes by specifying a compositing rule. A compositing rule can do more than just set the read more..

  • Page - 867

    Book IX Chapter 2 Drawing Shapes Filling Shapes 843 Constructor Description GradientPaint(float x1, float y1, Color c1, float x2, float y2, Color c2, boolean cyclic) Creates the same gradient as the first constructor, but if the cyclic parameter is true, the gradient pattern repeats infinitely beyond the two points. GradientPaint(Point2D p1, Color c1, Point2D p2 Color read more..

  • Page - 868

    Rotating and Translating 844 Color.BLACK, x, y+h-35, Color.WHITE, true); GradientPaint gp4 = new GradientPaint(x+35, y+35, Color.BLACK, x+w-35, y+h-35, Color.WHITE, true); Using this code as a starting point, you can devise many variations to create your own fills. Rotating and Translating This section describes two methods of the Graphics2D class that modify read more..

  • Page - 869

    Book IX Chapter 2 Drawing Shapes Rotating and Translating 845 The translate method The translate method takes two parameters — namely, the x and y coor- dinates of the point you want to designate as the center of the universe. For many graphics applications, translating to the center of the component is useful, so (0, 0) is in the middle of the component. read more..

  • Page - 870

    Drawing Text 846 Here’s an example from a paint method that creates an ellipse and then draws it several times at different rotations: int x = 50; int y = 75; int width = 200; int height = 100; Shape r1 = new Ellipse2D.Float(x, y, width, height); for (int angle = 0; angle <= 360; angle += 45) { g2.rotate(Math.toRadians(angle), x + width/2, read more..

  • Page - 871

    Book IX Chapter 2 Drawing Shapes Letting the User Draw on a Component 847 The current stroke, color, translation, and rotation apply to the text that’s drawn, as well as to the current font that you specify via the setFont method. This method accepts a Font object, like this: g2.setFont(new Font("Times New Roman", Font.PLAIN, 36)); Here the font is set to 36-point read more..

  • Page - 872

    Letting the User Draw on a Component 848 MouseEvent Method Description int getButton() This method gets the mouse button that has been clicked, pressed, or released. The result can be BUTTON1, BUTTON2, BUTTON3, or NOBUTTON. int getClickCount() This method gets the number of clicks to determine whether the user double- or triple-clicked. Point getPoint() This method gets the mouse read more..

  • Page - 873

    Book IX Chapter 2 Drawing Shapes Letting the User Draw on a Component 849 ✦ Also when the user releases the mouse button, you clear the two mouse locations that were saved while the user was drawing the rectangle. That way, the paint method knows not to draw the temporary rectangle. Here are a few other points to know about this program before I dive into the code: read more..

  • Page - 874

    Letting the User Draw on a Component 850 public class DrawingBoard extends JFrame { public static void main(String [] args) ➝8 { new DrawingBoard(); } public DrawingBoard() ➝13 { this.setSize(300, 300); this.setTitle("The Drawing Board"); read more..

  • Page - 875

    Book IX Chapter 2 Drawing Shapes Letting the User Draw on a Component 851 RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // draw background grid g2.setPaint(Color.LIGHT_GRAY); for (int i = 0; i < getSize().width; i += 10) read more..

  • Page - 876

    Letting the User Draw on a Component 852 The following paragraphs provide a road map through this program: ➝ 8 The main method creates an instance of the DrawingBoard class. ➝ 13 The constructor for the DrawingBoard class initializes the frame in the usual way, adding a new instance of a JComponent class named PaintSurface. ➝ 24 The PaintSurface class read more..

  • Page - 877

    Book IX Chapter 2 Drawing Shapes Letting the User Draw on a Component 853 ➝ 103 This if statement draws the temporary rectangle while the user is dragging the mouse. If either startDrag or endDrag is null, the rectangle isn’t drawn. ➝ 113 makeRectangle is a helper method that creates a Rectangle2D.Float object, given the points of two opposite corners. It read more..

  • Page - 878

    854 Book IX: Fun and Games read more..

  • Page - 879

    Chapter 3: Using Images and Sound In This Chapter ✓ Displaying images in Swing components ✓ Drawing images directly on a panel ✓ Scaling images ✓ Using a file chooser to pick an image ✓ Adding annoying sound effects and music to your programs S o far in this book, all the Swing applications have been pretty boring. They’ve had plenty of labels, text fields, read more..

  • Page - 880

    856 Using Images Using Images An image is a file that contains a picture. Java supports pictures in several formats, including these: ✦ GIF: GIF is Graphics Interchange Format, commonly used for small images such as those used as button icons and the like. ✦ JPEG: The Joint Photographic Experts Group (hence the name JPEG) devised this format to store photographic read more..

  • Page - 881

    Book IX Chapter 3 Using Images and Sound Using the ImageIcon Class 857 Table 3-1 Classes for Working with ImageIcon Objects ImageIcon Constructor and Method Description ImageIcon(String filename) Creates an ImageIcon object from the file indicated by the specified filename. ImageIcon(URL url) Creates an ImageIcon object from the file indicated by the specified URL. Image getImage() Gets the read more..

  • Page - 882

    Using the ImageIcon Class 858 To put everything together, here’s a complete application that displays the HalfDome.jpg image in a frame: import javax.swing.*; public class PictureApp extends JFrame { public static void main(String [] args) { new PictureApp(); } public PictureApp() { this.setTitle("Picture read more..

  • Page - 883

    Book IX Chapter 3 Using Images and Sound Using the Image Class 859 The following code produces the button shown in the margin: JButton openButton; ImageIcon openIcon = new ImageIcon("OpenIcon.gif"); openButton = new JButton(openIcon); You can also create buttons with both text and an icon. I created the button shown in the margin with this code: openButton = new read more..

  • Page - 884

    Using the Image Class 860 Table 3-2 Classes for Working with Image Objects Image Class Method and Field Description Image getScaledInstance (int x, int x, int hints) Gets an Image object that has been scaled according to the x and y parameters. If  either x or y is negative, the aspect ratio of the image is preserved. The hints param- eter can be one of read more..

  • Page - 885

    Book IX Chapter 3 Using Images and Sound Using the Image Class 861 To create an image from an ImageIcon object, you first create an ImageIcon object as described in the preceding section. Then you can use the getImage method to extract the Image from the ImageIcon, as in this example: ImageIcon picIcon = new ImageIcon("c:\\HalfDome.jpg"); Image picImage = read more..

  • Page - 886

    Using the Image Class 862 Another form of the drawImage method lets you set the size at which you want the image to be drawn, like this: g.drawImage(img, 0, 0, 200, 200, this); Here the image is drawn in a 200 × 200–pixel r ectangle starting in the top-left corner of the panel. Viewing an Image example To show how the elements presented in the preceding two sections work read more..

  • Page - 887

    Book IX Chapter 3 Using Images and Sound Using the Image Class 863 Figure 3-2: The Picture- Frame application in action. Listing 3-1: The PictureFrame Application import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.io.*; public class PictureFrame extends JFrame { Image img; ➝8 JButton getPictureButton; public static void main(String [] read more..

  • Page - 888

    Using the Image Class 864 { Toolkit kit = Toolkit.getDefaultToolkit(); img = kit.getImage(file); img = img.getScaledInstance( 300, -1, Image.SCALE_SMOOTH); this.repaint(); } } private String read more..

  • Page - 889

    Book IX Chapter 3 Using Images and Sound Playing Sounds and Making Music 865 The following paragraphs hit the highlights of this program: ➝ 8 The img variable is declared here so that the class can access it. ➝ 22 In the frame class constructor, a new instance of the PicturePanel class is created and added to the center of the frame. ➝ 25 Next, read more..

  • Page - 890

    Playing Sounds and Making Music 866 An audio file is represented by an object that implements the AudioClip interface, whose methods are listed in Table 3-3. As you can see, this inter- face is simple: You can play a sound once, play it in a loop, and stop playing the sound. Note that when you play or loop a sound, your program doesn’t wait for the sound to read more..

  • Page - 891

    Book IX Chapter 3 Using Images and Sound Playing Sounds and Making Music 867 Listing 3-2: The MouseClicker Program import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.applet.*; import java.net.URL; public class MouseClicker extends JFrame { AudioClip click; public static void main(String [] args) { new MouseClicker(); } read more..

  • Page - 892

    868 Book IX: Fun and Games read more..

  • Page - 893

    Chapter 4: Animation and Game Programming In This Chapter ✓ Using threads to control animation ✓ Creating a bouncing ball ✓ Creating a whole room full of bouncing balls ✓ Devising a simple Pong-like game B ecause of its powerful drawing capabilities, Java lends itself especially well to creating game programs — especially games that ar e created as applets so they can read more..

  • Page - 894

    Working with Sprites 870 In some cases, the sprite may have a series of images associated with it. If the sprite is a little person who walks around in your game world, you might have several images representing him walking left and right or moving in various stages of his little stride. Then you can put these images in an array and use an index variable to keep read more..

  • Page - 895

    Working with Sprites 871 Book IX Chapter 4 Animation and Game Programming Figure 4-1: The BallRoom applet in action. Listing 4-1: The BallRoom Applet import java.applet.*; import java.awt.*; import javax.swing.*; import java.awt.geom.*; public class BallRoom extends JApplet ➝6 { public static final int WIDTH = 350; public static final int HEIGHT = 300; read more..

  • Page - 896

    Understanding Double Buffering 872 { Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); x_pos += 1; // move ball right one pixel Shape ball = new Ellipse2D.Float( read more..

  • Page - 897

    Bouncing the Ball 873 Book IX Chapter 4 Animation and Game Programming draw shapes directly to the component. Instead, you create an offscreen image object called a buffer and draw the shapes to it. Then, when all the shapes are drawn, you transfer the entire buffer image to the component. Fortunately, any drawing you do on a Swing component is automatically double-buffered. read more..

  • Page - 898

    Bouncing the Ball 874 shown in Listing 4-1. Because the BallRoom class is unchanged, I’ve omitted it here so you can focus on the changes to the PaintSurface class.) Listing 4-2: A Bouncing Version of the PaintSur face Class class PaintSurface extends JComponent { int x_pos = 0; ➝3 int y_pos = 0; int x_speed = 1; int y_speed = 2; read more..

  • Page - 899

    Bouncing a Bunch of Balls 875 Book IX Chapter 4 Animation and Game Programming ➝ 21 After the x and y speed values are adjusted for bounces, the next two statements move the ball. If x_speed is a positive number, the ball moves right; if it’s negative, the ball moves left. Similarly, if y_speed is positive, the ball moves down; if it’s negative, the read more..

  • Page - 900

    Bouncing a Bunch of Balls 876 if (super.y < 0 || super.y > height - d) y_speed = -y_speed; super.x += x_speed; super.y += y_speed; } } The following paragraphs point out the highlights of this program: ➝ 1 Because a ball is essentially an ellipse with a few additional characteristics, read more..

  • Page - 901

    Bouncing a Bunch of Balls 877 Book IX Chapter 4 Animation and Game Programming { for (int i = 0; i < 10; i++) balls.add(new Ball(20)); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint( read more..

  • Page - 902

    Creating Collidable Balls 878 Creating Collidable Balls The balls created by the Ball class shown earlier in this chapter have one slightly unrealistic behavior: They’re transparent to one another. If two balls happen to arrive at the same place at the same time, they simply pass right through each other without noticing. If you want to create balls that bounce off one read more..

  • Page - 903

    Creating Collidable Balls 879 Book IX Chapter 4 Animation and Game Programming if (super.x < 0) ➝40 { super.x = 0; x_speed = Math.abs(x_speed); } else if (super.x > width - d) { super.x = width - d; read more..

  • Page - 904

    Playing Games 880 ➝ 30 If a collision is detected, the x and y speed values of the two balls are swapped. Not only do the balls bounce away from each other, but also the slower ball picks up speed and the faster ball slows down. ➝ 37 A break statement is executed if a collision is detected to prevent detecting collisions with more than one ball. read more..

  • Page - 905

    Playing Games 881 Book IX Chapter 4 Animation and Game Programming Shape paddle = new Rectangle2D.Float( paddle_x, 360, 60, 8); g2.setColor(Color.BLACK); g2.fill(paddle); The paddle is drawn as a 60 × 8–pixel black r ectangle. When the user moves the mouse pointer over the applet, the paddle moves along with the mouse pointer. To read more..

  • Page - 906

    Playing Games 882 Listing 4-6: The NotPong Program import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.awt.geom.*; import java.util.concurrent.*; public class NotPong extends JApplet ➝8 { public static final int WIDTH = 400; public static final int HEIGHT = 400; private PaintSurface canvas; public void init() ➝16 read more..

  • Page - 907

    Playing Games 883 Book IX Chapter 4 Animation and Game Programming { public void mouseMoved(MouseEvent e) { if (e.getX() - 30 - paddle_x > 5) english = 1.5f; read more..

  • Page - 908

    Playing Games 884 public int x_speed, y_speed; private int d; private int width = NotPong.WIDTH; private int height = NotPong.HEIGHT; public Ball(int diameter) { super((int)(Math.random() * (NotPong.WIDTH - 20) + 1), 0, diameter, diameter); this.d = diameter; read more..

  • Page - 909

    Playing Games 885 Book IX Chapter 4 Animation and Game Programming ➝ 52 An array of Color objects and an index variable are used so that the ball can be drawn with several colors. Each time the user hits the ball with English applied, the index variable is incremented so that the ball is drawn with a different color. ➝ 57 The constructor for the read more..

  • Page - 910

    886 Book IX: Fun and Games read more..

  • Page - 911

    Symbols and Numerics -- (decrement operator), 96, 101–103 - (minus sign), 95, 233 -? option, 28 ! operator, 135 != operator, 124 # (hash symbol), 233 $ (dollar sign), 52 % (percent symbol), 96, 774 %= operator, 105 & operator, 135–136, BC2:7, BC2:8–BC2:10 &nbsp; (HTML entity), 691 ( ) parentheses, 126, 509–510 * (asterisk), 53, 95, 508, 773, 801 *= operator, 105 . (dot) read more..

  • Page - 912

    Java All-in-One For Dummies, 4th Edition 888 activeCount() method, 450, 473 adapter class defined, 597 for event listeners, 598 add() method ArrayList class, 397 BigDecimal class, 555 DefaultListModel class, 638 DefaultMutableTreeNode class, 643 JApplet class, 677 JFrame class, 572 JMenu class, BC3:3 JMenuBar class, BC3:2 JPanel class, 577 LinkedList class, 411, 415 addActionListener() read more..

  • Page - 913

    Index 889 increment and decrement, 101–103 overview, 95–97 standard assignment operator, 103–105 unary operators, 100–101 ArithmeticException, 202, 205, 208, 278, 560 ArrayList class constructors, 397 creating, 399–400 elements accessing, 401–402 adding, 400–401 deleting, 406–407 updating, 404–406 generic collections, 422 LinkedList class versus, 410–411 methods, 397–399 Object class and, read more..

  • Page - 914

    Java All-in-One For Dummies, 4th Edition 890 B \b escape sequence, 74, 352 backslash ( \ ), 74, 352, 509, 512, 722 BallRoom applet, 871–872 bang, defined, 135 BartClient program, 491–494 BartServer program accepting multiple client connections, 494–497 BartQuote class, 486–488 code for, 488–491 overview, 485–486 base 10 number system, 119 base class, 229, 262 baseline, 846 Basic Java read more..

  • Page - 915

    Index 891 Border layout manager BorderLayout class, 655–656 defined, 652 BorderFactory class, 619 borders (Swing) JComponent class and, 618 overview, 617–619 Pizza Order program, 623–627 BOTH field, 662 bouncing ball example multiple balls animating randomly, 876–877 Ball class, 875–876 collidable balls, 877–880 single ball, 873–875 bounds checking, 15 Box class, 657–658 Box layout read more..

  • Page - 916

    Java All-in-One For Dummies, 4th Edition 892 caret ( ^ ), 137–138, 507, BC2:7, BC2:11 case keyword, 173 case-sensitivity identifiers, 52 Java keywords, 47 cast operator, 82 CastClassException, 274 casting types. See type casting catch block, 204–205. See also try/catch statement catching exceptions checked, 214–215 defined, 202 displaying message, 210 examples, 205–207 Exception class, read more..

  • Page - 917

    Index 893 overview, 236, 244 subclasses and, 266 counting instances in, 256–257 creating objects, 56 data types and, 14 declaring, 235 defined, 10 Delegation pattern, 265 designing for programs, 230–231 determining type, 273–274 diagrams arrows, 234 drawing, 232–233 overview, 231–232 directory for, 696 fields overview, 236, 239 static, 254–255 final keyword, 271 importing entire packages, 90 read more..

  • Page - 918

    Java All-in-One For Dummies, 4th Edition 894 clone() method ArrayList class, 397, 424 deep copies, 313–318 defined, 299, 300 LinkedList class, 412 reason for, 309 shallow copies, 312–313 using, 309–312 Cloneable interface, 312–313, 318 CloneNotSupportedException, 312–313, 318 close() method BufferedReader class, 743 Connection class, 785–786 DataOutputStream class, 762, 764 read more..

  • Page - 919

    Index 895 buttons disabling, 582 displaying images on, 859 events for, 580 handling events for, 587–588 JButton class, 580–582 text for, 581 visibility of, 582 check boxes JCheckBox class, 612–615 Pizza Order program, 623–627 combo boxes creating, 631–632 defined, 629 events, 633 getting items from, 632 JComboBox class, 630 frames adding components to, 577–578 default layout manager, read more..

  • Page - 920

    Java All-in-One For Dummies, 4th Edition 896 concurrency, 462–466. See also threading Conditional And operator, 135–136 conditional operator, 140 Conditional Or operator, 136–137 connect() method, 483 Connection class, 785 console defined, 43 lining up output in, 544 Console View, Eclipse, BC1:3 const keyword, 47 constants, 107. See also final variables constructor anonymous classes and, read more..

  • Page - 921

    Index 897 -d option, 26 -D option, 28 DARK_GRAY constant, 824 darker() method, 824 data layer, 231 data types boolean type overview, 74 primitive data types, 69 wrapper class, 74–75 boxing, 82 byte type primitive data types, 69 size of, 70 switch statement cases, 172 wrapper class, 74–75 casting automatic numeric conversions, 80–81 inherited classes, 271–273 operands, 96 overview, read more..

  • Page - 922

    Java All-in-One For Dummies, 4th Edition 898 short type integer overflow, 118 primitive data types, 69 size of, 70 switch statement cases, 172 wrapper class, 74–75 strings combining, 78 converting, 78–80 declaring, 77 strongly typed language, 68 unboxing, 82 using interface as, 286–287 value types, 69 varchar type (SQL), 771 wrapper classes, 74–75 databases connecting to, 783–785 read more..

  • Page - 923

    Index 899 default package, 334 DefaultListModel class, 637–638 DefaultMutableTreeNode class overview, 643 using, 644 Delegation Event Model, 324 Delegation pattern, 265 delete() method File class, 720 Paths class, 734 StringBuilder class, 364 delete statement (SQL) defined, 769 executing, 792–793 using, 778–779 deleteCharAt() method, 364 deleteIfExists() method, 734 deleteRow() method, read more..

  • Page - 924

    Java All-in-One For Dummies, 4th Edition 900 Document Type Definition. See DTD DOCUMENT_NODE field, 808 documentation for classes, 29 Java language specification, 31–32 Java SE API, 30–31 on Oracle Java website, 30 DocumentBuilder class creating DOM document, 806 creating object, 805, 814 package, 807 DocumentBuilderFactory class configuring, 805–806 creating object, 805 package, 807 read more..

  • Page - 925

    Index 901 DTD (Document Type Definition) overview, 800–803 validating document, 806 dump, defined, 201 dynamic menus, BC3:7 -ea option, 28 E EAST field, 656, 662 Ebay, 683 Eclipse adding class file, BC1:10–BC1:13 bonus chapter online, 33 creating project, BC1:5–BC1:10 debugging breakpoints, BC1:17, BC1:19–BC1:20 overview, BC1:15–BC1:16 stepping through, BC1:16–BC1:17 variables, BC1:18–BC1:19 read more..

  • Page - 926

    Java All-in-One For Dummies, 4th Edition 902 ERA value, 542 Error class, 277–278 error messages case-sensitivity and, 47–48 java command-line program, 28 in TextPad, clicking on, 37 ERROR_OPTION field, 730 errorPage attribute, 705 -esa option, 28 escape sequences defined, 73 listing of, 352 regular expression escape character, 509 events class methods, 584–587 ClickMe program, 589–591 read more..

  • Page - 927

    Index 903 factorial of integer defined, 515 nonrecursive method, 515–516 recursive method, 516–517 factory class, 619 factory methods, 619 Factory pattern, 619 fields class body, 236 in interface, 287–288 for objects, 227 overview, 239 static, 254–255 File class. See also Paths class binary streams and, 754 character streams and, 742 creating object, 722 directories getting contents of, read more..

  • Page - 928

    Java All-in-One For Dummies, 4th Edition 904 floor() method, 113–114 FLOOR value, 560 Flow layout manager defined, 652 overview, 653–654 FlowLayout class defined, 582 using, 654 flush() method DataOutputStream class, 762, 764 PrintWriter class, 749, 751 FocusAdapter class, 598 FocusEvent class, 584 focusGained() method, 587 FocusListener interface, 584, 587, 598 focusLost() method, read more..

  • Page - 929

    Index 905 generics creating class, 423–424 diamond operator, 432–433 Java 1.5, 396 purpose of, 409 queue class, 429–432 reason for, 422 stack class, 424–427 wildcard parameters, 427–428 get() method ArrayList class, 398 DefaultListModel class, 638 LinkedList class, 412 GET method (HTTP), 692, 695 getAddress() method, 479 getAllByName() method, 479, 480, 482 getAlpha() method, 824 read more..

  • Page - 930

    Java All-in-One For Dummies, 4th Edition 906 getSelectedFile() method, 728, 730 getSelectedFiles() method, 728 getSelectedIndex() method, 630, 635, 637 getSelectedIndexes() method, 635 getSelectedItem() method, 630, 632, 637 getSelectedValue() method, 635, 636 getSelectedValues() method, 635, 636 getSelectionModel() method, 646–647 getShort() method, 788 getState() method, BC3:8 getString() read more..

  • Page - 931

    Index 907 creating dialog box, 729–730 getting selected file, 730–731 JFileChooser class, 728–729 overview, 727 using file filters, 731–733 fonts example program, 820–823 Font class, 817–818 getting list of available, 820 logical font names, 818 name parameter, 818 setting for component, 819–820 styles, 819 frames class methods, 572–573 positioning, 575–576 handling events, 587–588 read more..

  • Page - 932

    Java All-in-One For Dummies, 4th Edition 908 hexadecimal numbers Calculator program (Windows), BC2:9 converting integers to, BC2:5–BC2:6 overview, BC2:4–BC2:5 hints, rendering, 832 horizontal box, 656 HORIZONTAL field, 662 HORIZONTAL_SCROLLBAR_ALWAYS field, 611 HORIZONTAL_SCROLLBAR_AS_NEEDED field, 611 HORIZONTAL_SCROLLBAR_NEVER field, 611 host names defined, 477 InetAddress class, 479–480 looking read more..

  • Page - 933

    Index 909 nesting, 129–132 overview, 126–128 IllegalArgumentException, 202, 630, 825 ImageObserver interface, 861 images add to swing Image class creating object, 860–861 drawing object, 861–862 overview, 859–860 ImageIcon class in applet, 859 overview, 856–857 in Swing application, 857–859 PictureFrame program, 862–865 scaling, 862 supported formats, 856 imageUpdate() method, 861 immutable read more..

  • Page - 934

    Java All-in-One For Dummies, 4th Edition 910 defined, 326–327 example, 328–330 defined, 237 example, 322–325 listening for events using, 591–593 overview, 321–322 static, 325–326 inner if statement, 129 input servlets, 695–696 text fields class methods, 602–603 Namer program, 603–605 numeric entry, 605–607 validating creating class for, 607–608 using loop, 152–154 input stream, read more..

  • Page - 935

    Index 911 IntStream interface, 438–440 intValue() method, 563 invoking methods, 181 I/O (input/output) streams classes documentation, 742 overview, 741 System object, 86–87 IOException, 202, 494, 688, 720, 755–756, 806 IP (Internet Protocol) addresses, 476 isAfter() method, 538, 541 isBefore() method, 538, 541 isBound() method ServerSocket class, 485 Socket class, 484 isClosed() method read more..

  • Page - 936

    Java All-in-One For Dummies, 4th Edition 912 Java 2 Standard Edition (J2SE), 18 Java 2D, 831 Java 8 bulk data operations, 435 Data-Time API, 529 default methods, 292–295 lambda expressions, 330–331 Java API abstract classes, 284 disadvantages of, 16 documentation, 30–31 importing classes, 60 overview, 10 Java archive files. See JAR files java command-line program error messages, 28 read more..

  • Page - 937

    Index 913 creating object, 631–632 overview, 630 JComponent class borders and, 618 Swing API, 571 JDBC (Java Database Connectivity). See also SQL connecting to database, 783–785 executing queries, 787 executing updates, 792–793 ListMovie program, 789–792 MySQL driver, 783 querying database, 785–786 result set getting data from, 787–789 navigating, 787 SQL and, 767 updatable result set read more..

  • Page - 938

    Java All-in-One For Dummies, 4th Edition 914 sample page for, BC4:8–BC4:10 setting property values, BC4:7–BC4:8 tags, BC4:5 overview, 703–704 scriptlets, 708–710 .jsp extension, 703 jsp:getProperty tag, BC4:5–BC4:6 JSpinner class, 639–640 jsp:setProperty tag, BC4:5–BC4:8 jsp:useBean tag, BC4:5–BC4:6, BC4:10 JTextArea class overview, 609–611 scrollbars and, 609 JTextField class numeric read more..

  • Page - 939

    Index 915 LIGHT_GRAY constant, 824 limit() method, 439 line breaks, 50 Line2D class, 836, 837 lines, drawing, 837 LinkedIn, 683 LinkedList class adding items, 415–417 ArrayList class versus, 410–411 creating, 415 efficiency of, 410–411 generic queue class, 429–432 generic stack class, 425–427 methods, 411–414 overview, 410–411 removing items, 419 retrieving items, 417–418 updating read more..

  • Page - 940

    Java All-in-One For Dummies, 4th Edition 916 guessing game example, 165–167 overview, 164 using arrays with, 372 validating user input using, 152–154 while loop, 144–145 low-level events, 585 M M format pattern, 543 m format pattern, 543 M option, 339 m option, 339 MAGENTA constant, 824 mail servers, 476 main() method applets and, 675 C/C++, 11 in Hello World! program, 45 read more..

  • Page - 941

    Index 917 parameters declaring, 194–195 scope for, 195 pass-by-value, 196 playARound example, 184–186 return statement, 187–188 return type for, 187, 188–190 sayHello example, 183–184 static, 55–56, 255–256 synchronizing on threads, 462–466 using arrays with, 376 using in assignment statement, 188 MIDI format, 865 min() function (SQL), 775 min() method, 108 BigDecimal class, 556 read more..

  • Page - 942

    Java All-in-One For Dummies, 4th Edition 918 DNS defined, 476 overview, 477 host names, 477 HTTP, 476 InetAddress class, 479–480 IP addresses, 476 looking up host names, 480–482 mail servers, 476 multiple client connections, 494–497 ports, 476 servers, creating, 482–483 servers versus clients, 475 ServerSocket class, 484–485 SMTP, 476 Socket class, 483–484 telnet, 477–478 URLs, 477 read more..

  • Page - 943

    Index 919 identity, 224–225 life cycle of, 228 methods for, 9 object-oriented, defined, 9–10 state, 9, 226–227 type, 225–226 Observable interface, 324 Observer interface, 324 Observer pattern, 324 octal numbers Calculator program (Windows), BC2:9 converting integers to, BC2:5–BC2:6 overview, BC2:5–BC2:6 octet, 476 ODBC driver, 784 of() method Date-Time API, 534–535 LocalDate class, 538 read more..

  • Page - 944

    Java All-in-One For Dummies, 4th Edition 920 diamond, 432–433 Exclusive Or, 137–138 instance of, 273–274 logical !, 135 & and &&, 135–136 ^, 137–138 | and ||, 136–137 combining, 138–140 overview, 134 modulus, 97 Or, 136–137 relational, 124 ternary conditional operator, 140 defined, 97 unary defined, 97 plus and minus, 100–101 Xor, 137–138 optional data type, 441 OptionalDouble read more..

  • Page - 945

    Index 921 paths backslashes in pathnames, 722 trees (Swing), 642 Paths class. See also File class creating files, 734–735 File class versus, 733 getting directory contents, 735–736 overview, 733–734 walking file tree, 736–739 Pattern class, 513–514 pattern-matching. See regular expression patterns, design Abstract Factory pattern, 282 Accessor pattern, BC4:2 Delegation pattern, 265 read more..

  • Page - 946

    Java All-in-One For Dummies, 4th Edition 922 double type converting BigDecimal to, 563 creating BigDecimal object from, 554 inaccuracies, 550–552 mathematical limitations of, 549–550 size of, 71 wrapper class, 74–75 enum type, 94 float type creating BigDecimal object from, 554 inaccuracies, 550–551 positioning shapes, 836 size of, 71 wrapper class, 74–75 int type converting read more..

  • Page - 947

    Index 923 JSP advantages of, 703 classes in, 712–716 declarations, 710–712 directives, 705–706 elements in, 704 expressions, 706–708 implicit objects, 706 JavaBeans in, BC4:5–BC4:10 overview, 703–704 scriptlets defined, 704 separating statements, 709–710 using, 708–709 servlets defined, 11 engine for, 684 forms for, 694–695 getting input, 695–696 Hello World! program, 692–694 HttpServlet read more..

  • Page - 948

    Java All-in-One For Dummies, 4th Edition 924 Rectangle2D class, 836 rectangles, drawing, 837–838 recursion defined, 515 deleting nonempty directories, 725 displaying directories, 517–521 factorials nonrecursive method, 515–516 recursive method, 516–517 origin of term, 515 sorting partition() method, 523–525 program code, 525–528 Quicksort, 521–522 sort() method, 523 RED constant, 824 read more..

  • Page - 949

    Index 925 navigating, 787 updatable deleting row, 795 inserting row, 796 overview, 793–794 updating row, 795–796 ResultSet interface data retrieval methods, 788–789 navigating result set, 787 overview, 785–786 SQL and, 772 retainAll() method ArrayList class, 398 LinkedList class, 414 return statement, 187–188 @return tag, 343 return type for methods compilation errors and, 188–190 read more..

  • Page - 950

    Java All-in-One For Dummies, 4th Edition 926 SecureRandom class, 111 select statement (SQL) defined, 769 executing, 787 multiple table selects, 776–777 structure of, 772–773 suppressing duplicates, 777–778 where clause, 773–774 wildcard character, 774 semantic events, 585 semicolon (;), 11, 49, 51, 62, 331, 770 sequential group, 668 sequential streams, 442 Serif logical font, 818 -server read more..

  • Page - 951

    Index 927 setForeground() method, 825, 827, 829 setIconImage() method, 572 setIgnoringComments() method, 805 setIgnoringElementContent Whitespace() method, 805 setInvert() method, 621 setJMenuBar() method, 573, 677 setLastModified() method, 721 setLayout() method applying layout managers, 653 JApplet class, 677 JFrame class, 572 JPanel class, 577, 582 setLength() method, 365 setLineWrap() read more..

  • Page - 952

    Java All-in-One For Dummies, 4th Edition 928 ellipses, 838 filling gradient, 842–844 solid color, 841 lines, drawing, 837 rectangles, 837–838 rotating, 845–846 setting attributes for, 833 Shape interface classes implementing, 836 defined, 832 ShapeMaker program, 839–841 SimpleShape program, 833–835 text as, 846–847 translating to center, 845 transparent, 842 shift operators, BC2:12–BC2:14 shopping read more..

  • Page - 953

    Index 929 spinners (Swing) class methods, 639–640 defined, 639 models for, 640–641 Spinoff program, 648–650 split() method, 355, 359–361 splitting strings, 359–361 spreadsheets, 377 Spring layout manager, 653 sprites animating, 870 BallRoom applet, 871–872 overview, 869–870 SQL (Structured Query Language). See also JDBC column functions, 775–776 common statements, 768–769 creating database, read more..

  • Page - 954

    Java All-in-One For Dummies, 4th Edition 930 BufferedReader class, 744 character streams connecting PrintWriter object to file, 750–751 reading, 742–744 reading from file, 744–748 writing, 748–749, 751 writing to file, 752–754 DirectoryStream class, 735 I/O classes documentation, 742 overview, 741–742 String class, 77 limitations of, 362–363 matches() method, 512–513 methods for, read more..

  • Page - 955

    Index 931 buttons, 580–582 check boxes JCheckBox class, 612–615 Pizza Order program, 623–627 class hierarchy, 570–571 colors color chooser, 827–829 Color class, 823–825 immutable objects, 824 setting component color, 826–827 system colors, 825–826 combo boxes class methods, 630 creating, 631–632 defined, 629 events, 633 getting items from, 632 JComboBox class, 630 double buffering, 873 read more..

  • Page - 956

    Java All-in-One For Dummies, 4th Edition 932 models for, 640–641 text area defined, 608 JTextArea class, 609–611 text fields defined, 601 focus, 602 JTextField class, 602–603 Namer program, 603–605 numeric entry using, 605–607 trees getting selected node, 647–648 JTree class, 646–647 overview, 641–642 Spinoff program, 648–650 switch statement char type cases, 175–176 commission read more..

  • Page - 957

    Index 933 locks, 467–468 main thread, 448 Object class methods, 300 overview, 447–448 starting thread overview, 452 using Runnable interface, 453 StringBuilder and StringBuffer classes, 363 synchronizing methods, 462–466 using executor, 460–462 Throwable class, 277 throwing exceptions checked, 215–216 custom, 217–218 custom, using inheritance, 279–280 defined, 202 from main() method, 216 read more..

  • Page - 958

    Java All-in-One For Dummies, 4th Edition 934 TreeSelectionEvent class, 647 TreeSelectionListener interface, 647 TreeSelectionModel class, 647 trim() method, 355, 356–357 trimToSize() method, 365 try/catch statement custom exceptions, 279–280 displaying message, 210 examples using, 205–207 Exception class, 209–210 finally block, 205, 211–213 overview, 204–205 two-dimensional arrays accessing read more..

  • Page - 959

    Index 935 user input creating class for, 607–608 using loop, 152–154 XML documents, 801 value types, 69 valueChanged() method, 647 valueOf() method, 355 varchar type (SQL), 771 variables allowed characters for, 62 creating objects, 56 debugging in Eclipse, BC1:18–BC1:19 declaring class variables, 63 final variables, 67–68 instance variables, 64 local variables, 64–65 multiple in one read more..

  • Page - 960

    Java All-in-One For Dummies, 4th Edition 936 workspaces in Eclipse, BC1:5 in TextPad, 36 wrapper class defined, 74 listing of, 75 wrapping, 82 writeBoolean() method, 762 writeByte() method, 762 writeChar() method, 762 writeDouble() method, 762 writeFloat() method, 762 writeInt() method, 763 writeLong() method, 763 write-only property, BC4:2 writeShort() method, 763 writeUTF() method, 763 X read more..

  • Page - 961

    About the Author Doug Lowe has been writing computer programming books since the guys who invented Java were in high school. He’s written books on COBOL, FORTRAN, Visual Basic, IBM mainframe computers, mid-range systems, PCs, web programming, and probably a few he’s long forgotten about. He’s the author of more than 30 For Dummies books, including Networking For Dummies, read more..

  • Page - 962

    Publisher’s Acknowledgments Acquisitions Editor: Connie Santisteban Project Editor: Heidi Unger Copy Editor: Barry Childs-Helton Technical Editor: John Mueller Editorial Assistant: Annie Sullivan Sr. Editorial Assistant: Cherie Case Project Coordinator: Phil Midkiff Supervising Producer: Richard Graves Cover Image: ©budgetstockphoto/ iStockphoto.com read more..

  • Page - 963

    www.facebook.com/fordummies www.twitter.com/fordummies From eLearning to e-books, test prep to test banks, language learning to video training, mobile apps, and more, Dummies makes learning easier. At home, at work, or on the go, Dummies is here to help you go digital! read more..

Write Your Review