Tải bản đầy đủ (.pdf) (444 trang)

Java Programming Fundamentals pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.88 MB, 444 trang )

Java Programming
Fundamentals
JVPG-SSMN-0101A
Java Programming Fundamentals
JVPG-SSMN-0101A
©1988-2000 Wave Technologies International, Inc.,
a Thomson Learning company.
Thomson Learning™ is a trademark used herein under license.
All rights reserved.
Printed in the United States of America. No part of this book may be used or reproduced in any
form or by any means, or stored in a database or retrieval system, without prior written
permission of the publisher. Making copies of any part of this book for any purpose other than
your own personal use is a violation of United States copyright laws. For information, contact
Wave Technologies International, Inc., 10845 Olive Blvd., Suite 250, St. Louis, Missouri
63141.
This book is sold as is, without warranty of any kind, either express or implied, respecting the
contents of this book, including, but not limited to, implied warranties for the book’s quality,
performance, merchantability, or fitness for any particular purpose. Neither Wave Technologies
International, Inc., nor its dealers or distributors shall be liable to the purchaser or any other
person or entity with respect to any liability, loss, or damage caused or alleged to be caused
directly or indirectly by this book.
Trademarks
Trademarks and registered trademarks of products mentioned in this book are held by the
companies producing them. Use of a term in this book should not be regarded as affecting the
validity of any trademark or service mark.
The Wave Technologies International, Inc. logo is a registered trademark of Wave Technologies
International, Inc., St. Louis, Missouri.
Copyrights of any screen captures in this book are the property of the software’s manufacturer.
Mention of any products in this book in no way constitutes an endorsement by Wave
Technologies International, Inc.
10 9 8 7 6 5 4 3 2 1


iii
SELF-STUDY
Contents
Introduction 1
Course Purpose 1
Course Goals 1
Exercises 2
Scenario-Based Learning 3
Multimedia Overview 3
Videos 3
Assessment 4
Hardware and Software Requirements 4
Chapter 1—Java Runtime Environment 5
Objectives 6
Pre-Test Questions 6
Introduction 7
The Java Virtual Machine 7
The Java 2 Software Development Kit 8
Installation 8
Windows 95/98/Me 9
Windows NT/2000 9
Linux 10
Creating a Simple, Stand-Alone Application 11
Creating a Simple Applet 13
Java Comments 14
Sun Certification 15
Summary 16
Post-Test Questions 16
Chapter 2—Data Types, Variables and Operators 17
Objectives 18

Pre-Test Questions 18
Introduction 19
Data Types 19
Variables 20
Default variable values 21
Variable declaration and initialization 21
Casting 22
iv Contents
Operators 24
Arithmetic operators 24
Relational operators 25
Logical operators 26
Precedence 27
Sun Certification 28
Summary 29
Post-Test Questions 30
Chapter 3—Control Statements 33
Objectives 34
Pre-Test Questions 34
Introduction 34
Code Blocks 35
Expressions 36
Conditional Statements 38
if statement 38
switch/case statement 40
Iteration (Loop) Statements 42
while loop (entry condition loop) 42
do while loop (exit condition loop) 43
for loop 43
Nested loops (break and continue) 44

Exercise 3-1: Using while and for loops 46
Sun Certification 47
Summary 48
Post-Test questions 48
Chapter 4—Methods 49
Objectives 50
Pre-Test Questions 50
Introduction 51
Methods 51
Return Statement 53
Calling a Method 55
Parameters 57
Pass by Value 58
Overloading 60
Exercise 4-1: Writing methods 62
Sun Certification 63
Summary 64
Post-Test Questions 64
Contents v
Chapter 5—Arrays 65
Objectives 66
Pre-Test Questions 66
Introduction 67
What Is an Array? 67
Initializing an Array 68
Using an Array 70
Passing an Array to a Method 74
Methods with an Array Return Type 75
Garbage Collection 76
Command Line Parameters 78

Exercise 5-1: Using arrays 79
Graduating Task #1: Creating a binary search 79
Sun Certification 81
Summary 83
Post-Test Questions 83
Chapter 6—Classes and Objects 85
Objectives 86
Pre-Test Questions 86
Introduction 87
Object-Oriented Programming 87
What Is a Class? 88
What Is an Object? 89
Instance and Class Members 89
Instance members 90
Class members 93
Abstraction 95
Object References 96
Exercise 6-1: Creating your own classes 98
Sun Certification 99
Summary 100
Post-Test Questions 101
Chapter 7—Inheritance 103
Objectives 104
Pre-Test Questions 104
Introduction 105
What Is Inheritance? 105
Using inheritance 106
Extending Classes 107
Using this and super() 110
The instanceof Operator 111

vi Contents
Overriding Methods 112
Exercise 7-1: Implementing inheritance 113
Sun Certification 114
Summary 116
Post-Test Questions 117
Chapter 8—Constructors 119
Objectives 120
Pre-Test Questions 120
Introduction 121
What Is a Constructor? 121
What can constructors do? 122
Using Constructors 123
This 126
this() as a constructor 126
Avoiding namespace conflicts 127
Super 128
Constructor Process 129
Constructors and Callbacks 130
Strings and StringBuffer 132
String constructors 132
String characteristics 133
Methods of String 135
StringBuffer 136
Exercise 8-1: Building constructors 137
Exercise 8-2: Implementing callbacks 138
Sun Certification 139
Summary 142
Post-Test Questions 143
Chapter 9—Interfaces and Abstract Classes 145

Objectives 146
Pre-Test Questions 146
Introduction 147
What Is an Interface? 147
Contents of an interface 148
Interface functions 149
Polymorphism 151
What Is an Abstract Class? 158
Graduating Task #2: Interfaces and Polymorphism 161
Sun Certification 161
Summary 162
Post-Test Questions 162
Contents vii
Chapter 10—Packages and Access Modifiers 163
Objectives 164
Pre-Test Questions 164
Introduction 165
Packages and Access Modifiers 165
Packages 165
Access modifiers 167
Comparison Between Java 1.1 And Java 2 168
Information Hiding 169
Encapsulation 171
Exercise 10-1: Using encapsulation, accessors and mutators 173
Sun Certification 173
Summary 174
Post-Test Questions 175
Chapter 11—Swing Components 177
Objectives 178
Pre-Test Questions 178

Introduction 179
What Is the AWT? 179
Heavyweight components (peer pattern) 180
AWT 1.1 180
What Is Swing? 181
Model View Controller (MVC) programming paradigm 182
Basic Swing Components 183
Graphical widgets 185
Containers 203
JavaBeans 207
Sun Certification 208
Summary 208
Post-Test Questions 209
Chapter 12—Layout Managers 211
Objectives 212
Pre-Test Questions 212
Introduction 213
What Is a Layout Manager? 213
FlowLayout 214
GridLayout 216
BorderLayout 218
BoxLayout 221
viii Contents
Swing 223
Strut 223
Glue 225
Combining layouts 227
Graduating Task #3: Creating sophisticated layouts 230
Sun Certification 231
Summary 232

Post-Test Questions 232
Chapter 13—Graphics 233
Objectives 234
Pre-Test Questions 234
Introduction 235
What Are Graphics in Java? 235
Graphics Class 236
drawString() 244
drawLine() 244
drawRect() 245
drawImage() 247
Color class 248
Font class 250
Exercise 13-1: Drawing to your Scribble JFrame 252
Sun Certification 253
Summary 253
Post-Test Questions 254
Chapter 14—The Delegation Model 257
Objectives 258
Pre-Test Questions 258
Introduction 259
What Is an Event? 259
SDK 1.3 Event Handling 260
Generating the event object 261
Sending the event object to the listener 261
Preparing the listener to receive the event 262
Example: Creating a closeable JFrame 263
JFrame convenience methods for event handling 268
Example: Event handling and callbacks 269
Sun Certification 274

Summary 274
Post-Test Questions 275
Contents ix
Chapter 15—Inner Classes 277
Objectives 278
Pre-Test Questions 278
Introduction 279
What Is an Inner Class? 279
Inner Classes for Event Handling 282
Graduating Task #4: Event-enabling the Scribble Application 286
Sun Certification 287
Summary 289
Post-Test Questions 290
Chapter 16—Applets 291
Objectives 292
Pre-Test Questions 292
Introduction 293
Applets and Web Browsers 294
JApplets 294
Applet life cycle 295
The <APPLET></APPLET> tags 296
Passing parameters to applets 298
Applets should not be trusted 300
Converting an Application into an Applet 301
Converting an Applet into an Application 306
Exercise 16-1: Converting the Scribble application into an applet 308
Sun Certification 308
Summary 309
Post-Test Questions 309
Chapter 17—Exceptions 311

Objectives 312
Pre-Test Questions 312
Introduction 313
What Is an Exception? 313
Errors 314
Exceptions 314
When Bad Things Happen to Good Programs 316
Ignoring the Exception 316
Handling the Exception 317
Throwing the Exception to the calling method 319
Handling and rethrowing the Exception 320
Creating and Throwing Your Own Exceptions 321
xContents
Exception Handling Tips 324
Sun Certification 325
Summary 326
Post-Test Questions 326
Chapter 18—Creating Threads and Thread Methods 327
Objectives 328
Pre-Test Questions 328
Introduction 329
What Are Threads? 329
How Operating Systems Handle Multitasking 330
Types of Threads in Java 330
Creating Threads 332
Subclassing the Thread class 332
Implementing the Runnable interface 335
Which technique? 337
Thread states 339
The currentThread(), getName() and sleep() methods 341

The setName() and setPriority() methods 343
The yield() method 345
Graduating Task #5: Creating a threaded digital clock 346
Sun Certification 347
Summary 347
Post-Test Questions 348
Chapter 19—Synchronization 351
Objectives 352
Pre-Test Questions 352
Introduction 353
What Is Thread Synchronization? 353
Thread Racing 353
Synchronized and the Object Monitor 355
Thread Race Condition 356
Competing for resources 357
Synchronizing the methods 359
Atomic processes 360
Sophisticated Thread Synchronization 361
Consumer/producer scenario 362
Deadlocks 368
Graduating Task #6: Enhancing the Digital Clock with Advanced
Thread Techniques 369
Sun Certification 370
Summary 370
Post-Test Questions 371
Contents xi
Chapter 20—Streams and Serialization 373
Objectives 374
Pre-Test Questions 375
Introduction 375

What Is a Stream? 376
InputStream, OutputStream, Reader and Writer 377
Files 378
Instantiating a File object 379
Working with a File object 380
Stream Classes of java.io.* 382
System.in and System.out 384
Reading bytes from System.in 385
Converting a byte stream into a character stream 387
Wrapper streams 389
File I/O 391
Serialization 393
The process of object serialization 394
Transient variables and security 399
Graduating Task #7: Building a Simple Word Processor 400
Sun Certification 401
Summary 403
Post-Test Questions 404
Appendix A—Answers to Pre-Test and Post-Test Questions 405
Glossary 417
Index 429
xii Contents
1
SELF-STUDY
Introduction
COURSE PURPOSE
This coursebook was developed for self-study training and will assist you during class.
Along with comprehensive instructional text and objectives checklists, this coursebook
provides easy-to-follow hands-on lab exercises and a glossary of specific terms. It also
provides Internet addresses needed to complete some exercises, although due to the

constantly changing nature of the Internet, some addresses may no longer be valid.
Many coursebooks also list additional reference works for continued learning outside the
classroom. When you return to your home or office, you will find this coursebook to be a
valuable resource, one to which you can refer whether you want to review the steps in an
exercise or apply what you have learned.
This course teaches you how to write Java applications and applets. You will learn the Java
language mechanics found in other programming languages, such as variables, iterations,
control statements, methods and arrays. You will also discuss object-oriented theory as it
relates to Java. You will create Graphical User Interfaces (GUIs) for both applications and
applets, emphasizing components, layouts, and graphics. This course will also prepare
you for the Sun Certified Programmer Exam for the Java 2 Platform by providing reviews
and examples relative to the exam.
Upon completion of this course, you will be experienced in writing Java applications and
applets. You will also be very familiar and comfortable the Java 2 API.
COURSE GOALS
This self-study course will provide you with the information you need to complete the
following:
Describe the Java Runtime Environment (JRE).
Use Java variables, control statements, methods and arrays.
Describe object-oriented theory, including abstraction, encapsulation, inheritance
and polymorphism.
Describe method overloading and overriding.
Use Java static and instance members.
2 Introduction
Create Java constructors.
Identify the differences between instance and class members.
Use Java abstract classes and interfaces.
Use Java Strings and StringBuffers.
Describe Java packages and accessibility.
Use the Java Abstract Windowing Toolkit (AWT) and Swing components central

to JDK 1.2.
Use the JDK 1.2.x event delegation model.
Define applets and the applet life cycle.
Throw and handle exceptions.
Create threads.
Use streams.
Describe Java and networking.
Complete Sun certification examination examples.
EXERCISES
The exercises in this manual are designed to give you hands-on practice working in both
stand-alone and network environments. It is suggested that you complete the exercises
when referenced. However, this may not always be convenient. If you need to skip an
exercise, you should plan on completing the exercise later when time and circumstances
allow.
You may find that there are some exercises that you are unable to complete due to
hardware or software requirements. Do not let this stop you from completing the other
exercises in this manual.
NOTICE:
The exercises in this self-study product are designed to be used on a system that is
designated for training purposes only. Practicing the exercises on a LAN or workstation
that is used for other purposes may cause configuration problems, which could require a
reinstallation and/or restoration from a tape backup of the original configuration. Please
keep this in mind when working through the exercises.
Scenario-Based Learning 3
SCENARIO-BASED LEARNING
This self-study manual uses a number of scenario-based learning exercises. In these, you
are presented with a situation similar to those you are likely to encounter in day-to-day
support and management. You will be provided with the information you need and
asked to determine the best solution. A suggested solution is provided at the back of the
self-study manual.

These exercises are being used to supplement hands-on practice and to help get you
started thinking critically about practical applications. In some cases, they have been
used as a replacement for hands-on practice for scenarios where it would be especially
difficult to emulate a real-world situation.
It is important that you take the time to work through the scenario-based exercises.
These are an important supplement to the training materials and are meant to reinforce
the text information in your manual.
MULTIMEDIA OVERVIEW
The Interactive Learning CD-ROM is a robust collection of learning tools designed to
enhance your understanding and prepare you for certification. You access these tools
from the Start menu: select Wave Interactive Learning and then select the appropriate
curriculum.
Videos
A key element of the Interactive Learning CD-ROM included with this course is digital
video. Digital video lessons describe key concepts covered in the manual. Often concepts
are best understood by drawing a picture. Digital video segments provide a graphical
illustration, accompanied by an instructor’s narration. These lessons are ideal both as
introductions to key concepts and for reinforcement.
4 Introduction
Assessment
As reinforcement and review for certification exams, the Challenge! Interactive is
significantly helpful. The Challenge! contains sample test items for each exam. The
sample tests are comprised of multiple-choice, screen simulation, and scenario questions
to better prepare you for exams. It is a good idea to take the Challenge! test on a particular
exam, read the study guide and then take the Challenge! test again. It is useful to take the
Challenge! tests as frequently as possible because they are such excellent reinforcement
tools.
HARDWARE AND SOFTWARE REQUIREMENTS
Hardware Requirements
Software Requirements

Microsoft Windows 95, 98, ME, 2000, NT 4.0 or higher.
Netscape Navigator 4.5 or higher.
Microsoft Internet Explorer 5.5 or higher
Java Development Kit version 1.2.2 or higher ( )
CIW hardware specifications Greater than or equal to the following
Processor Intel Pentium II (or equivalent) personal computer with processor speed
greater than or equal to 300 MHz
L2 cache 256 KB
Hard disk 2-GB hard drive
RAM At least 128 MB
CD-ROM 32X
Video adapter At least 4 MB
Monitor 15-inch monitor
Internet Connectivity 28.8 modem and ISP account
Sound 16-bit sound card or better with speakers
Network Interface Card 10BaseT and 100BaseT
MAJOR TOPICS
M A J O R T O P I C S
1
Java Runtime Environment
Objectives 6
Pre-Test Questions 6
Introduction 7
The Java Virtual Machine 7
The Java 2 Software Development Kit 8
Installation 8
Creating a Simple Applet 13
Java Comments 14
Sun Certification 15
Summary 16

Post-Test Questions 16
6 Chapter 1—Java Runtime Environment
OBJECTIVES
At the completion of this chapter, you will be able to:
Identify the differences between stand-alone applications and applets.
Describe the role of the Java Virtual Machine.
Create a main() method.
Describe the differences between *.java and *.class files.
Use statement terminators.
Use Java comments.
PRE-TEST QUESTIONS
The answers to these questions are in Appendix A at the end of this manual.
1. What is the extension of a Java file?


2. What is the extension of a compiled Java file?


Introduction 7
INTRODUCTION
One of the major difficulties associated with programming over the years has been the
problem of creating cross-platform programs. How can one create software, which, when
compiled, will run exactly the same way from one type of computer to the next? This is
the problem for which Java was created. Java is a programming language which allows a
programmer to create and compile a program on one machine that will run on computers
with different operating systems. For example, one could create a program on an Apple
computer that could then run on Windows, Linux, or Solaris. This is a definite advantage
over standard programming languages which require that programs be compiled for each
operating system. In this chapter we will walk through a basic installation of the Java
Development Kit (JDK) and the creation, compilation and execution of a small Java

program.
THE JAVA VIRTUAL MACHINE
The Java Virtual Machine (JVM) separates Java from most other programming
languages. One of the primary design goals of the Java language is to enable the same
code to run on any platform. The JVM is a software program that behaves like an entire
computer. By using this virtual computer on different platforms (UNIX, Win32,
Macintosh, and so forth), you can reuse programs without creating a version for each
platform. You will always run Java programs in a JVM.
Java allows you to write stand-alone applications (Java programs that need not be run in a
browser), servlets (Java applications that run on a server) or applets (which must be run in
a Web browser or a program called Appletviewer). When the code is compiled, the
compiler creates bytecode that is stored in a .class file. The virtual machine is responsible
for interpreting this byte code into a machine-useable format.
Because of the combination of compilation and interpretation, Java is considered to be a
hybrid language. Note that many compilers exist that will compile Java code into a native
format. If this is done, the compiled program will not be portable; however, the program
will execute without the virtual machine.
8 Chapter 1—Java Runtime Environment
THE JAVA 2 SOFTWARE DEVELOPMENT KIT
The development platform used in this course is the Java 2 Software Development Kit
(SDK), Standard Edition, v 1.2.2 or higher. The Java 2 SDK was previously known as the
Java Development Kit (JDK) 1.2, and it is backward compatible with JDK 1.1. It
contains several components, including:
The Java Runtime Environment (JRE), which provides the JVM.
The development tools and compilation libraries necessary to create Java
applications and applets. This grouping includes the Java compiler, debugging
programs and tools to run applets without a browser.
INSTALLATION
Below are the installation procedures for Microsoft Windows and Linux operating
systems. If you do not have the current software from Sun, you can download it from

Look for the most recent release of the Java2 Software
Development Kit (SDK) Standard Edition. At the time of this writing the latest release
was version 1.3.
Installation 9
Windows 95/98/Me
1. Once you have the installer program downloaded to your computer, simply run it
by double clicking its icon.
2. You will be prompted to accept some license agreements and to select an install
directory (The default for the current release is C:/jdk1.3, if you change this you
should note the path to which you change it).
3. You will also be prompted for the various packages to install (Again, it is
recommended to install all of them, although if you are short of disk space, the
demo and/or the sources packages would probably suffice). Once you have
selected the packages you want, the installation program will do its job.
4. Once the installation program is finished, you should put the Java directory into
your Path so that it can be run from any directory. To do this, click Start/Run and
run sysedit. In AUTOEXEC.BAT you need to edit the PATH statement to
include the directory containing the Java executables. These executables are in the
\bin directory within the installation directory that you chose in step 2. Here is an
example of a PATH statement where Java was installed to the default directory.
The text after the last semicolon is what you would need to add.
PATH C:\WINDOWS;C:\WINDOWS\COMMAND;C:\JDK1.3\BIN
You can then activate your changes by opening a Command Prompt window and
typing “autoexec.bat” at the prompt. If you do not do this, the PATH will not be
reset until you restart Windows.
5. To check that Java has been set up correctly, open up a Command Prompt window
and type
javac - if everything is set up correctly, it should return usage options.
Windows NT/2000
The installation procedure for NT and 2000 should be done while logged in as

administrator. The process itself is identical to that for Windows 95/98/Me except for
the PATH setting procedure.
To set the PATH in NT/2000, go to the Control Panel and double click the System Icon.
Go to the Advanced tab and select Environment. Look for “Path” in the System Variables
list and edit it as was described above. Then click OK, SET, or APPLY. The new Path
will take effect with every new Command Prompt window you open.
10 Chapter 1—Java Runtime Environment
Linux
At the time or this writing, Sun provided two methods of installation on a Linux
machine, one via RPM file and one via shell script. The following procedure utilizes the
shell script method as it is generally not dependent on the version of Linux you are
running.
1. Once you have the installation file saved to your computer, move it to the
directory you want to install java in (it will make its own subdirectory), and make
the program executable. To make it executable, open a terminal (if you are in
X Window) and type
chmod +x j2sdk*.bin
2. Then run the program by typing the file’s name at the prompt, for example:
johndoe$ ./j2sdk-1_3_0-linux.bin
3. You will be prompted to accept the licensing agreement. If you agree, type yes.
The installation program will unpack the files and install them in the directory you
chose in step 1. Once it is finished, if you type “ls” you should see a new directory
named jdk1.# that corresponds to the package you installed.
4. Now you should set the Path environment variable to point to the directory
containing the java executables. The method for doing this varies with the type of
shell you are working under (bash,csh,sh etc ), so it is left to the reader to decide.
5. Once the PATH is set, you can test that it is correct by going to a command
prompt and, from any directory, typing
javac. If everything is set correctly, it
should return usage options.

Installation 11
Creating a Simple, Stand-Alone Application
You will begin writing a simple program by defining a class. Give the class a name and a
pair of braces to contain the body of the class. By convention, the class name should start
with a capital letter as in the following example:
class HelloWorld
{
}
When you write a stand-alone application, the Java Virtual Machine must know where to
begin executing the code. To begin executing code, the JVM looks for and calls a special
method by the name of
public static void main(String[] args). The JVM uses this method
to begin executing your program.
class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
This program is complete. Note that Java programs are case-sensitive; the word Class is
not the same as class. You must save the program with your text editor as
HelloWorld.java
(giving it the same name as your class), and compile it using a Java compiler. You can use
the
Javac program if you have the Java 2 Software Development Kit (SDK) supplied by
Sun.
javac HelloWorld.java
The Java compiler converts your source code (saved as HelloWorld.java, a text file) to the
HelloWorld.class file. This *.class file is no longer a standard text file, but a file compiled

into bytecode.
12 Chapter 1—Java Runtime Environment
Bytecode is another element that makes Java different from other programming
languages. Other compiled programming languages generate machine dependent
binaries, which are files that contain native machine language statements. To make Java
portable, the Javac compiler generates bytecode. Java bytecode is composed of an
instruction set native only to the JVM. Because JVMs exist for multiple platforms, the
Java bytecode is portable to any JVM. This portability makes Java incredibly powerful,
while at the same time, it makes Java less robust than languages such as C++.
TECH TIP:
As noted earlier, bytecode is interpreted by the JVM. However, the loss of speed
caused by interpretation can be overcome. If the code is compiled into native
binaries, the program will execute like any other binary.
To execute the program, you must run it in a JVM. This is accomplished by going to the
command prompt and invoking the Java interpreter
java:
java HelloWorld
Note that you type java HelloWorld, not java HelloWorld.class. When you enter the
proper command, the JVM will display
"Hello World!" in a command line window. The
Java application development cycle is shown in Figure 1-1.
Figure 1-1: Java development cycle
*.java *.class Output Window
Text Editor javac java
Creating a Simple Applet 13
CREATING A SIMPLE APPLET
Applets are Java programs that run within a Java-enabled Web browser. They do not
utilize the main() method as stand alone applications do. Instead there is a hierarchy of
methods that are run at startup. This will be discusses in more detail later. For now,
open up a text editor and enter the following program.

import java.applet.Applet;
import java.awt.Graphics;
public class HelloApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString(“Hello World”, 10, 10);
}
}
Save this file as HelloApplet.java (you MUST give the file the same name as the primary
class). Once it is saved, compile it. Open a command prompt, go to the directory you
saved the file in and type
javac HelloApplet.java
This will, if successful, generate a bytecode file named HelloApplet.class.

×