Click on the Source Code button to get to the source code page.. The source code and class files are organized under their respective chapters.. The file extension for the source code is
Trang 1Java SDK
Click on the Java SDK button to get to this page From this page, you can run the installation file, which will install Java SDK, version 1.3.1 There are different files depending on which operating system you have Look for the file that is right for your operating system If you have any Windows version, look under the Microsoft section If you are using Linux, look under the Linux x86 section If you want to install the SDK on a Solaris machine, look under the Solaris SPARC/x86 section You can find the instructions for installing and setting up the SDK for your system in Chapter 1, “Getting Started.”
You can also find the Java Documentation installation here You can either install the documentation on your system or browse it online on Sun’s Web site by using
the URL http://java.sun.com/j2se/1.3/docs/.
Source Code
All of the source code of the examples in this book can be found on the CD-ROM Click on the Source Code button to get to the source code page The source code and class files are organized under their respective chapters Each chapter gives you the option to either browse or download the files If you chose to download, click the Download button The download file is in ZIP format, so you will need
an unzip tool, such as Winzip (included on the CD-ROM), to unpack the files into the local directory of your choosing If you choose to browse the files without sav-ing them to your local disk, click Explore A new window will open up that con-tains the files associated with that chapter The file extension for the source code
is java You can open this file with any text editor since it is a straight text file.
It is still possible to run the example programs without installing them locally.
To do this, you need to open up a shell (command prompt) and change to the class file directory For example, if you’re using Windows and your CD-ROM drive letter is D, to run the HelloWorldexample from Chapter 1, you need to change to the directory D:\Source Code\Chapter 1\ Next, you need to run the java com-mand on the program (Note: you can only do this after you’ve installed the SDK.) For example, this is what you type at your command prompt to run the Hel-loWorldapplication: java HelloWorld.
478
J a
s o
l ut
n e
Trang 2Web Links
The Web Links section includes links to some useful Internet sites To get to this section, simply click the Web Links button The links you will find there are:
Sun Java This takes you directly to Sun’s Java Web site.
(http://java.sun.com).
Sun Microsystems This takes you to Sun’s main Web site Sun
Microsystems is the innovator behind Java
technology (http://www.sun.com).
Sun Educational Services Here you can learn how to further your Java
education and become a Sun-certified Java
programmer! (http://suned.sun.com).
East Coast Games A site written by programmers that you can
use as a resource for your video game
pro-gramming endeavors
(http://www.east-coastgames.com).
NetBeans NetBeans is an open source integrated
devel-opment environment (IDE) that you can download and use to facilitate your Java
appli-cation programming projects
(http://www.net-beans.org).
Programs
This section includes some programs that you can install and use on your system.
To get to this section, click on the Programs button For installation instructions, visit the Web site link, which is under the program name listing on this page The programs are:
Cool Edit Pro This is a demo version of a very cool audio
editing program.
The GIMP The GIMP is a powerful image-editing tool.
Just install it and thank me later It rocks.
Internet Explorer 5.5 Microsoft’s very popular Internet browser.
You can install this latest version and run the applet examples from the book with it.
Winzip 8.0 Winzip is a great tool for packaging and
unpacking file archives.
479
Trang 4Reserved Words
The following list included Java’s reserved words, also known as key-words You cannot use them to name identifiers.
continue goto package synchronized The booleanliterals trueand false, and the nullliteral, although not technically keywords, cannot be used as identifiers either.
Java Language
Summary
B
A P P E N D I X
Trang 5Primitive Data Types
boolean 1
Ranges for Integral Types
Floating-Point Constants
Float.NEGATIVE_INFINITY Float.POSITIVE_INFINITY Float.NaN
Double.NEGATIVE_INFINITY Double.POSITIVE_INFINITY Double.NaN
NaN stands for “not a number” and represents values of undefined operations such as 0.0 / 0.0.
482
J a
s o
l ut
n e
Trang 6Comments
There are three types of comments used in Java (single line, multi-line, and javadoc).
This is a single line comment example:
// this is a single line comment This is a multi-line comment example:
/* this is a multi-line comment */
This is a javadoc comment example:
/**
* This is a javadoc comment
*/
Literals
Literals are used in Java to represent values that are of the primitive, String, or nulltypes in source code The following sections summarize their syntaxes Any-thing within square braces ([and ]) is optional and the bar character (|) sepa-rates different options For example, [+|-]means the code can include +, -, or neither (because they are within square brackets).
Integer Literals
Integer literals can be expressed in octal (base 8), decimal (base 10), or hexadeci-mal (base 16) Octal digits can be any digits from 0 to 7 Decihexadeci-mal digits can be any digits ranging from 0 to 9 Hexadecimal digits can be any digit ranging from 0 to
9 and also any letter (case-insensitive) from A to F A=10, B=11, C=12, D=13, E=14, F=15 The syntax for an integer literal is:
[+|-][0[X|x]]number[L|l]
67 intliteral having value 67 +67 intliteral having value 67 -67 negative intliteral having value –67
012 octal intliteral having value 10
483
Trang 7-0X27C hexadecimal intliteral having value –636
1234567890L longliteral having value 1,234,567,890 -0XBEL hexadecimal longliteral having value -190
Floating-Point Literals
A floating-point literal can be either a floator a double The syntax for a float-ing-point number is:
[+|-]number.number[[+|-]Eexponent|[+|-]eexponent][F|D|f|d]
-10 doubleliteral having value -10.0 +.01 doubleliteral having value 0.01 1.23 doubleliteral having value 1.23 1.23d doubleliteral having value 1.23 1.23f floatliteral having value 1.23 2E4 doubleliteral having value 20,000.0 (2x104) -133e-2F floatliteral having value -1.33 (-133x10-2)
Boolean Literals
Boolean literals must be either trueor false.
Character Literals
A character literal is a single character or escape sequence enclosed in single quotes The data type of a character literal is always char A Unicode character escape sequence is in the form \unnnn, where nnnnis the hexadecimal represen-tation of the character The syntax for a character literal is (exactly one character
or escape sequence must appear within the single quotes):
'character|escape_sequence'
'a' charliteral a '$' charliteral $ '\u003F' charliteral ? '\'' charliteral ' (single quote) '\"' charliteral " (double quote)
484
J a
s o
l ut
n e
Trang 8'\b' charliteral for backspace '\f' charliteral for form-feed '\n' charliteral for new line '\r' charliteral for carriage return '\t' charliteral for tab
'\\' charliteral for backslash (\)
String Literals
A string literal consists of a string of characters and/or escape sequences within double quotes The data type is always String The syntax for a Stringliteral is:
"[characters&|escape_sequences]"
"\"Java\"" Stringliteral "Java"
"C:\\My Documents\\myfile.txt" Stringliteral C:\My
Documents\myfile.txt
Null Literal
The null literal is null.
Operators
In the following table, argrefers to any variable or value Some operators only take certain types of arguments For example, !only works on Boolean types.
Unary +arg, -arg Sign (positive or negative)
++variable Prefix increment
variable++ Postfix increment
variable Prefix decrement
variable Postfix decrement
485
Trang 9Arithmetic arg + arg Addition
arg - arg Subtraction
arg * arg Multiplication
arg / arg Division
arg % arg Modulus Shift arg >> arg Left shift
arg >> arg Right shift
arg >>> arg Unsigned right shift Comparison arg < arg Less than
arg > arg Greater than
arg <= arg Less than or equal to
arg >= arg Greater than or equal to
arg == arg Equal to
arg != arg Not equal to
arg instanceof Instance of
class
Bitwise arg & arg Bitwise AND
arg | arg Bitwise OR
arg ^ arg Bitwise XOR Logical arg && arg Logical AND
arg || arg Logical OR Ternary condition ?
val_if_true : val_if_false Conditional operator
Assignment Operators
Assignment operators store a value into a variable This section covers the opera-tors that included the equals sign (=), however, the increment (++) and decrement ( ) operators perform assignments as well The assignment operator can be just the equals sign or the equals sign followed by an additional operator (although the combination of the two constitutes one single operator) The syntax for the assignment operator is:
variable =[op] arg
486
J a
s o
l ut
n e
Trang 10If = is combined with another operator, the operation is logically equivalent to:
variable = variable op arg
The following are all assignment operators:
>>= >>>=
Loops
forloop for([init, init, …];[condition];[update, update, …])
{ body }
whileloop while(condition) { body }
doloop do { body } while (condition);
Break and Continue
The breakand continuestatements redirect the flow of loops breaktakes con-trol out of the loop and continuereturns control to the top of the loop.
Conditionals
The conditional statements are if, switch, and also the Ternary operator described in the “Operators” section The syntax for the if conditional is (the square brackets [] indicate that the else ifand elsestatements are optional and are not part of the syntax):
if (condition) { statements_condition_true;
}
[else if (other_condition) { statements_other_condition_true;
}, …]
[else {
statements_no_condition_true;
}]
487
Trang 11The syntax for the switchconditional is:
switch (test) { case value: [statements_test_equals_value] [break;]
…
[default: [statements_test_equals_no_case_value]
}
Try… Catch Blocks
Try… catchblocks are used for exception handling Here is the syntax:
try {
statements_that_might_cause_an_exception;
} catch (exception_type exception_variable_name) { [statements_that_execute_if_exception_is_caught]
}
Class Definition
The syntax for defining a class follows:
[package package_name;]
[[import Imported_class_or_package;] …]
[access_modifier] class class_name [extends super_class_name] [implements implemented_Interface, …] {
[class_definition]
}
Class Modifiers
public Access modifier final Class cannot be subclassed abstract Must be subclassed (cannot be instantiated)
Constructor Definition
The syntax for a constructor is as follows The first line of the constructor body must be either an explicit call to the superclass’s constructor using super(), an
488
J a
s o
l ut
n e
Trang 12implied call to the superclass’s no-argconstructor, or a call to another construc-tor within this class using this():
[access_modifier] class_name([arg, …]) { [constructor_body] }
Variable Declaration
The syntax for declaring a variable is as follows:
[access_modifier] [modifier, ] type variable_name [ = initial_value];
Variable Modifiers
public protected private Access modifiers static Indicates this is a class variable
transient Indicates a variable that cannot be serialized volatile Indicates that variable may be modified
asynchronously
Method Definition
The syntax for defining a method is as follows Unless the return type is void, the last executable statement of any logical path of execution within the method must be a returnstatement that returns a value of type return_type:
[access_modifier] [modifier, …] return_type method_name([arg, …]) [throws exception, …] { [body] }
Method Modifiers
public protected private Access modifiers static Indicates this is a class method final Indicates that this method cannot be
over-ridden abstract Indicates the body must be defined in a
subclass
489
Trang 13native Indicates the method body is defined
out-side of Java in a native library synchronized Indicates that, at most, only one thread can
have control of this method at any given time
490
J a
s o
l ut
n e
Trang 14// (double slashes), 18 / (division operator), 37
- (subtraction operator), 37 + (addition), 37
$ (dollar sign), 31
% (modulus operator/division remainder), 37
* (multiplication operator), 37 _ (underscore), 31
3D rectangles, drawing, 319–320
A
abstract classes, 435–436 Abstract Windowing Toolkit See AWT access modifiers, 143–145
ActionEvents class, 247–249 action commands, 252–255 knowing source of, 248–252 methods, list of, 248–249 addition (+), 37
AdjustmentEvents class, 258–260 animations
double buffering, 367–369 ShootingRange game example, 370–376 Sprite class
overview, 363–364 testing, 365–367 applets
Applet class, 282–284 applets versus applications, 279 creating, 20–21
defined, 20, 279
destroy() method, 290–292 functions of, 20
HelloWeb applet example program, 280–281
HTML document, incorporating in, 21–22
images and, 304–306 init() method, 290–292 methods, list of, 281 QuizShow applet example, 306–310 running, 21–22
sound files, 302–304 start() method, 290–292 status messages, printing, 293 stop() method, 290–292
in Web pages, 282–284 applet HTML tag, 284–285 passing parameters to applets, 284–288
security restrictions, 290–291 using frames with, 288–290 writing Java programs as, 294 rewriting MadInputPanel example, 295–298
rewriting MadLib game example, 298–301
appleviewer utility, 20–22 applications
applications versus applets, 279 examples of See example code playing sound from, 369–370 arcs, drawing, 321–324
arguments, command-line arguments, 46–47
Index
Trang 15arrays ArrayTest program example, 88–89 declaring, 85–86
defined, 85 elements, assigning values to, 85–88 looping on, 104–106
multidimensional, 87–89 subscripts, 85–86 assigning values to variables, 31–34 AWT (Abstract Windowing Toolkit), 172–173 components
buttons, 184–187 canvas, 202–203 checkbox, 198–202 choice, 192–195 dialog, 211–214 labels, 182–185 list, 195–198 listof, 173–176 menu, 203–207 panel, 208–209 pop-up menu, 206–208 scrollbar, 209–213 text area, 190–193 textfield, 186–191 events, 177
Frame component, 178–180 graphics, 177–178
package classes, 172–173
B
blackjack card game addUpPoints() method, 168 Card class, writing, 147–151 CardDeck class, 150–153 deal() method, 152 dealerBlackJack() method, 168 deck’s list() method, 126–127 explanation of, 122–123 hitDealer() method, 168
hitPlayer() method, 168 isPictureCard() method, 167 play() method, 167–168 playerBlackJack() method, 168 private hit() method, 168 RandomCardDeck class, 158–160 reset() method, 152
shuffle() method, 158–160 SimpleCardDeck class example, 123–127 source code, example of, 162–167 updatePoints() method, 168 Vector class, 160–163 Block Game
block area, 378–380 block shape, 378–380 BlockGame.java, source code listing, 423–427
BlockGrid class, creating addBlock() method, 385–386 block area, 384–386 blockOutOfBounds() method, 387–388 collision detection, 388–389
methods, list of, 386–387 removeBlock() method, 385–386 setBlock() method, 385–386 source code listing, 389–392 Block.java application, source code listing, 381–384
blockOutOfArea() method, 388–389 BlockTest.java application, source code listing, 384
concept of, 378 controls, 378 createBlock() method, 423–424 introduceNextBlock() method, 423–424 PlayArea class
block movements, 401–403 EventThread inner class, 407–409 falling blocks, 404–407
inner classes, 398–401
492
d e