Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 908 trang
THÔNG TIN TÀI LIỆU
Cấu trúc
Front Cover
Title Page
Copyright
CONTENTS
PREFACE
READ THIS BEFORE YOU BEGIN
CHAPTER 1 CREATING YOUR FIRST JAVA CLASSES
LEARNING ABOUT PROGRAMMING
INTRODUCING OBJECT-ORIENTED PROGRAMMING CONCEPTS
Procedural Programming
Object- Oriented Programming
Understanding Objects, Classes, and Encapsulation
Understanding Inheritance and Polymorphism
LEARNING ABOUT JAVA
Java Program Types
ANALYZING A JAVA APPLICATION THAT USES CONSOLE OUTPUT
Understanding the Statement That Prints the Output
Understanding the First Class
Understanding the main() Method
ADDING COMMENTS TO A JAVA CLASS
SAVING, COMPILING, RUNNING, AND MODIFYING A JAVA APPLICATION
Saving a Java Class
Compiling a Java Class
Running a Java Application
Modifying a Java Class
CREATING A JAVA APPLICATION USING GUI OUTPUT
CORRECTING ERRORS AND FINDING HELP
YOU DO IT
Your First Application
Adding Comments to a Class
Modifying a Class
Creating a Dialog Box
DON'T DO IT
KEY TERMS
CHAPTER SUMMARY
REVIEW QUESTIONS
EXERCISES
DEBUGGING EXERCISES
GAME ZONE
TOUGH QUESTIONS
UP FOR DISCUSSION
CHAPTER 2 USING DATA WITHIN A PROGRAM
USING CONSTANTS AND VARIABLES
Declaring Variables
Declaring Named Constants
Pitfall: Forgetting That a Variable Holds One Value at a Time
LEARNING ABOUT THE int DATA TYPE
DISPLAYING DATA
WRITING ARITHMETIC STATEMENTS
Writing Arithmetic Statements Efficiently
USING THE BOOLEAN DATA TYPE
LEARNING ABOUT FLOATING-POINT DATA TYPES
UNDERSTANDING NUMERIC-TYPE CONVERSION
WORKING WITH THE char DATA TYPE
USING THE Scanner CLASS FOR KEYBOARD INPUT
Pitfall: Using nextLine() Following One of the Other Scanner Input Methods
USING THE JOptionPane CLASS FOR GUI INPUT
Using Input Dialog Boxes
Using Confirm Dialog Boxes
YOU DO IT
Working with Numeric Values
Accepting User Data
Performing Arithmetic
Experimenting with Java Programs
DON'T DO IT
KEY TERMS
CHAPTER SUMMARY
REVIEW QUESTIONS
EXERCISES
DEBUGGING EXERCISES
GAME ZONE
TOUGH QUESTIONS
UP FOR DISCUSSION
CHAPTER 3 USING METHODS, CLASSES, AND OBJECTS
CREATING METHODS WITH ZERO, ONE, AND MULTIPLE PARAMETERS
Creating Methods That Require a Single Parameter
Creating Methods That Require Multiple Parameters
CREATING METHODS THAT RETURN VALUES
Calling a Method from Another Method
LEARNING ABOUT CLASS CONCEPTS
CREATING A CLASS
CREATING INSTANCE METHODS IN A CLASS
DECLARING OBJECTS AND USING THEIR METHODS
Understanding Data Hiding
ORGANIZING CLASSES
AN INTRODUCTION TO USING CONSTRUCTORS
UNDERSTANDING THAT CLASSES ARE DATA TYPES
YOU DO IT
Creating a Static Method That Requires No Arguments and Returns No Values
Calling a Static Method from Another Class
Creating a Static Method That Accepts Arguments and Returns Values
Creating a Class That Contains Instance Fields and Methods
Creating a Class That Instantiates Objects of Another Class
Adding a Constructor to a Class
Creating a More Complete Class
DON'T DO IT
KEY TERMS
CHAPTER SUMMARY
REVIEW QUESTIONS
EXERCISES
DEBUGGING EXERCISES
GAME ZONE
TOUGH QUESTIONS
UP FOR DISCUSSION
CHAPTER 4 MORE OBJECT CONCEPTS
UNDERSTANDING BLOCKS AND SCOPE
OVERLOADING A METHOD
LEARNING ABOUT AMBIGUITY
SENDING ARGUMENTS TO CONSTRUCTORS
OVERLOADING CONSTRUCTORS
LEARNING ABOUT THE this REFERENCE
Using the this Reference to Make Overloaded Constructors More Efficient
USING static VARIABLES
USING CONSTANT FIELDS
USING AUTOMATICALLY IMPORTED, PREWRITTEN CONSTANTS AND METHODS
USING AN EXPLICITLY IMPORTED PREWRITTEN CLASS AND ITS METHODS
UNDERSTANDING COMPOSITION
A BRIEF LOOK AT NESTED AND INNER CLASSES
YOU DO IT
Demonstrating Scope
Overloading Methods
Creating a Constructor That Requires an Argument
Using an Explicitly Imported Prewritten Class
Creating an Interactive Application with a Timer
DON'T DO IT
KEY TERMS
CHAPTER SUMMARY
REVIEW QUESTIONS
EXERCISES
DEBUGGING EXERCISES
GAME ZONE
TOUGH QUESTIONS
UP FOR DISCUSSION
CHAPTER 5 MAKING DECISIONS
UNDERSTANDING DECISION MAKING
MAKING DECISIONS WITH THE if AND if ... else STRUCTURES
Pitfall: Misplacing a Semicolon in an if Statement
Pitfall: Using the Assignment Operator Instead of the Equivalency Operator
Pitfall: Attempting to Compare Objects Using the Relational Operators
The if...else Structure
USING MULTIPLE STATEMENTS IN AN if OR if ... else STRUCTURE
NESTING if AND if...else STATEMENTS
USING LOGICAL AND and OR OPERATORS
MAKING ACCURATE AND EFFICIENT DECISIONS
Using AND and OR Appropriately
USING THE switch STATEMENT
USING THE CONDITIONAL AND NOT OPERATORS
Using the NOT Operator
UNDERSTANDING PRECEDENCE
YOU DO IT
Using an if...else
Creating an Event Class to Use in a Decision-Making Application
Writing an Application that Uses the Event class
Using the switch Statement
DON'T DO IT
KEY TERMS
CHAPTER SUMMARY
REVIEW QUESTIONS
EXERCISES
DEBUGGING EXERCISES
GAME ZONE
TOUGH QUESTIONS
UP FOR DISCUSSION
CHAPTER 6 LOOPING
LEARNING ABOUT THE LOOP STRUCTURE
USING A while LOOP TO CREATE A DEFINITE LOOP
USING A while LOOP TO CREATE AN INDEFINITE LOOP
USING SHORTCUT ARITHMETIC OPERATORS
USING A for LOOP
LEARNING HOW AND WHEN TO USE A do...while LOOP
LEARNING ABOUT NESTED LOOPS
IMPROVING LOOP PERFORMANCE
Avoiding Unnecessary Operations
Considering the Order of Evaluation of Short-Circuit Operators
Comparing to Zero
Employing Loop Fusion
YOU DO IT
Writing a Loop to Validate Data Entries
Working with Prefix and Postfix Increment Operators
Working with Definite Loops
Working with Nested Loops
DON'T DO IT
KEY TERMS
CHAPTER SUMMARY
REVIEW QUESTIONS
EXERCISES
DEBUGGING EXERCISES
GAME ZONE
TOUGH QUESTIONS
UP FOR DISCUSSION
CHAPTER 7 CHARACTERS, STRINGS, AND THE STRINGBUILDER
IDENTIFYING PROBLEMS THAT CAN OCCUR WHEN YOU MANIPULATE STRING DATA
MANIPULATING CHARACTERS
DECLARING A String OBJECT
COMPARING String VALUES
USING OTHER String METHODS
CONVERTING Strings TO NUMBERS
LEARNING ABOUT THE StringBuilder AND StringBuffer CLASSES
YOU DO IT
Using String Class Methods
Converting a String to an Integer
Using StringBuilder Methods
DON'T DO IT
KEY TERMS
CHAPTER SUMMARY
REVIEW QUESTIONS
EXERCISES
DEBUGGING EXERCISES
GAME ZONE
TOUGH QUESTIONS
UP FOR DISCUSSION
CHAPTER 8 ARRAYS
DECLARING AND INITIALIZING AN ARRAY
Initializing an Array
USING SUBSCRIPTS WITH AN ARRAY
DECLARING AN ARRAY OF OBJECTS
SEARCHING AN ARRAY FOR AN EXACT MATCH
SEARCHING AN ARRAY FOR A RANGE MATCH
PASSING ARRAYS TO AND RETURNING ARRAYS FROM METHODS
Returning an Array from a Method
MANIPULATING ARRAYS OF Strings
SORTING ARRAY ELEMENTS
Sorting Arrays of Objects
USING TWO-DIMENSIONAL AND MULTIDIMENSIONAL ARRAYS
Using the length Field with a Two-Dimensional Array
Understanding Ragged Arrays
Using Multidimensional Arrays
USING THE Arrays CLASS
USING THE ArrayList CLASS
Understanding the Limitations of the ArrayList Class
YOU DO IT
Creating and Populating an Array
Initializing an Array
Using a for Loop to Access Array Elements
Creating Parallel Arrays to Eliminate Nested if Statements
Creating an Application with an Array of Objects
Creating an Interactive Application That Creates an Array of Objects
Passing an Array to a Method
Using Arrays Class Methods
DON'T DO IT
KEY TERMS
CHAPTER SUMMARY
REVIEW QUESTIONS
EXERCISES
DEBUGGING EXERCISES
GAME ZONE
TOUGH QUESTIONS
UP FOR DISCUSSION
CHAPTER 9 INTRODUCTION TO INHERITANCE
LEARNING ABOUT THE CONCEPT OF INHERITANCE
EXTENDING CLASSES
OVERRIDING SUPERCLASS METHODS
UNDERSTANDING HOW CONSTRUCTORS ARE CALLED DURING INHERITANCE
USING SUPERCLASS CONSTRUCTORS THAT REQUIRE ARGUMENTS
ACCESSING SUPERCLASS METHODS
Comparing this and super
LEARNING ABOUT INFORMATION HIDING
METHODS YOU CANNOT OVERRIDE
A Subclass Cannot Override static Methods in Its Superclass
A Subclass Cannot Override final Methods in Its Superclass
A Subclass Cannot Override Methods in a final Superclass
YOU DO IT
Creating a Superclass and an Application to Use It
Creating a Subclass and an Application to Use It
Creating a Subclass Method That Overrides a Superclass Method
Understanding the Role of Constructors in Inheritance
Inheritance When the Superclass Requires Constructor Arguments
Accessing an Overridden Superclass Method from Within a Subclass
DON'T DO IT
KEY TERMS
CHAPTER SUMMARY
REVIEW QUESTIONS
EXERCISES
DEBUGGING EXERCISES
GAME ZONE
TOUGH QUESTIONS
UP FOR DISCUSSION
CHAPTER 10 ADVANCED INHERITANCE CONCEPTS
CREATING AND USING ABSTRACT CLASSES
USING DYNAMIC METHOD BINDING
Using a Superclass as a Method Parameter Type
CREATING ARRAYS OF SUBCLASS OBJECTS
USING THE Object CLASS AND ITS METHODS
Using the toString() Method
Using the equals() Method
USING INHERITANCE TO ACHIEVE GOOD SOFTWARE DESIGN
CREATING AND USING INTERFACES
Creating Interfaces to Store Related Constants
CREATING AND USING PACKAGES
YOU DO IT
Creating an Abstract Class
Extending an Abstract Class
Extending an Abstract Class with a Second Subclass
Instantiating Objects from Subclasses
Using Object References
Overriding the Object Class equals() Method
Eliminating Duplicate User Entries
Creating a Package
DON'T DO IT
KEY TERMS
CHAPTER SUMMARY
REVIEW QUESTIONS
EXERCISES
DEBUGGING EXERCISES
GAME ZONE
TOUGH QUESTIONS
UP FOR DISCUSSION
CHAPTER 11 EXCEPTION HANDLING
LEARNING ABOUT EXCEPTIONS
TRYING CODE AND CATCHING Exceptions
THROWING AND CATCHING MULTIPLE Exceptions
USING THE Finally BLOCK
UNDERSTANDING THE ADVANTAGES OF EXCEPTION HANDLING
SPECIFYING THE Exceptions A METHOD CAN THROW
TRACING Exceptions THROUGH THE CALL STACK
CREATING YOUR OWN Exceptions
USING ASSERTIONS
YOU DO IT
Catching an Exception and Using getMessage()
Generating a NumberFormatException
Adding NumberFormatException Handling Capabilities to an Application
Creating a Class That Automatically Throws Exceptions
Creating a Class That Passes on an Exception
Creating an Application That Can Catch Exceptions
Extending a Class That Throws Exceptions
Using the printStackTrace() Method
Creating an Exception Class
Using an Exception You Created
DON'T DO IT
KEY TERMS
CHAPTER SUMMARY
REVIEW QUESTIONS
EXERCISES
DEBUGGING EXERCISES
GAME ZONE
TOUGH QUESTIONS
UP FOR DISCUSSION
CHAPTER 12 FILE INPUT AND OUTPUT
UNDERSTANDING COMPUTER FILES
USING THE File CLASS
UNDERSTANDING DATA FILE ORGANIZATION AND STREAMS
USING STREAMS
WRITING TO AND READING FROM A FILE
Reading from a File
WRITING FORMATTED FILE DATA
READING FORMATTED FILE DATA
USING A VARIABLE FILENAME
CREATING AND USING RANDOM ACCESS FILES
WRITING RECORDS TO A RANDOM ACCESS FILE
READING RECORDS FROM A RANDOM ACCESS FILE
Accessing a Random Access File Sequentially
Accessing a Random Access File Randomly
READING AND WRITING OBJECTS TO AND FROM FILES
YOU DO IT
Using the File Class to Examine File Status
Comparing Two File Dates
Using InputStream and OutputStream Objects
Writing to an Output File
Reading Data from a File
Creating a Class to Use in a File of Objects
Creating a Program that Writes Event Objects to a File
Creating a Program that Accesses Stored Event Object Data
DON'T DO IT
KEY TERMS
CHAPTER SUMMARY
REVIEW QUESTIONS
EXERCISES
DEBUGGING EXERCISES
GAME ZONE
TOUGH QUESTIONS
UP FOR DISCUSSION
CHAPTER 13 INTRODUCTION TO SWING COMPONENTS
UNDERSTANDING Swing COMPONENTS
USING THE JFrame CLASS
Customizing a JFrame's Appearance
USING A JLabel
Changing a JLabel's Font
USING A LAYOUT MANAGER
EXTENDING THE JFrame CLASS
ADDING JTextFields, JBUTTONS, AND TOOL TIPS TO A JFrame
Adding JButtons
Using Tool Tips
LEARNING ABOUT EVENT-DRIVEN PROGRAMMING
Preparing Your Class to Accept Event Messages
Telling Your Class to Expect Events to Happen
Telling Your Class How to Respond to Events
Using the setEnabled() Method
UNDERSTANDING Swing EVENT LISTENERS
USING THE JCheckBox CLASS
USING THE ButtonGroup CLASS
USING THE JComboBox CLASS
YOU DO IT
Creating a JFrame
Ending an Application When a JFrame Closes
Adding Components to a JFrame
Adding Functionality to a JButton and a JTextField
Distinguishing Event Sources
Including JCheckBoxes in an Application
DON'T DO IT
KEY TERMS
CHAPTER SUMMARY
REVIEW QUESTIONS
EXERCISES
DEBUGGING EXERCISES
GAME ZONE
TOUGH QUESTIONS
UP FOR DISCUSSION
CHAPTER 14 ADVANCED GUI TOPICS
UNDERSTANDING THE CONTENT PANE
USING COLOR
LEARNING MORE ABOUT LAYOUT MANAGERS
Using BorderLayout
Using FlowLayout
Using GridLayout
Using CardLayout
Using Advanced Layout Managers
USING THE JPanel CLASS
CREATING JScrollPanes
A CLOSER LOOK AT EVENTS AND EVENT HANDLING
An Event-Handling Example: KeyListener
USING AWTEvent CLASS METHODS
Understanding x- and y-Coordinates
HANDLING MOUSE EVENTS
USING MENUS
Using JCheckBoxMenuItem and JRadioButtonMenuItem Objects
Using addSeparator()
Using setMnemonic()
YOU DO IT
Using BorderLayout
Using Fewer than Five Components with the BorderLayout Manager
Using FlowLayout
Using GridLayout
Using CardLayout
Viewing All the Cards in CardLayout
Using a Menu Bar and JPanels
DON'T DO IT
KEY TERMS
CHAPTER SUMMARY
REVIEW QUESTIONS
EXERCISES
DEBUGGING EXERCISES
GAME ZONE
TOUGH QUESTIONS
UP FOR DISCUSSION
CHAPTER 15 GRAPHICS
LEARNING ABOUT THE paint() AND repaint() METHODS
Using the setLocation() Method
USING THE drawString() METHOD
Using the setFont() and setColor() Methods
Using Color
CREATING Graphics AND Graphics2D OBJECTS
DRAWING LINES AND SHAPES
Drawing Ovals
Drawing Arcs
Creating Shadowed Rectangles
Creating Polygons
Copying an Area
LEARNING MORE ABOUT FONTS AND METHODS YOU CAN USE WITH THEM
Discovering Screen Statistics Using the Toolkit Class
Discovering Font Statistics
DRAWING WITH JAVA 2D GRAPHICS
Specifying the Rendering Attributes
Setting a Drawing Stroke
Creating Objects to Draw
YOU DO IT
Using the drawString() Method
Using Fonts and Colors
Creating Your Own Graphics Object
Examining Screen Coordinates
Creating a Drawing
Copying an Area
Using FontMetrics Methods to Compare Fonts
Using FontMetrics Methods to Place a Border Around a String
Using Drawing Strokes
Working with Shapes
DON'T DO IT
KEY TERMS
CHAPTER SUMMARY
REVIEW QUESTIONS
EXERCISES
DEBUGGING EXERCISES
GAME ZONE
TOUGH QUESTIONS
UP FOR DISCUSSION
CHAPTER 16 APPLETS, IMAGES, AND SOUND
INTRODUCING APPLETS
Understanding the JApplet Class
Running an Applet
WRITING AN HTML DOCUMENT TO HOST AN APPLET
CREATING A JApplet THAT CONTAINS AN init() METHOD
WORKING WITH JApplet COMPONENTS
UNDERSTANDING THE JApplet LIFE CYCLE
The init() Method
The start() Method
The stop() Method
The destroy() Method
UNDERSTANDING MULTIMEDIA AND USING IMAGES
Adding Images to JApplets
Using ImageIcons
ADDING SOUND TO JApplets
YOU DO IT
Creating an HTML Document to Host an Applet
Creating and Running a JApplet
Running a JApplet in Your Web Browser
Creating a More Complicated JApplet
Making the JApplet's Button Respond to Events
Understanding the Applet Life Cycle
Displaying Images
Playing Sounds
DON'T DO IT
KEY TERMS
CHAPTER SUMMARY
REVIEW QUESTIONS
EXERCISES
DEBUGGING EXERCISES
GAME ZONE
TOUGH QUESTIONS
UP FOR DISCUSSION
APPENDIX A: WORKING WITH THE JAVA PLATFORM
APPENDIX B: LEARNING ABOUT ASCII AND UNICODE
APPENDIX C: FORMATTING OUTPUT
APPENDIX D: GENERATING RANDOM NUMBERS
APPENDIX E: JAVADOC
GLOSSARY
INDEX
Nội dung
[...]... CREATING YOUR FIRST JAVA CLASSES » In this chapter, you will: Learn about programming Be introduced to object-oriented programming concepts Learn about Java Analyze a Java application that uses console output Add comments to a Java class Save, compile, run, and modify a Java application Create a Java application using GUI output Correct errors and find help 1 CREATING YOUR FIRST JAVA CLASSES JAVA ON THE JOB,... provided on the CD that comes with this book: » Sun Microsystems Java SE 6, the Java language, compiler, and runtime environment » Sun Microsystems Java Application Programming Interface (API) Specification, official documentation for the Javaprogramming language » The jGRASP integrated development environment for Java » Code files for all Java program examples contained in the text VISIT OUR WORLD WIDE... OBJECT-ORIENTED PROGRAMMING CONCEPTS Two popular approaches to writing computer programs are procedural programming and object-oriented programming PROCEDURAL PROGRAMMING »NOTE Procedures are also called modules, methods, functions, and subroutines Users of different programming languages tend to use different terms Java programmers most frequently use the term “method.” Procedural programming is a style of programming. .. 805 APPENDIX A WORKING WITH THE JAVA PLATFORM 807 APPENDIX B LEARNING ABOUT ASCII AND UNICODE 815 APPENDIX C FORMATTING OUTPUT 821 APPENDIX D GENERATING RANDOM NUMBERS 833 APPENDIX E JAVADOC 839 GLOSSARY 847 INDEX 867 xviii PREFACE Java Programming, Fifth Edition provides the beginning programmer with a guide to developing applications using the Javaprogramming language Java is popular among professional... example, if you misspell a programminglanguage word, you commit a syntax error, but if you use a correct word in the wrong context, you commit a semantic error 3 »NOTE You will learn more about debugging Java programs later in this chapter CREATING YOUR FIRST JAVA CLASSES »TWO TRUTHS AND A LIE: LEARNING ABOUT PROGRAMMING 1 Unlike a low-level programming language, a high-level programming language allows... (JVM) Figure 1-3 shows the Java environment Programming statements written in a high-level programming language are called source code When you write a Java program, you first construct the source code using a text editor such as Notepad The statements are saved in a file; then, the Java compiler converts the source code into a binary program of bytecode A program called the Java interpreter then checks... other programming languages, software vendors usually have to produce multiple versions of the same product 8 C H A P T E R O N E (a Windows version, Macintosh version, UNIX version, Linux version, and so on) so all users can run the program With Java, one program version will run on all these platforms Java Source Code Source code is stored on a disk in a file with a name ending in java Java Compiler Java. .. class Computer Operating System JVM (named java. exe) performs security checks and translates bytecodes to machine language, which executes Java Virtual Machine Figure 1-3 The Java environment Java is also simpler to use than many other object-oriented languages Java is modeled after C++ Although neither language is easy to read or understand on first exposure, Java does eliminate some of the most difficult-to-understand... LEARNING ABOUT JAVA 1 Java was developed to be architecturally neutral, which means that anyone can build an application without extensive study 2 After you write a Java program, the compiler converts the source code into a binary program of bytecode 3 Java programs that are embedded in a Web page are called applets, while stand-alone programs are called Java applications The false statement is #1 Java was... complete the steps and exercises, you need the following: » Software: Java SE 6, available from http:/ /java. sun.com (Although almost all of the examples in this » » book will work with earlier versions of Java, this book was created using Java 6.) The book clearly points out the few cases when an example does not work with earlier versions of Java You also need a text editor, such as Notepad A few exercises . YOUR FIRST JAVA CLASSES 1
LEARNING ABOUT PROGRAMMING 2
INTRODUCING OBJECT-ORIENTED PROGRAMMING CONCEPTS 4
Procedural Programming 4
Object-Oriented Programming. COMMENTS TO A JAVA CLASS 16
SAVING, COMPILING, RUNNING, AND MODIFYING A JAVA APPLICATION 18
Saving a Java Class 18
Compiling a Java Class 18
Running a Java Application