Home > Store

Java Rules

Register your product to gain access to bonus material or receive a coupon.

Java Rules

Book

  • Sorry, this book is no longer in print.
Not for Sale

Description

  • Copyright 2002
  • Edition: 1st
  • Book
  • ISBN-10: 0-201-70916-3
  • ISBN-13: 978-0-201-70916-2

Detailed yet accessible, Java™ Rules is a comprehensive reference for the application programmer who needs to master the intricacies of the Java™ programming language. Thoroughly describing the core of the Java programming language and the Java™ virtual machine (JVM™), Java™ Rules makes it possible for programmers to efficiently master the Java platform.

Based on the second editions of The Java™ Language Specification and The Java™ Virtual Machine Specification, Java™ Rules presents a subset of those specifications in a gentle tutorial style. From platform basics to APIs, this encyclopedic guidebook reveals every facet of the language--including previously undocumented features. Throughout the book, practical tutorials are supported with official language documentation or with insights shared by respected leaders. The book's unique format and conversational style are ideally suited for experienced programmers seeking a short path to language proficiency.

As both a tutorial and detailed reference, this volume of Java™ Rules covers:

  • Lexical structure, escape sequences, and positional notation systems
  • The anatomy of a compilation unit
  • The five kinds of classes and interfaces
  • Containment and inner class hierarchies (versus inheritance hierarchies)
  • The static modifier, this and super
  • Primitive data types and Object
  • Strings and other common data types
  • Arrays and the Collections Framework

With Java™ Rules in hand, both novices and experienced programmers can quickly master the language.



0201709163B10162001

Sample Content

Downloadable Sample Chapter

Click below for Sample Chapter related to this title:
dunnch03.pdf

Table of Contents



Preface.


About This Book.


A Java Tradition.


1. Lexical Structure.

Introduction.

White Space.

Indenting.

Comments.

Commenting Out Large Blocks of Code.

Identifiers.

Java Naming Conventions.

Keywords.

Literals.

Character Literals.

Escape Sequences.

String Literals.

Numeric Literals.

Class Literals.

Separators.

Operators.



2. Compilation Units.

Introduction.

The Terminology of Class Body Declarations.

The Definition of Fields in Java.

Recognizing Constructors in Source Code.

Anatomy of a Compilation Unit.

Special Initialization Methods.

The Significance of Textual Order.

Limit of One “public” Package Member.

Package Declarations.

Package Names.

The Members of a Package.

Using the SDK to Develop Packages.

Import Declarations.

Automatic Imports.

Redundant Imports.

Importing Nested Classes of All Sorts (Top-Level or Inner).

How Import Declarations are Used by a Compiler.

The Efficiency of Type-Import-on-Demand Declarations.

Type Declarations.

Class Type Declarations.

Interface Type Declarations.

The Definition of Top-Level Classes.

Helper Classes are Not Fundamentally Different.

Technical Arguments Against the Use of Helper Classes.

The Five Kinds of Classes and Interfaces.

“Public” Top-Level Classes.

Non-“public” Member Classes.

Local and Anonymous Classes.

Nested Interfaces.

Choosing Which Kind of Class to Use.

From “VectorEnumerator” to an Anonymous Class.

The Rationale for Containment and Inner Class Hierarchies.

Containment and Inner Class Hierarchies.

Containment Hierarchies.

Inner Class Hierarchies.



3. The “static” Modifier, “this,” and “super”.

Introduction.

The “static” Modifier.

“static” Fields.

“static” Methods.

“static” Classes.

The Definition of “static” Context.

The “static” Context in an Inner Class Hierarchy.

The “this” and “super” Keywords.

The Current Object (“this”).

The Direct Superclass (“super”).

Practical Uses of the “this” and “super” Keywords.

Using “super” to Reference Members in Different Packages.

Multiple Current Instances (a.k.a. Levels).

A Note About Deeply Nested Types.

Qualifying the “this” Keyword.

Qualifying the “new” Keyword.

Qualifying the “super” Keyword.



4. Primitive Data Types and Object.

Introduction.

The Definition of Data Types.

Data Type as a Set of Values.

The Object-Oriented Definition of Type.

Numeric Data Types.

Integral Types.

Floating-Point Types.

Understanding the Floating-Point Types.

The “char” Data Type.

The “boolean” Data Type.

The “null” Type.

The “Number” Class.

The “java.math” Package.

The “BigInteger” Class.

The “BigDecimal” Class.

Currency Calculations.

Inexact Results and Comparison Operators.

Rounding the Result of a Floating-Point Operation.

Using Integral Types to Store Monetary Values.

Primitive Type Wrapper Classes.

Parsing Strings for Primitive Type Values.

Converting Primitive Numeric Types to Strings.

Bit Pattern Manipulation.

Accessing Primitive Type System Properties.

Unicode Utility Methods.

The “Object” Class.

Reference Equality Versus the Equivalence Relationship.

Understanding Hash Tables.

The Five Housekeeping Methods.

The Comparison Methods.

What is Default Ordering?

What is Natural Ordering?

Reverse Order (or Descending) Sorts.

Sorting By More Than One Field.

The “Comparable” Interface.

The “Comparator” Interface.



5. Strings and Other Common Data Types.

Introduction.

Would-Be Mutator Methods.

The Length of a “String” or “StringBuffer”.

The Capacity of a “StringBuffer”.

Ensuring the Capacity of a “StringBuffer”.

“String” Indices.

Right-Open Intervals in “String” and “StringBuffer”.

Checked Exceptions in String and “StringBuffer”.

The “String” Class.

Case Mappings.

Comparing Strings.

Accessing Individual Characters or Substrings.

“char[]” to “String” Conversions and Vice Versa.

Translating Locally Encoded Strings.

Miscellaneous Methods in the “String” Class.

Unusual Constructors in the “String” Class.

The “StringBuffer” Class.

The Overloaded insert and append Methods.

Other Methods in the “StringBuffer” Class.

Other String-Related Classes.

The “StringCharacterIterator” Class.

The “StringReader” and “StringWriter” Classes.

Lexical Analysis.

The “BreakIterator” Class.

The “StringTokenizer” Class.

The “StreamTokenizer” Class.

String Concatenation Operations.

A Note about the Overloaded Binary + Operator.

Implicit String Conversions.

The Intern Mechanism.

Shared Character Buffers.

Displaying Diagnostic Messages on the Console.

Standard I/O.

The “print” and “println” Methods.

The Locale” Class.

The Default Locale.

Supported Locales.

The “Date” Class.

Date Comparisons.

The “GregorianCalendar” Class.

Instantiating the “GregorianCalendar” Class.

The Inconsistent Field Rule.

The Maximum DAY_OF_MONTH Rule.

Date and Time Fields in the Calendar Class.

Standard Default Values for Date and Time Fields.

Normalizing Date and Time Fields.

Date and Time Field Manipulation Methods.

The “TimeZone” Class.

Understanding the Difference between i18n and l10n.

The Localization of Common Data Types.

Formatting Numbers.

Formatting Dates and Times.



6. Arrays and The Collections Framework.

Introduction.

Array, Component, and Element Types.

Arrays.

The Canonical Form of the “for” Loop.

Array Classes Are Dynamically Created.

The Members of an Array Type.

Array Type Variable Declarations.

Initializing Array Type Variables.

Array Access Expressions.

A Bridge over Troubled Waters (the “toArray” Methods).

Untyped References versus Parameterized Types.

What Is Run-Time Type?

Time Complexities (or Big-O Notation).

Constant Time Operations.

Amortized Constant Time.

Logarithmic Time.

Linear Time.

Quadratic Time.

The Equivalence Relationship and Elements.

Duplicate Elements.

Using Mutable Objects as Elements in a “Set” or Keys in a “Map”.

The Collections Framework.

Bulk Operations.

The Principle of Maximum Generality.

The “Collection” Interface.

The Map Interface.

Housekeeping Methods for Containers.

General-Purpose Implementations.

Choosing a General-Purpose Implementation.

Performance Tuning the General-Purpose Implementations.

Special-Purpose Implementations.

“WeakHashMap”.

Views.

Synchronized Views.

Unmodifiable Views.

Range Views (Sublists, Subsets, and Submaps).

Collection Views of a Map.

List View of an Array.

Iterators.

List Iterators.

Using Collection Views to Iterate over a Map.

A Poor Man's Collection.

Synchronized Iterators.

Fail-Fast Iterators.

Iterating Backwards Through a “TreeSet” or “TreeMap”.

Al-Khwarizmi Concerning the Hindu Art of Reckoning.

Utility Methods for “Arrays” and Other “Collections”.

Sorting Containers.

Searching.

Cloning versus Copying a Container.

Shuffling.

Filling.

The Minimum and Maximum Elements.

Convenience Implementations.

An “equals” Method for Arrays.

Custom Implementations of the Core Collection Interfaces.

Abstract Implementations.

Optional Operations.

Restricted Containers.

Standard Constructors.

Multimaps and Multidimensional Arrays.

Multimaps.

Multidimensional Arrays.

Legacy Containers.



Index. 0201709163T10162001

Preface

This book has been under continuous development for over five years, since shortly after the JDK 1.0 release in 1995.

Married to the Java Specifications

This book is based on the Java Language Specification (JLS). In fact, I started out to write what I regarded as The Java Language Specification for Application Programmers. Shortly thereafter, however, I realized that material from The Java Virtual Machine Specification (JVMS) would have to be included as well. This work has grown to include everything of interest to mainstream business application programmers in a host of Java specifications, including the second editions of both the JLS and the JVMS.

The Target Audience

The main difference between the specifications and this book is the target audience. The JVMS is, of course, written for someone who wants to implement a JVM. What is not as generally understood is that the JLS is a grammar primarily intended for someone who wants to write a Java compiler, such as the jikes compiler team at IBM. Thus, it includes a lot of material that is of interest only to programmers who make a living in the arcane world of compilers. That is truly unfortunate because the JLS contains a wealth of information of interest to application programmers that rarely makes it into mainstream Java books. The same can be said of the JVMS. This book extracts all of that information, elaborates upon it where necessary, and presents it in a technical writing style appropriate for mainstream business application programmers.

Mainstream business application programmers are the target audience. By that I mean working programmers, most of whom will be found in corporations outside of Silicon Valley. They are experienced professionals who need to learn the language at a professional level in the first pass. This requires a serious and dedicated focus on the part of the reader. Mainstream business application programmers have that focus. They bring to the subject years of experience and a strong motivation to learn.

More generally, this book is for any programmer who wants to truly master the basics of the Java programming language. While formalism and stylistic norms forbid me from including students in the target audience, I firmly believe that these books can be profitably used to teach the Java programming language (if not as the primary text, then as an auxiliary reference work).



0201709163P10162001

Index

Symbols
" (quotation mark) 27
$ (dollar sign) 11
% (percent sign) 446
+ (plus sign) 30
+ operator 369
+= operator 362
, (comma) 42
. (period) 42
; (semicolon) 42
= = (reference equality operator) 260-262
? (question mark) 446
\ (backslash) 27
_ (underscore) 11
' (apostrophe) 27
Numerics
32-bit pointers 181
64-bit pointers 181
64-bit systems 181
A
abnormal program termination 389-390
absolute endpoints 583
absolute pathname 81
abstract implementations 629-632
abstract keyword 15
abstract method modifiers 99
abstract modifiers 95
AbstractCollection class 632-633
AbstractList class 633-635
clear() method in 634
remove-Range(int fromIndex, int to-Index) method in 634
See also classes
AbstractMap class 636-637
AbstractMethodError 69
AbstractSequentialList class 635-636
AbstractSet class 632-633
accessor methods 300
in ResourceBundle class 430
public 237
acute accent 353
add rule 424
add(BigDecimal val) method 225
add(BigInteger val) method 222
add(First Object o) method 541
add(int field, int value) method 415, 416
add(int index Object element) method 519
add(Object o) method 494, 500
description of 511, 592
in LinkedList Iterator 494
in Set interface 499
addAll(Collection c) method 505, 511
addAll(int index, Collection c) method 495, 519
addAll(Map t) method 586
addition operations 370
addLast(Object o) method 541
Albania 403
Albanian language 399, 403
Algeria 400
algorithms 465, 610
Al-Khwarizmi, Mohammed ibn-Musa 610
alphabet 36
AM_PM field 409, 417
default symbol 454
amortized constant time 491, 493-495
anonymous classes 112
as optional class bodies 121
orphaned 137
using 126-128
vs. local classes 121-123
See also classes
API (application programming interface) 483
apostrophe (') 27
append methods 340
<applet> tag 42
application programming interface (API) 483
application programs 94
performance optimizations of 472-473
applyPattern(String pattern) method 436, 442-445, 457
Arabic language 398, 400
Arabic system 34
arbitrary precision 191
Argentina 401
argument expressions 148
ArithmeticException 69
Armenian script 246
array access expressions 481
general form of 481
subexpressions 481
Array class
binary search methods in 614-616
compareTo(Object o) method in 301
creating 474-475
sort algorithms in 314
sort methods in 612
view method in 587
array creation expressions 479-480
general form of 479
array index expressions 482-483
array initializers 478-479
array reference expressions 481
array type 466
descriptors 475
members of 475
array type variables 464
declarations 476-478
initializing 478
array variables 464
ArrayIndexOutOfBoundsException 69, 325, 482, 518
ArrayList class
add methods in 494
constant time operations in 494
element shifting in 538-539, 622
ensureCapacity (int minimumCapacity) method in 365-366, 555-557, 628
get(int index) method in 482, 493, 534
get(Object o) method in 468
vs. LinkedList class 532-537
performance tuning in 555-557
RangeCheck() method in 577
set(int index, Object element) method in 534
trimToSize() method in 555
See also arrays
See also classes
arrays 467-470
array type 466
binary searches of 615-618
char [ ] 334-336
compile-time type checking of 469
component type 466
components 466
    automatic initialization of 480-481
copying 621-622
element type 466-467
equals(Object o) method for 628
fixed length of 468
initializers 478-479
interoperability of 468
list view of 587
local variable 472
modifiable components 468
multidimensional 650-652
one-dimensional 479
resizable 468
sorting 612
speed of 468
two-dimensional 479
unnamed variables in 466
Arrays.asList(Object[ ] a) method 570
ArrayStoreException 69, 469, 485
ASCII character set 22
asList(Object[ ] a) method 587
assignment operations 33
asymmetric difference 506
asymmetric set difference 512
Australia 401
Austria 400
automatic imports 66-67, 88
B
backing containers 564-566
modCount in 600
structural modifications of 606
backslash (\) 27
backspace 24
bag 514
Bahrain 400
balanced binary trees 546
balanceTree(Node node) method 494
base class 255
base point 34
base-of-all-classes. See Object class
basic containers 632
basic iterators 632
basic operations 630-631
beginIndex value 332
Belarus 400
Belgium 402
BigDecimal class 223-224
comparison operators for 229- 230, 300-301
in currency calculations 233-235
in java.math.package 199
printing the values of floating-point types using 199
rounding modes 226-229
scale of 224-226
See also classes
BigDecimal(double val) constructor 224
BigInteger class 222, 223
Big-O notation 490-493
binary data 350
binary names 11
binary operators 43, 369
binary point 34
binary searches 614
of arrays 615-618
of random access lists 615-618
binary strings 241-243
binary system 34
binary trees 490, 546
balanced 546
binarySearch method 615-618
return value for 617
bit patterns 243
of exponents 208
BitPattern utility class 207
bitwise copy 295
Bokmål dialect 393
Bolivia 401
Boolean class 68
boolean data type 19, 220
boolean keyword 15
Boolean literals 220
boolean methods 333
Boolean(String s) constructor 239
booleanValue() accessor method 237
bounds check 482
<BR> tag 25
brackets 476
Brazil 402
break keyword 15
BreakIterator class 347-352
iterating over glyph boundaries 353-354
iterating over sentence boundaries 356
iterating over word boundaries 354-356
line wrapping 356
See also classes
breaks. See text boundaries
buckets 268
buffer sharing 368
BufferedWriter class
newLine() method in 26
OutPutStream in 387
built-in data types 178
Bulgaria 400
Bulgarian language 398, 400
bulk operations 503-507
result type of 505
and set theory 506
Byelorussian language 398, 400
Byte class 68, 374
byte keyword 15
bytecodes 150
byteValue() accessor method 237
byvalue keyword 16
C
C programming language 20
type system in 489
C++ programming language 20
C0 control characters 22-24
cached hash code optimization 275
Calendar class 406
date fields in 416-419
inconsistent information policy in 413-414
methods in

Updates

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020