Online Sample Chapter
Java's Lexical Structure
Table of Contents
Preface to the Second Edition.
Relationship to Predefined Classes and Interfaces.
References. 2. Grammars.
The Lexical Grammar.
The Syntactic Grammar.
Grammar Notation. 3. Lexical Structure.
Input Elements and Tokens.
Escape Sequences for Character and String Literals.
The Null Literal.
Operators. 4. Types, Values, and Variables.
The Kinds of Types and Values.
Primitive Types and Values.
Integral Types and Values.
Floating-Point Types, Formats, and Values.
The boolean Type and boolean Values.
Reference Types and Values
The Class Object.
The Class String.
When Reference Types Are the Same.
Where Types Are Used.
Variables of Primitive Type.
Variables of Reference Type.
Kinds of Variables.
Initial Values of Variables.
Types, Classes, and Interfaces. 5. Conversions and Promotions.
Kinds of Conversion.
Widening Primitive Conversion.
Narrowing Primitive Conversions.
Widening Reference Conversions.
Narrowing Reference Conversions.
Value Set Conversion.
Method Invocation Conversion.
Unary Numeric Promotion.
Binary Numeric Promotion. 6. Names.
Names and Identifiers.
Scope of a Declaration.
Members and Inheritance.
The Members of a Package.
The Members of a Class Type.
The Members of an Interface Type.
The Members of an Array Type.
Determining the Meaning of a Name.
Syntactic Classification of a Name According to Context.
Reclassification of Contextually Ambiguous Names.
Meaning of Package Names.
Simple Package Names.
Qualified Package Names.
Meaning of PackageOrTypeNames.
Meaning of Type Names.
Simple Type Names.
Qualified Type Names.
Meaning of Expression Names.
Simple Expression Names.
Qualified Expression Names.
Meaning of Method Names.
Simple Method Names.
Qualified Method Names.
Details on protected Access.
Access to a protected Member.
Qualified Access to a protected Constructor.
An Example of Access Control.
Example: Access to public and Non-public Classes.
Example: Default-Access Fields, Methods, and Constructors.
Example: public Fields, Methods, and Constructors.
Example: protected Fields, Methods, and Constructors.
Example: private Fields, Methods, and Constructors.
Fully Qualified Names and Canonical Names.
Class and Interface Type Names.
Local Variable and Parameter Names. 7. Packages.
Host Support for Packages.
Storing Packages in a File System.
Storing Packages in a Database.
Observability of a Package.
Scope of a Package Declaration.
A Strange Example.
Top Level Type Declarations.
Unique Package Names. 8. Classes.
Inner Classes and Enclosing Instances.
Superclasses and Subclasses.
Class Body and Member Declarations.
Examples of Inheritance.
Example: Inheritance with Default Access.
Inheritance with public and protected.
Inheritance with private.
Accessing Members of Inaccessible Classes.
Initialization of Fields.
Initializers for Class Variables.
Initializers for Instance Variables.
Restrictions on the use of Fields during Initialization.
Examples of Field Declarations.
Example: Hiding of Class Variables.
Example: Hiding of Instance Variables.
Example: Multiply Inherited Fields.
Example: Re-inheritance of Fields.
Inheritance, Overriding, and Hiding.
Overriding (by Instance Methods).
Hiding (by Class Methods).
Requirements in Overriding and Hiding.
Inheriting Methods with the Same Signature.
Examples of Method Declarations.
Example: Overloading, Overriding, and Hiding.
Example: Incorrect Overriding.
Example: Overriding versus Hiding.
Example: Invocation of Hidden Class Methods.
Large Example of Overriding.
Example: Incorrect Overriding because of Throws.
Member Type Declarations.
Static Member Type Declarations.
Explicit Constructor Invocations.
Preventing Instantiation of a Class. 9. Interfaces.
Superinterfaces and Subinterfaces.
Interface Body and Member Declarations.
Access to Interface Member Names.
Field (Constant) Declarations.
Initialization of Fields in Interfaces.
Examples of Field Declarations.
Ambiguous Inherited Fields.
Multiply Inherited Fields.
Abstract Method Declarations.
Inheritance and Overriding.
Examples of Abstract Method Declarations.
Member Type Declarations. 10. Arrays.
Arrays: A Simple Example.
Class Objects for Arrays.
An Array of Characters is Not a String.
Array Store Exception. 11. Exceptions.
The Causes of Exceptions.
Compile-Time Checking of Exceptions.
Why Errors are Not Checked.
Why Runtime Exceptions are Not Checked.
Handling of an Exception.
Exceptions are Precise.
Handling Asynchronous Exceptions.
An Example of Exceptions.
The Exception Hierarchy.
Loading and Linkage Errors.
Virtual Machine Errors. 12. Execution.
Virtual Machine Start-Up.
Load the Class Test.
Link Test: Verify, Prepare, (Optionally) Resolve.
Initialize Test: Execute Initializers.
Loading of Classes and Interfaces.
The Loading Process.
Linking of Classes and Interfaces.
Verification of the Binary Representation.
Preparation of a Class or Interface Type.
Resolution of Symbolic References.
Initialization of Classes and Interfaces.
When Initialization Occurs.
Detailed Initialization Procedure.
Initialization: Implications for Code Generation.
Creation of New Class Instances.
Finalization of Class Instances.
Finalizer Invocations are Not Ordered.
Unloading of Classes and Interfaces.
Program Exit. 13. Binary Compatibility.
The Form of a Binary.
What Binary Compatibility Is and Is Not.
Evolution of Packages.
Evolution of Classes.
Superclasses and Superinterfaces.
Class Body and Member Declarations.
Access to Members and Constructors.
Final Fields and Constants.
Method and Constructor Declarations.
Method and Constructor Parameters.
Method Result Type.
Method and Constructor Throws.
Method and Constructor Body.
Method and Constructor Overloading.
Evolution of Interfaces.
The Interface Members.
Abstract Method Declarations. 14. Blocks and Statements.
Normal and Abrupt Completion of Statements.
Local Class Declarations.
Local Variable Declaration Statements.
Local Variable Declarators and Types.
Scope of Local Variable Declarations.
Shadowing of Names by Local Variables.
Execution of Local Variable Declarations.
The Empty Statement.
The if Statement.
The if—then Statement.
The if—then—else Statement.
The switch Statement.
The while Statement.
The do Statement.
Example of do statement.
The for Statement.
Initialization of for statement.
Iteration of for statement.
Abrupt Completion of for statement.
The break Statement.
The continue Statement.
The return Statement.
The throw Statement.
The synchronized Statement.
The try statement.
Execution of try—catch.
Execution of try—catch—finally.
Unreachable Statements. 15. Expressions.
Evaluation, Denotation, and Result.
Variables as Values.
Type of an Expression.
Expressions and Run-Time Checks.
Normal and Abrupt Completion of Evaluation.
Evaluate Left-Hand Operand First.
Evaluate Operands before Operation.
Evaluation Respects Parentheses and Precedence.
Argument Lists are Evaluated Left-to-Right.
Evaluation Order for Other Expressions.
Class Instance Creation Expressions.
Determining the Class being Instantiated.
Determining Enclosing Instances.
Choosing the Constructor and its Arguments.
Run-time Evaluation of Class Instance Creation Expressions.
Anonymous Class Declarations.
Example: Evaluation Order and Out-of-Memory Detection.
Array Creation Expressions.
Run-time Evaluation of Array Creation Expressions.
Example: Array Creation Evaluation Order.
Example: Array Creation and Out-of-Memory Detection.
Field Access Expressions.
Field Access Using a Primary.
Accessing Superclass Members using super.
Method Invocation Expressions.
Compile-Time Step 1: Determine Class or Interface to Search.
Compile-Time Step 2: Determine Method Signature.
Find Methods that are Applicable and Accessible.
Choose the Most Specific Method.
Example: Overloading Ambiguity.
Example: Return Type Not Considered.
Example: Compile-Time Resolution.
Compile-Time Step 3: Is the Chosen Method Appropriate?
Runtime Evaluation of Method Invocation.
Compute Target Reference (If Necessary).
Check Accessibility of Type and Method.
Locate Method to Invoke.
Create Frame, Synchronize, Transfer Control.
Example: Target Reference and Static Methods.
Example: Evaluation Order.
Example: Method Invocation using super.
Array Access Expressions.
Runtime Evaluation of Array Access.
Examples: Array Access Evaluation Order.
Postfix Increment Operator.
Postfix Decrement Operator.
Prefix Increment Operator.
Prefix Decrement Operator.
Unary Plus Operator.
Unary Minus Operator.
Bitwise Complement Operator ~
Logical Complement Operator !
Multiplication Operator *
Division Operator /
Remainder Operator %
String Concatenation Operator +
Optimization of String Concatenation.
Examples of String Concatenation.
Additive Operators (+ and -) for Numeric Types.
Numerical Comparison Operators <, <=, >, and >=.
Type Comparison Operator instanceof.
Numerical Equality Operators == and !=
Boolean Equality Operators == and !=
Reference Equality Operators == and !=
Bitwise and Logical Operators.
Integer Bitwise Operators &, ^, and |
Boolean Logical Operators &, ^, and |
Conditional-And Operator &&
Conditional-Or Operator ||
Conditional Operator ? :
Simple Assignment Operator =
Compound Assignment Operators.
Constant Expression. 16. Definite Assignment.
Definite Assignment and Expressions.
Boolean Constant Expressions.
The Boolean Operator &&
The Boolean Operator ||
The Boolean Operator !
The Boolean Operator ? :
The Conditional Operator ? :
Operators ++ and --
Definite Assignment and Statements.
Local Class Declaration Statements.
Local Variable Declaration Statements.
break, continue, return, and throw Statements.
Definite Assignment and Parameters.
Definite Assignment and Array Initializers.
Definite Assignment and Anonymous Classes.
Definite Assignment and Member Types.
Definite Assignment and Static Initializers.
Definite Assignment, Constructors, and Instance Initializers. 17. Threads and Locks.
Terminology and Framework.
Rules about Variables.
Nonatomic Treatment of double and long.
Rules about Locks.
Rules about the Interaction of Locks and Variables.
Rules for Volatile Variables.
Prescient Store Actions.
Example: Possible Swap.
Example: Out-of-Order Writes.
Locks and Synchronization.
Wait Sets and Notification. 18. Syntax.
The Grammar of the Java Programming Language. Index. Credits. Colophon. 0201310082T04062001
The Java programming language was originally called Oak, and was designed for use in embedded consumer-electronic applications by James Gosling. After several years of experience with the language, and significant contributions by Ed Frank, Patrick Naughton, Jonathan Payne, and Chris Warth it was retargeted to the Internet, renamed, and substantially revised to be the language specified here. The final form of the language was defined by James Gosling, Bill Joy, Guy Steele, Richard Tuck, Frank Yellin, and Arthur van Hoff, with help from Graham Hamil ton, Tim Lindholm, and many other friends and colleagues.
The Java programming language is a general-purpose concurrent class-based object-oriented programming language, specifically designed to have as few implementation dependencies as possible. It allows application developers to write a program once and then be able to run it everywhere on the Internet. This book attempts a complete specification of the syntax and semantics of the language. We intend that the behavior of every language construct is specified here, so that all implementations will accept the same programs. Except for timing dependencies or other non-determinisms and given sufficient time and sufficient memory space, a program written in the Java programming language should com pute the same result on all machines and in all implementations.
We believe that the Java programming language is a mature language, ready for widespread use. Nevertheless, we expect some evolution of the language in the years to come. We intend to manage this evolution in a way that is completely compatible with existing applications. To do this, we intend to make relatively few new versions of the language, and to distinguish each new version with a different filename extension. Compilers and systems will be able to support the several ver sions simultannously, with complete compatibility.
Much research and experimentation with the Java platform is already under way. We encourage this work, and will continue to cooperate with external groups to explore improvements to the language and platform. For example, we have already received several interesting proposals for parameterized types. In techni cally difficult areas, near the state of the art, this kind of research collaboration is essential.
We acknowledge and thank the many people who have contributed to this book through their excellent feedback, assistance and encouragement: Particularly thorough, careful, and thoughtful reviews of drafts were provided by Tom Cargill, Peter Deutsch, Paul Hilfinger, Masayuki Ida, David Moon, Steven Muchnick, Charles L. Perkins, Chris Van Wyk, Steve Vinoski, Philip Wadler, Daniel Weinreb, and Kenneth Zadeck. We are very grateful for their extraordinary volunteer efforts.
We are also grateful for reviews, questions, comments, and suggestions from Stephen Adams, Bowen Alpern, Glenn Ammons, Leonid Arbuzov, Kim Bruce, Edwin Chan, David Chase, Pavel Curtis, Drew Dean, William Dietz, David Dill, Patrick Dussud, Ed Felten, John Giannandrea, John Gilmore, Charles Gust, Warren Harris, Lee Hasiuk, Mike Hendrickson, Mark Hill, Urs Hoelzle, Roger Hoover, Susan Flynn Hummel, Christopher Jang, Mick Jordan, Mukesh Kacker, Peter Kessler, James Larus, Derek Lieber, Bill McKeeman, Steve Naroff, Evi Nemeth, Robert O'Callahan, Dave Papay, Craig Partridge, Scott Pfeffer, Eric Raymond, Jim Roskind, Jim Russell, William Scherlis, Edith Schonberg, Anthony Scian, Matthew Self, Janice Shepherd, Kathy Stark, Barbara Steele, Rob Strom, William Waite, Greg Weeks, and Bob Wilson. (This list was generated semi-automatically from our E-mail records. We apologize if we have omitted anyone.)
The feedback from all these reviewers was invaluable to us in improving the definition of the language as well as the form of the presentation in this book. We thank them for their diligence. Any remaining errors in this book---we hope they are few---are our responsibility and not theirs.
We thank Francesca Freedman and Doug Kramer for assistance with matters of typography and layout. We thank Dan Mills of Adobe Systems Incorporated for assistance in exploring possible choices of typefaces.
Many of our colleagues at Sun Microsystems have helped us in one way or another. Lisa Friendly, our series editor, managed our relationship with Addison Wesley. Susan Stambaugh managed the distribution of many hundreds of copies of drafts to reviewers. We received valuable assistance and technical advice from Ben Adida, Ole Agesen, Ken Arnold, Rick Cattell, Asmus Freytag, Norm Hardy, Steve Heller, David Hough, Doug Kramer, Nancy Lee, Marianne Mueller, Akira Tanaka, Greg Tarsy, David Ungar, Jim Waldo, Ann Wollrath, Geoff Wyant, and Derek White. We thank Alan Baratz, David Bowen, Mike Clary, John Doerr, Jon Kannegaard, Eric Schmidt, Bob Sproull, Bert Sutherland, and Scott McNealy for leadership and encouragement.
The on-line Bartleby Library of Columbia University, at URL: http://www.cc.columbia.edu/acis/bartleby/ was invaluable to us during the process of researching and verifying many of the quotations that are scattered throughout this book. Here is one example:
They lard their lean books with the fat of others' works.
---Robert Burton (1576--1640)
We are grateful to those who have toiled on Project Bartleby, for saving us a great deal of effort and reawakening our appreciation for the works of Walt Whitman.
We are thankful for the tools and services we had at our disposal in writing this book: telephones, overnight delivery, desktop workstations, laser printers, photocopiers, text formatting and page layout software, fonts, electronic mail, the World Wide Web, and, of course, the Internet. We live in three different states, scattered across a continent, but collaboration with each other and with our reviewers has seemed almost effortless. Kudos to the thousands of people who have worked over the years to make these excellent tools and services work quickly and reliably.
Mike Hendrickson, Katie Duffy, Simone Payment, and Rosa Aim"e GonzSumlez of Addison-Wesley were very helpful, encouraging, and patient during the long process of bringing this book to print. We also thank the copy editors. Rosemary Simpson worked hard, on a very tight schedule, to create the index. We got into the act at the last minute, however; blame us and not her for any jokes you may find hidden therein. Finally, we are grateful to our families and friends for their love and support during this last, crazy, year. In their book The C Programming Language, Brian Kernighan and Dennis Ritchie said that they felt that the C language "wears well as one's experience with it grows." If you like C, we think you will like the Java programming language.
We hope that it, too, wears well for you.
James Gosling--Cupertino, California
Bill Joy--Aspen, Colorado
Guy Steele--Chelmsford, Massachusetts