Third Edition - Oracle

Transcription

The Java Language SpecificationThird Edition

The Java SeriesThe Java Programming LanguageKen Arnold, James Gosling and David HolmesISBN 0-201-70433-1The Java Language Specification Third EditionJames Gosling, Bill Joy, Guy Steele and Gilad BrachaISBN 0-321-24678-0The Java Virtual Machine Specification Second EditionTim Lindholm and Frank YellinISBN 0-201-43294-3The Java Application Programming Interface,Volume 1: Core PackagesJames Gosling, Frank Yellin, and the Java TeamISBN 0-201-63452-XThe Java Application Programming Interface,Volume 2: Window Toolkit and AppletsJames Gosling, Frank Yellin, and the Java TeamISBN 0-201-63459-7The Java Tutorial: Object-Oriented Programming for the InternetMary Campione and Kathy WalrathISBN 0-201-63454-6The Java Class Libraries: An Annotated ReferencePatrick Chan and Rosanna LeeISBN 0-201-63458-9The Java FAQ: Frequently Asked QuestionsJonni KanervaISBN 0-201-63456-2

The Java Language SpecificationThird EditionJames GoslingBill JoyGuy SteeleGilad BrachaADDISON-WESLEYBoston San Francisco New York Toronto MontrealLondon Munich Paris MadridCapetown Sydney Tokyo Singapore Mexico City

The Java Language Specificationiv

Copyright 1996-2005 Sun Microsystems, Inc.4150 Network Circle, Santa Clara, California 95054 U.S.A.All rights reserved.Duke logo designed by Joe Palrang.RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the United StatesGovernment is subject to the restrictions set forth in DFARS 252.227-7013 (c)(1)(ii) andFAR 52.227-19.The release described in this manual may be protected by one or more U.S. patents,foreign patents, or pending applications.Sun Microsystems, Inc. (SUN) hereby grants to you a fully paid, nonexclusive, nontransferable, perpetual, worldwide limited license (without the right to sublicense) underSUN’s intellectual property rights that are essential to practice this specification. Thislicense allows and is limited to the creation and distribution of clean room implementations of this specification that: (i) include a complete implementation of the current version of this specification without subsetting or supersetting; (ii) implement all theinterfaces and functionality of the required packages of the Java 2 Platform, StandardEdition, as defined by SUN, without subsetting or supersetting; (iii) do not add any additional packages, classes, or interfaces to the java.* or javax.* packages or their subpackages; (iv) pass all test suites relating to the most recent published version of thespecification of the Java 2 Platform, Standard Edition, that are available from SUN six(6) months prior to any beta release of the clean room implementation or upgrade thereto;(v) do not derive from SUN source code or binary materials; and (vi) do not include anySUN source code or binary materials without an appropriate and separate license fromSUN.Sun, Sun Microsystems, the Sun logo, Solaris, Java, JavaScript, JDK, and all Java-basedtrademarks or logos are trademarks or registered trademarks of Sun Microsystems, Inc.UNIX is a registered trademark of The Open Group in the United States and other countries. Apple and Dylan are trademarks of Apple Computer, Inc. All other product namesmentioned herein are the trademarks of their respective owners.THIS PUBLICATION IS PROVIDED “AS IS” WITHOUT WARRANTY OF ANYKIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULARPURPOSE, OR NON-INFRINGEMENT.THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESE CHANGES WILL BE INCORPORATED IN NEWEDITIONS OF THE PUBLICATION. SUN MICROSYSTEMS, INC. MAY MAKEIMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THIS PUBLICATION AT ANY TIME.Credits and permissions for quoted material appear in a separate section on page 649.

/Text printed on recycled and acid-free paperISBN 0-321-24678-01 2 3 4 5 6 7 8 9-MA-99989796First printing, May 2005vi

“When I use a word,” Humpty Dumpty said,in rather a scornful tone, “it means just what Ichoose it to mean—neither more nor less.”“The question is,” said Alice, “whether youcan make words mean so many different things.”“The question is,” said Humpty Dumpty,“which is to be master—that’s all.”—Lewis Carroll, Through the Looking Glass

ixPreface X X I I IPreface to the Second Edition X X V I IPreface to the Third Edition X X X I1 Introduction 11.11.21.31.4Example Programs 5Notation 6Relationship to Predefined Classes and Interfaces 6References 62 Grammars 92.12.22.32.4Context-Free Grammars 9The Lexical Grammar 9The Syntactic Grammar 10Grammar Notation 103 Lexical Structure 133.13.23.33.43.53.63.73.83.93.103.113.12Unicode 13Lexical Translations 14Unicode Escapes 15Line Terminators 16Input Elements and Tokens 17White Space 18Comments 18Identifiers 19Keywords 21Literals 213.10.1 Integer Literals 223.10.2 Floating-Point Literals 243.10.3 Boolean Literals 263.10.4 Character Literals 263.10.5 String Literals 283.10.6 Escape Sequences for Character and String Literals 303.10.7 The Null Literal 30Separators 31Operators 314 Types, Values, and Variables 334.14.2The Kinds of Types and Values 34Primitive Types and Values 344.2.1Integral Types and Values 354.2.2Integer Operations 36

The Java Language .3Floating-Point Types, Formats, and Values 374.2.4Floating-Point Operations 404.2.5The boolean Type and boolean Values 43Reference Types and Values 444.3.1Objects 454.3.2The Class Object 474.3.3The Class String 484.3.4When Reference Types Are the Same 49Type Variables 49Parameterized Types 514.5.1Type Arguments and Wildcards 524.5.1.1Type Argument Containment and Equivalence 554.5.2Members and Constructors of Parameterized Types 55Type Erasure 56Reifiable Types 56Raw Types 57Intersection Types 62Subtyping 634.10.1 Subtyping among Primitive Types 634.10.2 Subtyping among Class and Interface Types 634.10.3 Subtyping among Array Types 64Where Types Are Used 65Variables 674.12.1 Variables of Primitive Type 674.12.2 Variables of Reference Type 674.12.2.1 Heap Pollution 684.12.3 Kinds of Variables 694.12.4 final Variables 714.12.5 Initial Values of Variables 714.12.6 Types, Classes, and Interfaces 735 Conversions and Promotions 775.15.25.3Kinds of Conversion 805.1.1Identity Conversions 805.1.2Widening Primitive Conversion 805.1.3Narrowing Primitive Conversions 825.1.4Widening and Narrowing Primitive Conversions 845.1.5Widening Reference Conversions 855.1.6Narrowing Reference Conversions 855.1.7Boxing Conversion 865.1.8Unboxing Conversion 885.1.9Unchecked Conversion 895.1.10 Capture Conversion 895.1.11 String Conversions 925.1.12 Forbidden Conversions 925.1.13 Value Set Conversion 92Assignment Conversion 93Method Invocation Conversion 99

xi5.45.55.6String Conversion 101Casting Conversion 101Numeric Promotions 1085.6.1Unary Numeric Promotion 1085.6.2Binary Numeric Promotion 1106 Names 1136.16.26.36.46.56.6Declarations 114Names and Identifiers 115Scope of a Declaration 1176.3.1Shadowing Declarations 1196.3.2Obscured Declarations 122Members and Inheritance 1226.4.1The Members of Type Variables, Parameterized Types, Raw Types andIntersection Types 1226.4.2The Members of a Package 1226.4.3The Members of a Class Type 1236.4.4The Members of an Interface Type 1246.4.5The Members of an Array Type 125Determining the Meaning of a Name 1266.5.1Syntactic Classification of a Name According to Context 1276.5.2Reclassification of Contextually Ambiguous Names 1296.5.3Meaning of Package Names 1316.5.3.1Simple Package Names 1316.5.3.2Qualified Package Names 1326.5.4Meaning of PackageOrTypeNames 1326.5.4.1Simple PackageOrTypeNames 1326.5.4.2Qualified PackageOrTypeNames 1326.5.5Meaning of Type Names 1326.5.5.1Simple Type Names 1326.5.5.2Qualified Type Names 1326.5.6Meaning of Expression Names 1346.5.6.1Simple Expression Names 1346.5.6.2Qualified Expression Names 1356.5.7Meaning of Method Names 1376.5.7.1Simple Method Names 1376.5.7.2Qualified Method Names 137Access Control 1386.6.1Determining Accessibility 1386.6.2Details on protected Access 1396.6.2.1Access to a protected Member 1396.6.2.2Qualified Access to a protected Constructor 1406.6.3An Example of Access Control 1406.6.4Example: Access to public and Non-public Classes 1416.6.5Example: Default-Access Fields, Methods, and Constructors 1426.6.6Example: public Fields, Methods, and Constructors 1436.6.7Example: protected Fields, Methods, and Constructors 1436.6.8Example: private Fields, Methods, and Constructors 144

The Java Language Specificationxii6.76.8Fully Qualified Names and Canonical Names 145Naming Conventions 1466.8.1Package Names 1476.8.2Class and Interface Type Names 1476.8.3Type Variable Names 1486.8.4Method Names 1496.8.5Field Names 1506.8.6Constant Names 1506.8.7Local Variable and Parameter Names 1517 Packages 1537.17.27.37.47.57.67.7Package Members 154Host Support for Packages 1557.2.1Storing Packages in a File System 1557.2.2Storing Packages in a Database 157Compilation Units 157Package Declarations 1587.4.1Named Packages 1587.4.1.1Package Annotations 1587.4.2Unnamed Packages 1597.4.3Observability of a Package 1607.4.4Scope of a Package Declaration 160Import Declarations 1607.5.1Single-Type-Import Declaration 1617.5.2Type-Import-on-Demand Declaration 1637.5.3Single Static Import Declaration 1647.5.4Static-Import-on-Demand Declaration 1657.5.5Automatic Imports 1657.5.6A Strange Example 165Top Level Type Declarations 166Unique Package Names 1698 Classes 1738.18.2Class Declaration 1758.1.1Class Modifiers 1758.1.1.1abstract Classes 1768.1.1.2final Classes 1788.1.1.3strictfp Classes 1788.1.2Generic Classes and Type Parameters 1788.1.3Inner Classes and Enclosing Instances 1818.1.4Superclasses and Subclasses 1848.1.5Superinterfaces 1868.1.6Class Body and Member Declarations 189Class Members 1908.2.1Examples of Inheritance 1928.2.1.1Example: Inheritance with Default Access 1928.2.1.2Inheritance with public and protected 193

xiii8.38.48.58.2.1.3Inheritance with private 1938.2.1.4Accessing Members of Inaccessible Classes 194Field Declarations 1968.3.1Field Modifiers 1978.3.1.1static Fields 1988.3.1.2final Fields 199transient Fields 1998.3.1.38.3.1.4volatile Fields 1998.3.2Initialization of Fields 2018.3.2.1Initializers for Class Variables 2028.3.2.2Initializers for Instance Variables 2028.3.2.3Restrictions on the use of Fields during Initialization 2038.3.3Examples of Field Declarations 2058.3.3.1Example: Hiding of Class Variables 2058.3.3.2Example: Hiding of Instance Variables 2068.3.3.3Example: Multiply Inherited Fields 2078.3.3.4Example: Re-inheritance of Fields 209Method Declarations 2098.4.1Formal Parameters 2108.4.2Method Signature 2128.4.3Method Modifiers 2148.4.3.1abstract Methods 2148.4.3.2static Methods 2168.4.3.3final Methods 2178.4.3.4native Methods 2188.4.3.5strictfp Methods 2188.4.3.6synchronized Methods 2188.4.4Generic Methods 2208.4.5Method Return Type 2208.4.6Method Throws 2218.4.7Method Body 2238.4.8Inheritance, Overriding, and Hiding 2248.4.8.1Overriding (by Instance Methods) 2248.4.8.2Hiding (by Class Methods) 2258.4.8.3Requirements in Overriding and Hiding 2258.4.8.4Inheriting Methods with Override-Equivalent Signatures 2288.4.9Overloading 2298.4.10 Examples of Method Declarations 2308.4.10.1 Example: Overriding 2308.4.10.2 Example: Overloading, Overriding, and Hiding 2318.4.10.3 Example: Incorrect Overriding 2318.4.10.4 Example: Overriding versus Hiding 2328.4.10.5 Example: Invocation of Hidden Class Methods 2348.4.10.6 Large Example of Overriding 2348.4.10.7 Example: Incorrect Overriding because of Throws 236Member Type Declarations 2378.5.1Modifiers 2388.5.2Static Member Type Declarations 238

The Java Language Specificationxiv8.68.78.88.9Instance Initializers 238Static Initializers 239Constructor Declarations 2408.8.1Formal Parameters and Formal Type Parameter 2408.8.2Constructor Signature 2418.8.3Constructor Modifiers 2418.8.4Generic Constructors 2428.8.5Constructor Throws 2428.8.6The Type of a Constructor 2428.8.7Constructor Body 2428.8.7.1Explicit Constructor Invocations 2438.8.8Constructor Overloading 2468.8.9Default Constructor 2478.8.10 Preventing Instantiation of a Class 248Enums 2499 Interfaces 2599.19.29.39.49.59.69.7Interface Declarations 2609.1.1Interface Modifiers 2609.1.1.1abstract Interfaces 2619.1.1.2strictfp Interfaces 2619.1.2Generic Interfaces and Type Parameters 2619.1.3Superinterfaces and Subinterfaces 2619.1.4Interface Body and Member Declarations 2639.1.5Access to Interface Member Names 263Interface Members 263Field (Constant) Declarations 2649.3.1Initialization of Fields in Interfaces 2659.3.2Examples of Field Declarations 2659.3.2.1Ambiguous Inherited Fields 2659.3.2.2Multiply Inherited Fields 266Abstract Method Declarations 2669.4.1Inheritance and Overriding 2679.4.2Overloading 2689.4.3Examples of Abstract Method Declarations 2699.4.3.1Example: Overriding 2699.4.3.2Example: Overloading 269Member Type Declarations 270Annotation Types 2709.6.1Predefined Annotation Types 2779.6.1.1Target 2789.6.1.2Retention 2789.6.1.3Inherited 2799.6.1.4Override 2799.6.1.5SuppressWarnings 2809.6.1.6Deprecated 280Annotations 281

xv10 Arrays 28710.110.210.310.410.510.610.710.810.910.10Array Types 288Array Variables 288Array Creation 289Array Access 289Arrays: A Simple Example 290Array Initializers 290Array Members 292Class Objects for Arrays 293An Array of Characters is Not a String 294Array Store Exception 29411 Exceptions 29711.111.211.311.411.5The Causes of Exceptions 298Compile-Time Checking of Exceptions 29911.2.1 Exception Analysis of Expressions 29911.2.2 Exception Analysis of Statements 30011.2.3 Exception Checking 30111.2.4 Why Errors are Not Checked 30111.2.5 Why Runtime Exceptions are Not Checked 301Handling of an Exception 30211.3.1 Exceptions are Precise 30311.3.2 Handling Asynchronous Exceptions 303An Example of Exceptions 304The Exception Hierarchy 30611.5.1 Loading and Linkage Errors 30711.5.2 Virtual Machine Errors 30712 Execution 30912.112.212.312.412.512.6Virtual Machine Start-Up 30912.1.1 Load the Class Test 31012.1.2 Link Test: Verify, Prepare, (Optionally) Resolve 31012.1.3 Initialize Test: Execute Initializers 31112.1.4 Invoke Test.main 312Loading of Classes and Interfaces 31212.2.1 The Loading Process 313Linking of Classes and Interfaces 31412.3.1 Verification of the Binary Representation 31412.3.2 Preparation of a Class or Interface Type 31512.3.3 Resolution of Symbolic References 315Initialization of Classes and Interfaces 31612.4.1 When Initialization Occurs 31612.4.2 Detailed Initialization Procedure 31912.4.3 Initialization: Implications for Code Generation 321Creation of New Class Instances 322Finalization of Class Instances 325

The Java Language Specificationxvi12.6.112.712.8Implementing Finalization 32612.6.1.1 Interaction with the Memory Model 32812.6.2 Finalizer Invocations are Not Ordered 329Unloading of Classes and Interfaces 330Program Exit 33113 Binary Compatibility 33313.113.213.313.413.5The Form of a Binary 334What Binary Compatibility Is and Is Not 339Evolution of Packages 340Evolution of Classes 34013.4.1 abstract Classes 34013.4.2 final Classes 34113.4.3 public Classes 34113.4.4 Superclasses and Superinterfaces 34113.4.5 Class Formal Type Parameters 34213.4.6 Class Body and Member Declarations 34313.4.7 Access to Members and Constructors 34413.4.8 Field Declarations 34513.4.9 final Fields and Constants 34713.4.10 static Fields 34913.4.11 transient Fields 35013.4.12 Method and Constructor Declarations 35013.4.13 Method and Constructor Formal Type Parameters 35113.4.14 Method and Constructor Parameters 35213.4.15 Method Result Type 35213.4.16 abstract Methods 35213.4.17 final Methods 35313.4.18 native Methods 35413.4.19 static Methods 35413.4.20 synchronized Methods 35413.4.21 Method and Constructor Throws 35413.4.22 Method and Constructor Body 35413.4.23 Method and Constructor Overloading 35513.4.24 Method Overriding 35613.4.25 Static Initializers 35613.4.26 Evolution of Enums 356Evolution of Interfaces 35613.5.1 public Interfaces 35613.5.2 Superinterfaces 35713.5.3 The Interface Members 35713.5.4 Interface Formal Type Parameters 35713.5.5 Field Declarations 35813.5.6 Abstract Method Declarations 35813.5.7 Evolution of Annotation Types 358

xvii14 Blocks and Statements ormal and Abrupt Completion of Statements 360Blocks 361Local Class Declarations 361Local Variable Declaration Statements 36314.4.1 Local Variable Declarators and Types 36414.4.2 Scope of Local Variable Declarations 36414.4.3 Shadowing of Names by Local Variables 36714.4.4 Execution of Local Variable Declarations 367Statements 368The Empty Statement 370Labeled Statements 370Expression Statements 371The if Statement 37214.9.1 The if–then Statement 37214.9.2 The if–then–else Statement 372The assert Statement 373The switch Statement 377The while Statement 38014.12.1 Abrupt Completion 381The do Statement 38214.13.1 Abrupt Completion 38314.13.2 Example of do statement 383The for Statement 38414.14.1 The basic for Statement 38414.14.1.1 Initialization of for statement 38514.14.1.2 Iteration of for statement 38514.14.1.3 Abrupt Completion of for statement 38614.14.2 The enhanced for statement 387The break Statement 388The continue Statement 390The return Statement 392The throw Statement 393The synchronized Statement 395The try statement 39614.20.1 Execution of try–catch 39814.20.2 Execution of try–catch–finally 399Unreachable Statements 40215 Expressions 40915.115.215.315.415.515.615.7Evaluation, Denotation, and Result 409Variables as Values 410Type of an Expression 410FP-strict Expressions 411Expressions and Run-Time Checks 411Normal and Abrupt Completion of Evaluation 413Evaluation Order 414

The Java Language Specificationxviii15.7.1 Evaluate Left-Hand Operand First 41515.7.2 Evaluate Operands before Operation 41615.7.3 Evaluation Respects Parentheses and Precedence 41715.7.4 Argument Lists are Evaluated Left-to-Right 41815.7.5 Evaluation Order for Other Expressions 41915.8 Primary Expressions 42015.8.1 Lexical Literals 42015.8.2 Class Literals 42115.8.3 this 42115.8.4 Qualified this 42215.8.5 Parenthesized Expressions 42215.9 Class Instance Creation Expressions 42315.9.1 Determining the Class being Instantiated 42415.9.2 Determining Enclosing Instances 42515.9.3 Choosing the Constructor and its Arguments 42715.9.4 Run-time Evaluation of Class Instance Creation Expressions 42815.9.5 Anonymous Class Declarations 42915.9.5.1 Anonymous Constructors 42915.9.6 Example: Evaluation Order and Out-of-Memory Detection 43015.10 Array Creation Expressions 43115.10.1 Run-time Evaluation of Array Creation Expressions 43215.10.2 Example: Array Creation Evaluation Order 43315.10.3 Example: Array Creation and Out-of-Memory Detection 43415.11 Field Access Expressions 43515.11.1 Field Access Using a Primary 43515.11.2 Accessing Superclass Members using super 43815.12 Method Invocation Expressions 44015.12.1 Compile-Time Step 1: Determine Class or Interface to Search 44015.12.2 Compile-Time Step 2: Determine Method Signature 44215.12.2.1 Identify Potentially Applicable Methods 44315.12.2.2 Phase 1: Identify Matching Arity Methods Applicable by Subtyping 44515.12.2.3 Phase 2: Identify Matching Arity Methods Applicable byMethod Invocation Conversion 44615.12.2.4 Phase 3: Identify Applicable Variable Arity Methods 44615.12.2.5 Choosing the Most Specific Method 44715.12.2.6 Method Result and Throws Types 45015.12.2.7 Inferring Type Arguments Based on Actual Arguments 45115.12.2.8 Inferring Unresolved Type Arguments 46615.12.2.9 Examples 46615.12.2.10 Example: Overloading Ambiguity 46815.12.2.11 Example: Return Type Not Considered 46815.12.2.12 Example: Compile-Time Resolution 46915.12.3 Compile-Time Step 3: Is the Chosen Method Appropriate? 47115.12.4 Runtime Evaluation of Method Invocation 47315.12.4.1 Compute Target Reference (If Necessary) 47315.12.4.2 Evaluate Arguments 47415.12.4.3 Check Accessibility of Type and Method 475

.2215.2315.2415.2515.2615.12.4.4 Locate Method to Invoke 47615.12.4.5 Create Frame, Synchronize, Transfer Control 47715.12.4.6 Example: Target Reference and Static Methods 47915.12.4.7 Example: Evaluation Order 47915.12.4.8 Example: Overriding 48015.12.4.9 Example: Method Invocation using super 481Array Access Expressions 48215.13.1 Runtime Evaluation of Array Access 48315.13.2 Examples: Array Access Evaluation Order 483Postfix Expressions 48515.14.1 Expression Names 48515.14.2 Postfix Increment Operator 48515.14.3 Postfix Decrement Operator -- 486Unary Operators 48715.15.1 Prefix Increment Operator 48715.15.2 Prefix Decrement Operator -- 48815.15.3 Unary Plus Operator 48915.15.4 Unary Minus Operator - 48915.15.5 Bitwise Complement Operator 49015.15.6 Logical Complement Operator ! 490Cast Expressions 490Multiplicative Operators 49115.17.1 Multiplication Operator * 49215.17.2 Division Operator / 49315.17.3 Remainder Operator % 495Additive Operators 49615.18.1 String Concatenation Operator 49715.18.1.1 String Conversion 49715.18.1.2 Optimization of String Concatenation 49815.18.1.3 Examples of String Concatenation 49815.18.2 Additive Operators ( and -) for Numeric Types 500Shift Operators 502Relational Operators 50315.20.1 Numerical Comparison Operators , , , and 50315.20.2 Type Comparison Operator instanceof 504Equality Operators 50515.21.1 Numerical Equality Operators and ! 50615.21.2 Boolean Equality Operators and ! 50715.21.3 Reference Equality Operators and ! 507Bitwise and Logical Operators 50815.22.1 Integer Bitwise Operators &, , and 50815.22.2 Boolean Logical Operators &, , and 508Conditional-And Operator && 509Conditional-Or Operator 509Conditional Operator ? : 510Assignment Operators 51215.26.1 Simple Assignment Operator 51315.26.2 Compound Assignment Operators 518

The Java Language Specificationxx15.27 Expression 52515.28 Constant Expression 52516 Definite Assignment 52716.116.216.316.416.516.616.716.816.9Definite Assignment and Expressions 53316.1.1 Boolean Constant Expressions 53316.1.2 The Boolean Operator && 53316.1.3 The Boolean Operator 53416.1.4 The Boolean Operator ! 53416.1.5 The Boolean Operator ? : 53416.1.6 The Conditional Operator ? : 53516.1.7 Other Expressions of Type boolean 53516.1.8 Assignment Expressions 53516.1.9 Operators and -- 53616.1.10 Other Expressions 536Definite Assignment and Statements 53816.2.1 Empty Statements 53816.2.2 Blocks 53816.2.3 Local Class Declaration Statements 53916.2.4 Local Variable Declaration Statements 53916.2.5 Labeled Statements 54016.2.6 Expression Statements 54016.2.7 if Statements 54116.2.8 assert Statements 54116.2.9 switch Statements 54116.2.10 while Statements 54216.2.11 do Statements 54316.2.12 for Statements 54316.2.12.1 Initialization Part 54416.2.12.2 Incrementation Part 54416.2.13 break, continue, return, and throw Statements 54516.2.14 synchronized Statements 54516.2.15 try Statements 545Definite Assignment and Parameters 547Definite Assignment and Array Initializers 547Definite Assignment and Enum Constants 548Definite Assignment and Anonymous Classes 548Definite Assignment and Member Types 549Definite Assignment and Static Initializers 549Definite Assignment, Constructors, and Instance Initializers 55017 Threads and Locks 55317.117.217.317.4Locks 554Notation in Examples 554Incorrectly Synchronized Programs Exhibit Surprising Behaviors 555Memory Model 55717.4.1 Shared Variables 558

xxi17.517.617.717.817.917.4.2 Actions 55817.4.3 Programs and Program Order 56017.4.4 Synchronization Order 56117.4.5 Happens-before Order 56117.4.6 Executions 56717.4.7 Well-Formed Executions 56817.4.8 Executions and Causality Requirements 56817.4.9 Observable Behavior and Nonterminating Executions 571Final Field Semantics 57317.5.1 Semantics of Final Fields 57517.5.2 Reading Final Fields During Construction 57617.5.3 Subsequent Modification of Final Fields 57617.5.4 Write Protected Fields 578Word Tearing 578Non-atomic Treatment of double and long 579Wait Sets and Notification 58017.8.1 Wait 58017.8.2 Notification 58117.8.3 Interruptions 58217.8.4 Interactions of Waits, Notification and Interruption 582Sleep and Yield 58318 Syntax 58518.1The Grammar of the Java Programming Language 585Index 597Credits 649Colophon 651

The Java Language Specificationxxii

PrefaceTHE Java programming language was originally called Oak, and was designedfor use in embedded consumer-electronic applications by James Gosling. Afterseveral years of experience with the language, and significant contributions by EdFrank, Patrick Naughton, Jonathan Payne, and Chris Warth it was retargeted to theInternet, renamed, and substantially revised to be the language specified here. Thefinal 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 Hamilton, Tim Lindholm, and many other friends and colleagues.The Java programming language is a general-purpose concurrent class-basedobject-oriented programming language, specifically designed to have as fewimplementation dependencies as possible. It allows application developers towrite 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 ofthe language. We intend that the behavior of every language construct is specifiedhere, so that all implementations will accept the same programs. Except for timingdependencies or other non-determinisms and given sufficient time and sufficientmemory space, a program written in the Java programming language should compute the same result on all machines and in all implementations.We believe that the Java programming language is a mature language, readyfor widespread use. Nevertheless, we expect some evolution of the language in theyears to come. We intend to manage this evolution in a way that is completelycompatible with existing applications. To do this, we intend to make relatively fewnew versions of the language. Compilers and systems will be able to support theseveral versions simultaneously, with complete compatibility.Much research and experimentation with the Java platform is already underway. We encourage this work, and will continue to cooperate with external groupsto explore improvements to the language and platform. For example, we havealready received several interesting proposals for parameterized types. In technically difficult areas, near the state of the art, this kind of research collaboration isessential.xxiii

PREFACEWe acknowledge and thank the many people who have contributed to thisbook through their excellent feedback, assistance and encouragement:Particularly thorough, careful, and thoughtful reviews of drafts were providedby Tom Cargill, Peter Deutsch, Paul Hilfinger, Masayuki Ida, David Moon, StevenMuchnick, Charles L. Perkins, Chris Van Wyk, Steve Vinoski, Philip Wadler,Daniel Weinreb, and Kenneth Zadeck. We are very grateful for their extraordinaryvolunteer efforts.We are also grateful for reviews, questions, comments, and suggestions fromStephen 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, RogerHoover, 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, RobStrom, William Waite, Greg Weeks, and Bob Wilson. (This list was generatedsemi-automatically from our E-mail records. We apologize if we have omittedanyone.)The feedback from all these reviewers was invaluable to us in improving thedefinition of the language as well as the form of the presentation in this book. Wethank them for their diligence. Any remaining errors in this book—we hope theyare few—are our responsibility and not theirs.We thank Francesca Freedman and Doug Kramer for assistance with mattersof typography and layout. We thank Dan Mills of Adobe Systems Incorporated forassistance in exploring possible choices of typefaces.Many of our colleagues at Sun Microsystems have helped us in one way oranother. Lisa Friendly, our series editor, managed our relationship with AddisonWesley. Susan Stambaugh managed the distribution of many hundreds of copiesof drafts to reviewers. We received valuable assistance and technical advice fromBen Adida, Ole Agesen, Ken Arnold, Rick Cattell, Asmus Freytag, Norm Hardy,Steve Heller, David Hough, Doug Kramer, Nancy Lee, Marianne Mueller, AkiraTanaka, Greg Tarsy, David Ungar, Jim Waldo, Ann Wollrath, Geoff Wyant, andDerek White. We thank Alan Baratz, David Bowen, Mike Clary, John Doerr, JonKannegaard, Eric Schmidt, Bob Sproull, Bert Sutherland, and Scott McNealy forleadership and encouragement.The on-line Bartleby Library of Columbia University, at URL:http://www.cc.columbia.edu/acis/bartleby/xxiv

PREFACEwas invaluable to us during the process of researching and verifying many of thequotations 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 greatdeal of effort and reawakening our appreciation for the works of Walt Whitman.We are thankful for the tools and services we had at our

The Java Series The Java Programming Language Ken Arnold, James Gosling and David Holmes ISBN 0-201-70433-1 The Java Language Specification Third Edition James Gosling, Bill Joy, Guy Steele and Gilad Bracha ISBN 0-321-24678-0 The Java Virtual Machine Specification Second