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

Sybex java 2 complete certification 3rd edition jul 2002 ISBN 0782140777 pdf

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 (9.31 MB, 756 trang )

Using Your Sybex Electronic Book
To realize the full potential of this Sybex electronic book, you must have Adobe Acrobat Reader with
Search installed on your computer. To find out if you have the correct version of Acrobat Reader, click on
the Edit menu—Search should be an option within this menu file. If Search is not an option in the Edit
menu, please exit this application and install Adobe Acrobat Reader with Search from this CD (doubleclick rp500enu.exe in the Adobe folder).

Navigation
Navigate through the book by clicking on the headings that appear in the left panel;
the corresponding page from the book displays in the right panel.

Search

To search, click the Search Query button
on the toolbar
or choose Edit >Search > Query to open the Search window. In
the Adobe Acrobat Search dialog’s text field, type the text you
want to find and click Search.
Use the Search Next button
(Control+U) and Search
Previous button
(Control+Y) to go to other matches in
the book. The Search command also has powerful tools for
limiting and expanding the definition of the term you are
searching for. Refer to Acrobat's online Help (Help > Plug-In
Help > Using Acrobat Search) for more information.

Click here to begin using
your Sybex Elect ronic Book!

www.sybex.com



Complete Java™ 2
Certification
Study Guide
Third Edition

Philip Heller
Simon Roberts

San Francisco • London
Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


Associate Publisher: Richard Mills
Acquisitions and Developmental Editor: Denise Santoro Lincoln
Editor: Tiffany Taylor
Production Editor: Dennis Fitzgerald
Technical Editors: Michael Dailous, Natalie Levi, Kathy Collina, Bryan Basham
Book Designer: Bill Gibson
Graphic Illustrator: Tony Jonick
Electronic Publishing Specialist: Interactive Composition Corporation
Proofreaders: Nelson Kim, Dave Nash, Laurie O’Connell, Yariv Rabinovitch, Nancy Riddiough
Indexer: Ted Laux
CD Coordinator: Dan Mummert
CD Technician: Kevin Ly
Cover Designer: Archer Design
Cover Illustrator/Photographer: John Wang, PhotoDisc
Copyright © 2002 SYBEX Inc., 1151 Marina Village Parkway, Alameda, CA 94501. World rights reserved. No part of this

publication may be stored in a retrieval system, transmitted, or reproduced in any way, including but not limited to photocopy, photograph, magnetic, or other record, without the prior agreement and written permission of the publisher.
Library of Congress Card Number: 2002101979
ISBN: 0-7821-4077-7
SYBEX and the SYBEX logo are either registered trademarks or trademarks of SYBEX Inc. in the United States and/or other
countries.
Screen reproductions produced with Collage Complete.
Collage Complete is a trademark of Inner Media Inc.
TRADEMARKS: SYBEX has attempted throughout this book to distinguish proprietary trademarks from descriptive terms
by following the capitalization style used by the manufacturer.
The author and publisher have made their best efforts to prepare this book, and the content is based upon final release software whenever possible. Portions of the manuscript may be based upon pre-release versions supplied by software manufacturer(s). The author and the publisher make no representation or warranties of any kind with regard to the completeness
or accuracy of the contents herein and accept no liability of any kind including but not limited to performance, merchantability, fitness for any particular purpose, or any losses or damages of any kind caused or alleged to be caused directly or
indirectly from this book.
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


To our valued readers,
The success of Sun’s Java certification program has surpassed all expectations; it is now widely
recognized as the hottest programmer certification. Java is now a first-class citizen in the world of
programming languages and increasing use of the Java 2 Platform for enterprise-class applications
has fueled demand for the certifications.
Sybex is proud to have helped thousands of candidates for the Programmer and Developer certifications prepare for these challenging exams since the publication of the first edition of Complete Java
Certification Study Guide in 1997. Authors Philip Heller and Simon Roberts have played a major role
over the years in developing these exams for Sun, and their best-selling book has established a strong
reputation as the exam preparation guide of choice.
The authors and editors have worked hard to ensure that the new edition you hold in your hands is

comprehensive, in-depth, and pedagogically sound. We’re confident that this book will exceed the
demanding standards of the certification marketplace and help you succeed in your endeavors.
As always, your feedback is important to us. Please send comments, questions, or suggestions to
At Sybex we’re continually striving to meet the needs of individuals preparing
for IT certification exams.
Good luck in pursuit of your Java certification!

Richard Mills
Associate Publisher—Programming
Sybex Inc.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


Software License Agreement: Terms and Conditions
The media and/or any online materials accompanying this
book that are available now or in the future contain programs
and/or text files (the “Software”) to be used in connection with
the book. SYBEX hereby grants to you a license to use the Software, subject to the terms that follow. Your purchase, acceptance, or use of the Software will constitute your acceptance of
such terms.
The Software compilation is the property of SYBEX unless
otherwise indicated and is protected by copyright to SYBEX
or other copyright owner(s) as indicated in the media files
(the “Owner(s)”). You are hereby granted a single-user
license to use the Software for your personal, noncommercial
use only. You may not reproduce, sell, distribute, publish,
circulate, or commercially exploit the Software, or any portion thereof, without the written consent of SYBEX and the
specific copyright owner(s) of any component software

included on this media.
In the event that the Software or components include specific
license requirements or end-user agreements, statements of
condition, disclaimers, limitations or warranties (“End-User
License”), those End-User Licenses supersede the terms and
conditions herein as to that particular Software component.
Your purchase, acceptance, or use of the Software will constitute your acceptance of such End-User Licenses.
By purchase, use or acceptance of the Software you further
agree to comply with all export laws and regulations of the
United States as such laws and regulations may exist from
time to time.
Software Support
Components of the supplemental Software and any offers
associated with them may be supported by the specific
Owner(s) of that material, but they are not supported by
SYBEX. Information regarding any available support may be
obtained from the Owner(s) using the information provided in
the appropriate read.me files or listed elsewhere on the media.
Should the manufacturer(s) or other Owner(s) cease to offer
support or decline to honor any offer, SYBEX bears no
responsibility. This notice concerning support for the Software is provided for your information only. SYBEX is not the
agent or principal of the Owner(s), and SYBEX is in no way
responsible for providing any support for the Software, nor is
it liable or responsible for any support provided, or not provided, by the Owner(s).
Warranty
SYBEX warrants the enclosed media to be free of physical
defects for a period of ninety (90) days after purchase. The
Software is not available from SYBEX in any other form or
media than that enclosed herein or posted to www.sybex.com.


If you discover a defect in the media during this warranty
period, you may obtain a replacement of identical format at no
charge by sending the defective media, postage prepaid, with
proof of purchase to:
SYBEX Inc.
Product Support Department
1151 Marina Village Parkway
Alameda, CA 94501
Web:
After the 90-day period, you can obtain replacement media
of identical format by sending us the defective disk, proof of
purchase, and a check or money order for $10, payable to
SYBEX.
Disclaimer
SYBEX makes no warranty or representation, either expressed
or implied, with respect to the Software or its contents, quality, performance, merchantability, or fitness for a particular
purpose. In no event will SYBEX, its distributors, or dealers be
liable to you or any other party for direct, indirect, special,
incidental, consequential, or other damages arising out of the
use of or inability to use the Software or its contents even if
advised of the possibility of such damage. In the event that the
Software includes an online update feature, SYBEX further
disclaims any obligation to provide this feature for any specific
duration other than the initial posting.
The exclusion of implied warranties is not permitted by some
states. Therefore, the above exclusion may not apply to you.
This warranty provides you with specific legal rights; there
may be other rights that you may have that vary from state to
state. The pricing of the book with the Software by SYBEX
reflects the allocation of risk and limitations on liability contained in this agreement of Terms and Conditions.

Shareware Distribution
This Software may contain various programs that are distributed as shareware. Copyright laws apply to both shareware
and ordinary commercial software, and the copyright
Owner(s) retains all rights. If you try a shareware program
and continue using it, you are expected to register it. Individual programs differ on details of trial periods, registration,
and payment. Please observe the requirements stated in
appropriate files.
Copy Protection
The Software in whole or in part may or may not be copyprotected or encrypted. However, in all cases, reselling or
redistributing these files without authorization is expressly
forbidden except as specifically provided for by the Owner(s)
therein.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


To Richard Philip Gross, 1903–2002: a man of his century, and so much more
—Philip
For my children, Emily and Bethan
—Simon

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


Acknowledgments


Thanks to Ginni for all the radiance. Thanks to Michelle and Ricardo
for keeping me on my toes.
Thank you to Natalie Levi, Bryan Basham and Kathy Collina.
—Philip Heller
The authors would like to thank the people at Sybex: Richard Mills,
Denise Santoro Lincoln, Dennis Fitzgerald, Tiffany Taylor, Ted Laux, Dan
Mummert.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


Introduction

Hello! Come in, sit down, and make yourself at home. Please get
comfortable; there are a lot of topics to cover in this book.
You have come here because you are ready. Ready to get ready, at least,
which is practically the same thing. Now all that’s left to do is the work.
And there is a lot of work to be done. Probably you have heard that the
Programmer’s and Developer’s Exams are difficult, and it’s true. Not everybody passes, even on repeated attempts. We want to change these statistics
by offering you a little help.

About the Authors
This is, after all, the introduction, so allow us to introduce ourselves: We are
Phil and Simon. (We used to be Simon and Phil, but we’re trading off in this
edition and now Phil is the lead author. The only difference it makes is that
you probably found this book under under “H” instead of “R”.) Now that
we’ve met, you might wonder why you should trust a couple of guys you just
met, who claim to know about the certification exams. Very good question.

A lot of people are writing study guides and websites. Who should you trust?
We hope you will choose us. We have the best background of any team
around. Simon led the group that wrote all the questions for the exams. He
continues to be the driving force behind exam development. Phil is an ongoing consultant for development of the exams, is one of the assessors for the
Developer’s Exam, and wrote the technical proposal for the new revision of
the Developer’s Exam; so, he also has an inside view.
Our unique relationship with Sun (Simon as an employee, Phil as a consultant) places a few restrictions on us. We can’t give away any answers to
the questions on the exams. (We wouldn’t want to do that anyway; we
want you to pass because you’re good at Java, not because we slipped you
a crib.) We had to make sure the sample questions did not accidentally
match any of the real test questions. It took a bit more work, but we think
the benefit to you is tremendous: Everything in this book is here for a very
good reason. If it’s here, then we know you need to know about it. We
understand that buying a book like this costs you money, reading it costs
you time, and absorbing it costs you effort. We appreciate your investment,
and we believe it will pay off.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


xxiv

Introduction

If you read this book, absorb it, solve the practice questions at the end of
each chapter, and work through the practice exam on the CD-ROM, you
will be in the best possible position when you walk through the doors of your
local testing center.


The Importance of Certification
How important is certification? Importance is a tricky concept, and it has a
lot to do with opinion and subjective experience. Of course we believe certification is very important, because we spent all this time writing a book
about it. But what does the rest of the world believe? It would be useful if we
could just quote the statistics for you: This many people take the exams each
month, this many pass; the curves grow at this rate, have this second derivative, predict this trend. Unfortunately we’re not allowed to do that. Sun
treats all such information as confidential. Not just wink-nudge confidential,
but really confidential. Don’t trust any statistics anybody tries to give you.
We can’t give you the raw numbers, but we can give you four pieces of
anecdotal evidence that show the world is taking Java certification very
seriously:
Sales of the previous editions of this book have been, well, gratifying.
We would like to express our sincere gratitude to all the readers who
have previously bought the book, read it, and used it to gain their
certification.
Other publishers are deciding that Java certification is big enough that
they should get in the game. We have even seen at least one book that
is as close as it can legally come to being a shameless imitation of ours.
The sincerest form of flattery! We still believe we can give you the best
information, because we designed the Programmer’s and Developer’s
exams and continue to maintain them.
Attendance at Phil’s “Fast-Path Java Platform Certification” seminar
is strong despite the downturn in the tech economy and the shrinking
of the tradeshow and technical education sectors.
The fourth bit of evidence is a program that was announced at the
June 1999 JavaOne conference. Four impressive companies—IBM,
Oracle, Novell, and Netscape—joined with Sun in an initiative to
endorse Java certification. The endorsements took the form of action,
not just words and press releases. (You can read about the details of

this initiative and its current member companies in Appendix D, “The

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


Introduction

xxv

Certification Initiative for Enterprise Development.”) The big idea is
that the member companies, along with Sun, are throwing their considerable weight behind the proposition that people who claim to
know how to program in Java should be able to prove it. This is in
marked contrast to a hiring philosophy that was prevalent a few years
ago when the economy was ridiculously strong. The old hiring criterion was to see if the candidate’s resume said “Java” on it somewhere.
If the candidate passed this test, a cold mirror was held in front of the
candidate’s mouth. Misty condensation on the mirror meant “hire”;
no condensation meant “don’t hire, this one isn’t breathing.” Friends
in the medical profession assure me that even a person in a coma can
fog a mirror. But they can’t write good code, and the certification initiative is out to replace the mirror test with much more difficult exams.
Everybody who worked on this book is extremely pleased with how it
turned out. We hope you enjoy reading it, enjoy taking the exams, greatly
enjoy being told that you have passed, and boundlessly enjoy the career freedom that certification brings.

What’s New in This Edition?
We have kept the basic organization of the original book, but we have gone
over the content with a fine tooth comb. We have also added some new
material that we think you’ll really like:
We added over 100 questions to the CD-ROM. These, in addition to

the 150 that were already on the CD-ROM, the questions at the end
of each chapter, and the 50-question “Programmer’s Final Exam,”
should get you good and ready.
We updated our coverage of the Programmer’s Exam to reflect the
new revision, which covers the J2SE 1.4 revision of Java.
We updated our coverage of the Developer’s Exam to reflect the new
revision.
We added an appendix that describes Sun’s other Java exams.

Taking the Exam
You can take the Java Certification Exam whenever you like, by making an
appointment with Sun Educational Services. Sun contracts with third-party
test centers throughout the world, so hopefully you won’t have to travel far.
The cost of taking the exam is $150.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


xxvi

Introduction

The U.S. telephone number for Sun Educational Services is (800) 422-8020;
their URL is . From there it will be easy to find the links
you need. We hesitate to give more detailed instructions, because the site
changes fairly often.

You can make an appointment for any time during regular business hours.

When you make the appointment, ask how much time you will have. This is
subject to change; on average, you’ll be given two minutes per question. You
will not be allowed to bring food or personal belongings into the test area. One
piece of scratch paper is permitted; you will not be allowed to keep it after you
have finished the exam. Most sites have security cameras.
You will be escorted to a cubicle containing a PC. The exam program will
present you with randomly selected questions. Navigation buttons take you
to the next or previous question for review and checking. When you have finished the test, the program will immediately present you with your score and
a pass/fail indication. You will also be given feedback that indicates how well
you performed in each of the dozen or so categories of the objectives. You
will not be told which particular questions you got right or wrong.

Formalities of the Exam
There are no trick questions on the exam, but every question requires careful
thought. The wording of the questions is highly precise; the exam has been
reviewed not just by Java experts, but also by language experts whose task
was to eliminate any possible ambiguity. All you have to worry about is
knowing Java; your score will not depend on your ability to second-guess the
examiners.
It is not a good idea to try to second-guess the question layout. For example,
do not be biased toward answer C simply because C has not come up recently.
The questions are taken from a pool and presented to you in a random order,
so it is entirely possible to get a run of a particular option; it is also possible to
get the answers neatly spread out.
Most of the questions are multiple-choice. Of these, some have a single
answer, and others require you to select all the appropriate responses. The
graphical user interface of the test system indicates which kind of answer you
should supply. If a question only has one correct answer, you will be presented
with radio buttons, so that selecting a second answer cancels the selection of


Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


Introduction

xxvii

a previous answer. With this kind of question, you have to select the most
appropriate answer. If, on the other hand, you are presented with check
boxes, then you may need to make more than one selection, so every possible answer must be considered on its own merits—not weighed against
the others.
You should be aware that where multiple answers are possible, you are
being asked to make a decision about each answer, rather as though the
question were five individual true/false questions. This requires more effort
and understanding from you, because you have to get all the pieces correct.
Think carefully, and always base your answer on your knowledge of Java.
The short-answer, type-in questions often cause undue concern. How
are they marked? What happens if you omit a semicolon? These worries
can stem from the knowledge that the questions are marked electronically
and the belief that an answer might be marked wrong simply because the
machine didn’t have the sense to recognize a good variation of what it was
programmed to accept.
As with all exam questions, you should be careful to answer precisely
what is asked. However, you should also be aware that the system does
accept a variety of different answers; it has been set up with all the variations
the examination panel considered to be reasonable.
Some of the type-in questions do, however, provide specific instructions
concerning the format of the answer. Take this guidance seriously. If, for

example, a question says, “Answer in the form methodname(),” then your
answer should be
method()
and not any of
object.method()
method();
method(a, b)
method
Some of the other answers might well be accepted, but programming is a precision job and you should be accustomed to following precise directions.
The test is taken using a windowed interface that can be driven almost
entirely with the mouse. Many of the screens require scrolling; the scroll
bar is on the right side of the screen. Always check the scroll bar so you can
be sure you have read a question in its entirety. It would be a shame to get
a question wrong because you didn’t realize you needed to scroll down a
few lines.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


xxviii

Introduction

The exam contains about 60 questions. On average, this gives you a
little more than two minutes per question. Some of the questions are easier
than others, and undoubtedly you will be able to answer some more
quickly than others. However, you really do need to answer all the questions if you possibly can. The test system allows you to review your work
after you reach the end. The system will explicitly direct your attention

toward any multiple-choice questions that have no items selected. So, if
you find a particular question difficult, consider moving on and coming
back to it later.

Conventions Used in This Book
This book uses a number of conventions to present information in as readable a manner as possible. Tips, Notes, and Warnings, shown here, appear
from time to time in the text in order to call attention to specific highlights.

This is a Tip. Tips contain specific programming information.

This is a Note. Notes contain important side discussions.

This is a Warning. Warnings call attention to bugs, design omissions, and
other trouble spots.

This book takes advantage of several font styles. Bold font in text indicates something that the user types. A monospaced font is used for code,
output, URLs, and file and directory names. A monospaced italic font is
used for code variables mentioned in text.
These style conventions are intended to facilitate your learning experience
with this book—in other words, to increase your chances of passing the exam.
Let’s begin.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


The
Programmer’s
Exam


Copyright ©2002 SYBEX, Inc., Alameda, CA

PART

I

www.sybex.com


Chapter

1

Language Fundamentals
JAVA CERTIFICATION EXAM OBJECTIVES
COVERED IN THIS CHAPTER:
Identify correctly constructed package declarations, import
statements, class declarations (of all forms including inner
classes) interface declarations, method declarations (including
the main method that is used to start execution of a class),
variable declarations, and identifiers.
Identify all Java programming language keywords. Note: There
will not be any questions regarding esoteric distinctions
between keywords and manifest constants.
State the range of all primitive formats, data types and declare
literal values for String and all primitive types using all
permitted formats bases and representations.
For a given class, determine if a default constructor will be
created and if so state the prototype of that constructor.

Write code that declares, constructs and initializes arrays of any
base type using any of the permitted forms both for declaration
and for initialization.
State the effect of using a variable or array element of any kind
when no explicit assignment has been made to it.
State the correspondence between index values in the
argument array passed to a main method and command line
arguments.
Determine the effect upon objects and primitive values of
passing variables into methods and performing assignments or
other modifying operations in that method.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


State the behavior that is guaranteed by the garbage
collection system.
Write code that explicitly makes objects eligible for
garbage collection.
Recognize the point in a piece of source code at which an
object becomes eligible for garbage collection.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


T


his book is not an introduction to Java. Because you are
preparing for certification, you are obviously already familiar with the fundamentals. The purpose of this chapter is to make sure you are 100 percent
clear on those fundamentals covered by the Certification Exam objectives.

Source Files

A

ll Java source files must end with the .java extension. A source
file should generally contain, at most, one top-level public class definition;
if a public class is present, the class name should match the unextended
filename. For example, if a source file contains a public class called
RayTraceApplet, then the file must be called RayTraceApplet.java.
A source file may contain an unlimited number of non-public class
definitions.

This is not actually a language requirement, but is an implementation requirement of many compilers, including the reference compilers from Sun. It is
therefore unwise to ignore this convention, because doing so limits the
portability of your source files (but not, of course, your compiled files).

Three top-level elements known as compilation units may appear in a file.
None of these elements is required. If they are present, then they must
appear in the following order:
1. Package declaration

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com



6

Chapter 1

Language Fundamentals

2. Import statements
3. Class definitions

The format of the package declaration is quite simple. The keyword
package occurs first, and is followed by the package name. The package
name is a series of elements separated by periods. When class files are
created, they must be placed in a directory hierarchy that reflects their
package names. You must be careful that each component of your package
name hierarchy is a legitimate directory name on all platforms. Therefore,
you must not use characters such as the space, forward slash, backslash, or
other symbols.
Import statements have a similar form, but you may import either an
individual class from a package or the entire package. To import an individual class, simply place the fully qualified class name after the import keyword
and finish the statement with a semicolon; to import an entire package,
simply add an asterisk to the end of the package name.
White space and comments may appear before or after any of these
elements. For example, a file called Test.java might look like this:
1.
2.
3.
4.
5.
6.

7.
8.
9.

// Package declaration
package exam.prepguide;
// Imports
import java.awt.Button; // imports a specific class
import java.util.*;
// imports an entire package
// Class definition
public class Test {...}

Sometimes you might have classes with the same name in two different
packages, such as the Date classes in the packages java.util and java.sql.
If you use the asterisk form of import—to import both entire packages—and
then attempt to use a class simply called Date, you will get a compiler error
reporting that this usage is ambiguous. You must either make an additional
import, naming one or the other Date class explicitly, or you must refer to
the class using its fully qualified name.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


Keywords and Identifiers

7


Keywords and Identifiers

The Java language specifies 52 keywords and other reserved words,
which are listed in Table 1.1.
TABLE 1.1

Java Keywords and Reserved Words

abstract

class

false

import

package

super

try

assert

const

final

instanceof


private

switch

void

boolean

continue

finally

int

protected

synchronized

volatile

break

default

float

interface

public


this

while

byte

do

for

long

return

throw

case

double

goto

native

short

throws

catch


else

if

new

static

transient

char

extends

implements

null

strictfp

true

The words goto and const are reserved: Although they have no meaning
in Java, programmers may not use them as identifiers.
An identifier is a word used by a programmer to name a variable, method,
class, or label. Keywords and reserved words may not be used as identifiers.
An identifier must begin with a letter, a dollar sign ($), or an underscore (_);
subsequent characters may be letters, dollar signs, underscores, or digits.
Some examples are:
1. foobar

// legal
2. BIGinterface
// legal: embedded keywords
3.
// are OK.
4. $incomeAfterExpenses // legal
5. 3_node5
// illegal: starts with a digit
6. !theCase
// illegal: must start with
7.
// letter, $, or _
Identifiers are case sensitive—for example, radius and Radius are
distinct identifiers.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


8

Chapter 1

Language Fundamentals

The exam is careful to avoid potentially ambiguous questions that require
you to make purely academic distinctions between reserved words and
keywords.


Primitive Data Types

Java’s primitive data types are
boolean
char
byte
short
int
long
float
double
The apparent bit patterns of these types are defined in the Java language
specification, and their effective sizes are listed in Table 1.2.
TABLE 1.2

Primitive Data Types and Their Effective Sizes

Type

Effective
Representation
Size (bits)

Type

Effective
Representation
Size (bits)

boolean


1

char

16

byte

8

short

16

int

32

long

64

float

32

double

64


Variables of type boolean may take only the values true and false.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


Primitive Data Types

9

The actual storage size and memory layout for these data items are not, in
fact, required by the language specification. The specification does dictate
the apparent behavior; so, for example, the effect of bit mask operations,
shifts, and so on are entirely predictable at the Java level. If you write
native code, you might find things are different from these tables. Importantly, this means that you cannot reliably calculate the amount of memory
consumed by adding up data sizes. However, the exam is careful to avoid
potentially ambiguous questions and asks about variables only from the Java
language perspective, not the underlying implementation.

The four signed integral data types are:
byte
short
int
long
Variables of these types are two’s-complement numbers; their ranges are
given in Table 1.3. Notice that for each type, the exponent of 2 in the
minimum and maximum is one less than the size of the type.
TABLE 1.3


Ranges of the Integral Primitive Types
Type

Size

Minimum

Maximum

byte

8 bits

−27

27 − 1

short

16 bits

−215

215 − 1

int

32 bits


−231

231 − 1

long

64 bits

−263

263 − 1

The char type is integral but unsigned. The range of a variable of type
char is from 0 through 216 − 1. Java characters are in Unicode, which is a
16-bit encoding capable of representing a wide range of international characters. If the most significant 9 bits of a char are all 0, then the encoding
is the same as 7-bit ASCII.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


10

Chapter 1

Language Fundamentals

The two floating-point types are:
float

double
These types conform to the IEEE 754 specification. Many mathematical
operations can yield results that have no expression in numbers (infinity, for
example). To describe such non-numerical situations, both doubles and
floats can take on values that are bit patterns that do not represent numbers. Rather, these patterns represent non-numerical values. The patterns are
defined in the Float and Double classes and may be referenced as follows
(NaN stands for Not a Number):
Float.NaN
Float.NEGATIVE_INFINITY
Float.POSITIVE_INFINITY
Double.NaN
Double.NEGATIVE_INFINITY
Double.POSITIVE_INFINITY
The following code fragment shows the use of these constants:
1. double d = -10.0 / 0.0;
2. if (d == Double.NEGATIVE_INFINITY) {
3.
System.out.println(“d just exploded: “ + d);
4. }
In this code fragment, the test on line 2 passes, so line 3 is executed.

All the numerical primitive types (that is, all except boolean and char) are
signed.

Literals

A

literal is a value specified in the program source, as opposed to one
determined at runtime. Literals can represent primitive or string variables,

and may appear on the right side of assignments or in method calls. You

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


Literals

11

cannot assign values into literals, so they cannot appear on the left side of
assignments.

boolean Literals
The only valid literals of boolean type are true and false. For example:
1. boolean isBig = true;
2. boolean isLittle = false;

char Literals
A char literal can be expressed by enclosing the desired character in single
quotes, as shown here:
char c = ‘w’;
Of course, this technique only works if the desired character is available
on the keyboard at hand. Another way to express a character literal is as a
Unicode value specified using four hexadecimal digits, preceded by \u, with
the entire expression in single quotes. For example:
char c1 = ‘\u4567’;
Java supports a few escape sequences for denoting special characters:
‘\n’ for new line

‘\r’ for return
‘\t’ for tab
‘\b’ for backspace
‘\f’ for formfeed
‘\’’ for single quote
‘\”’ for double quote
‘\\’ for backslash

Integral Literals
Integral literals may be expressed in decimal, octal, or hexadecimal. The
default is decimal. To indicate octal, prefix the literal with 0 (zero). To
indicate hexadecimal, prefix the literal with 0x or 0X; the hex digits may

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


12

Chapter 1

Language Fundamentals

be upper- or lowercase. The value 28 may thus be expressed six ways:
28
034
0x1c
0x1C
0X1c

0X1C
By default, an integral literal is a 32-bit value. To indicate a long (64-bit)
literal, append the suffix L to the literal expression. (The suffix can be lowercase, but then it looks so much like a one that your readers are bound to
be confused.)

Floating-Point Literals
A floating-point literal expresses a floating-point number. In order to be
interpreted as a floating-point literal, a numerical expression must contain
one of the following:
A decimal point: 1.414
The letter E or e, indicating scientific notation: 4.23E+21
The suffix F or f, indicating a float literal: 1.828f
The suffix D or d, indicating a double literal: 1234d
A floating-point literal with no F or D suffix defaults to double type.

When you assign the value of a literal to a variable, as in short s = 9;,
the compiler determines the size of the literal according to the target of the
assignment. Therefore, the assignment just shown is OK. This contrasts with
the handling of variable expressions such as short s1 = 9 + s;, which causes
a compiler error because the size of the expression 9 + s is int, not short.

String Literals
A string literal is a sequence of characters enclosed in double quotes. For
example:
String s = “Characters in strings are 16-bit Unicode.”;

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com



Arrays

13

Java provides many advanced facilities for specifying non-literal string
values, including a concatenation operator and some sophisticated constructors for the String class. These facilities are discussed in detail in Chapter 8,
“The java.lang and java.util Packages.”

Arrays

A Java array is an ordered collection of primitives, object references,
or other arrays. Java arrays are homogeneous: Except as allowed by polymorphism, all elements of an array must be of the same type. That is, when
you create an array, you specify the element type, and the resulting array
can contain only elements that are instances of that class or subclasses of
that class.
To create and use an array, you must follow three steps:
1. Declaration
2. Construction
3. Initialization

Declaration tells the compiler the array’s name and what type its elements
will be. For example:
1. int[] ints;
2. double[] dubs;
3. Dimension[] dims;
4. float[][] twoDee;
Lines 1 and 2 declare arrays of primitive types. Line 3 declares an array of
object references (Dimension is a class in the java.awt package). Line 4
declares a two-dimensional array—that is, an array of arrays of floats.

The square brackets can come before or after the array variable name. This
is also true, and perhaps most useful, in method declarations. A method that
takes an array of doubles could be declared as myMethod(double dubs[]) or
as myMethod(double[] dubs); a method that returns an array of doubles
may be declared as either double[] anotherMethod() or as double
anotherMethod()[]. In this last case, the first form is probably more
readable.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com


×