Appendix B
Java Language Grammar

A language grammar (sometimes called a statement of syntax), like the one contained in this appendix, is intended as an aid to understanding. You shouldn't try to use it in isolation, as it doesn't contain an exact statement of the language. In particular, you could write Java code that conforms to the "letter of the law" as stated in the grammar, but that doesn't follow the rules laid out elsewhere in the book, and you would end up with code that doesn't compile and won't run.

For example, the grammar for statements and expressions is carefully laid out in this appendix. But from Chapter 7, you know that Java doesn't allow arbitrary combinations of data types. A statement or expression that conforms only to this grammar but that doesn't follow the type rules won't compile successfully.

See
"Operators," Chapter 7

As another example, this grammar describes legal forms for the declaration and use of variables. But Java imposes additional rules on variables that aren't covered in a grammar. The compiler goes to some lengths, for example, to make sure that variables are initialized before they are used; if the compiler thinks you are trying to use an uninitialized variable, it will give you an error. Those sorts of rules are not covered in the grammar of the language. The formal specification for the Java language, including the grammar, is available online from JavaSoft. The main documentation page is located at http://java.sun.com/doc.html. Documentation specific to the JDK is available at http://java.sun.com/JDK-1.0/index.html. The following grammatical elements refer to the corresponding character from the ASCII character set:

ASCII CR
Carriage return
ASCII LF
Line fee
ASCII SP
Space
ASCII HT
Horizontal tab
ASCII FF
Form feed


The following elements are as defined in the Unicode standard:

UnicodeLetter
A letter in the Unicode character set
UnicodeDigit
A digit in the Unicode character set


The subscript opt indicates that the element is optional; the element being defined will be legal (according to the grammar) with or without the optional element present.

Lexical Structure

Unicode Escapes and Character Input

EscapedInputCharacter:

UnicodeEscape
RawInputCharacter

UnicodeEscape:

\ UnicodeMarker HexDigit HexDigit HexDigit HexDigit

UnicodeMarker:

u
UnicodeMarkeru

RawInputCharacter:

any Unicode character

HexDigit: one of

0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F

Input Lines

LineTerminator:

ASCII-CR ASCII-LF ASCII-CR
ASCII-LF

InputCharacter:

EscapedInputCharacter, but not ASCII-CR or ASCII-LF

Tokens

Input:

InputElementsopt

InputElements:

InputElement
InputElements InputElement

InputElement:

Comment WhiteSpace
Token

WhiteSpace:

ASCII-SP ASCII-HT ASCII-FF
LineTerminator

Token:

Keyword Identifier Literal Separator
Operator

Comments

Comment:

/ * NotStar TraditionalComment / * * DocComment
/ / InputCharactersopt LineTerminator

TraditionalComment:

* / InputCharacter TraditionalComment
LineTerminator TraditionalComment

DocComment:

/ InputCharacter TraditionalComment
LineTerminator TraditionalCommentTraditionalComment

InputCharacters:

InputCharacter
InputCharacters InputCharacter

Keywords

Keyword: one of

abstract boolean break byte byvalue case cast catch char class const continue default do double else extends final finally float for future generic goto if implements import inner instanceof int interface long native new null operator outer package private protected public rest return short static super switch synchronized this throw throws transient try var void volatile while

Identifiers

Identifier:

UnicodeLetter Identifier UnicodeLetter
Identifier UnicodeDigit

Literals

Literal:

IntegerLiteral FloatingPointLiteral BooleanLiteral CharacterLiteral
StringLiteral

IntegerLiteral:

DecimalLiteral IntegerTypeSuffixopt HexLiteral IntegerTypeSuffixopt
OctalLiteral IntegerTypeSuffixopt

IntegerTypeSuffix: one of

l L

DecimalLiteral:

NonZeroDigit Digitsopt

Digits:

Digit
Digits Digit

Digit: one of

0 1 2 3 4 5 6 7 8 9

NonZeroDigit: one of

1 2 3 4 5 6 7 8 9

HexLiteral:

0x HexDigit 0X HexDigit HexLiteral HexDigit OctalLiteral: 0
OctalLiteral OctalDigit

OctalDigit: one of

0 1 2 3 4 5 6 7

FloatingPointLiteral:

Digits . Digitsopt ExponentPartopt FloatTypeSuffixopt . Digits ExponentPartopt FloatTypeSuffixopt
Digits ExponentPartopt FloatTypeSuffixopt

ExponentPart:

ExponentIndicator SignedInteger

ExponentIndicator: one of

e E

SignedInteger:

Signopt Digits

Sign: one of

+ -

FloatTypeSuffix: one of

f F d D

BooleanLiteral: one of

true false

CharacterLiteral:

` SingleCharacter '
` Escape '

SingleCharacter:

InputCharacter, but not ` or \

Escape: one of

\b \t \n \f \r \" \' \\
OctalEscape

OctalEscape:

\ OctalDigit \ OctalDigit OctalDigit
\ ZeroToThree OctalDigit OctalDigit

ZeroToThree: one of

0 1 2 3

StringLiteral:

" StringCharacters "

StringCharacters:

StringCharacter
StringCharacters StringCharacter

StringCharacter:

InputCharacter, but not " or \
Escape

Separators

Separator: one of

( ) { } ;
[ ] , .

Operators

Operator: one of

= > < ! ~ == <= >= != && || ++ -- + - * / & | ^ % << >> >>> += -= *= /= &= |= ^= %= <<= >>= >>>=

? =

Types and Variables

Type:

PrimitiveType ClassType InterfaceType
ArrayType

PrimitiveType: one of

boolean char byte short int
long float double

ClassType:

Name

InterfaceType:

Name

ArrayType:

Type []

Program Structure

CompilationUnit:

PackageStatementopt ImportStatementsopt TypeDeclarationsopt

PackageStatement:

package PackageName ;

PackageName:

PackageNameComponent
PackageName . PackageNameComponent

PackageNameComponent:

Identifier

ImportStatement:

PackageImportStatement TypeImportStatement
TypeImportOnDemandStatement

PackageImportStatement:

import PackageName ;

TypeImportStatement:

import PackageName . Identifier ;

TypeImportOnDemandStatement:

import PackageName . * ;

TypeDeclarations:

TypeDeclaration
TypeDeclarations TypeDeclaration

TypeDeclaration:

ClassDeclaration
InterfaceDeclaration

Classes and Interfaces

ClassDeclaration:

ClassModifiersopt class Identifier Superopt Interfacesopt ClassBody

ClassModifiers:

ClassModifier
ClassModifiers ClassModifier

ClassModifier: one of

abstract final public

Super:

extends TypeName

Interfaces:

implements TypeNameList

ClassBody:

{ FieldDeclarationsopt }

Field Declarations

FieldDeclarations:

FieldDeclaration
FieldDeclarations FieldDeclaration

FieldDeclaration:

FieldVariableDeclaration MethodDeclaration ConstructorDeclaration
StaticInitializer

Variable Declarations

FieldVariableDeclaration:

VariableModifiersopt Type VariableDeclarators ;

VariableModifiers:

VariableModifier
VariableModifiers VariableModifier

VariableModifier: one of

public protected private
static final transient volatile

VariableDeclarators:

VariableDeclarator
VariableDeclarators , VariableDeclarator

VariableDeclarator:

DeclaratorName
DeclaratorName = VariableInitializer

DeclaratorName:

Identifier
DeclaratorName []

VariableInitializer:

Expression
{ ArrayInitializersopt ,opt }

ArrayInitializers:

VariableInitializer
ArrayInitializers ,

Method Declarations

MethodDeclaration:

MethodModifiersopt ResultType MethodDeclarator Throwsopt MethodBody

MethodModifiers:

MethodModifier
MethodModifiers MethodModifier

MethodModifier: one of

public private protected static abstract final
native synchronized

ResultType:

Type
void

MethodDeclarator:

DeclaratorName ( ParameterListopt )
MethodDeclarator []

ParameterList:

Parameter
ParameterList , Parameter

Parameter:

TypeDeclaratorName

Throws:

throws TypeNameList

TypeNameList:

TypeName
TypeNameList , TypeName

MethodBody:

Block

;

Constructor Method Declarations

ConstructorDeclaration:

ConstructorModifieropt ConstructorDeclarator Throwsopt ConstructorBody

ConstructorDeclarator:

TypeName ( ParameterListopt )

ConstructorModifier: one of

public protected private

ConstructorBody:

{ ExplicitConstructorCallStatementopt BlockBody }

ExplicitConstructorCallStatement:

this ( ArgumentListopt ) ;
super ( ArgumentListopt ) ;

Static Initialization

StaticInitializer:

static Block

Interface Declarations

InterfaceDeclaration:

InterfaceModifiersopt interface Identifier ExtendsInterfacesopt InterfaceBody

InterfaceModifiers:

InterfaceModifier
InterfaceModifiers InterfaceModifier

InterfaceModifier: one of

public abstract

ExtendsInterfaces:

extends TypeNameList

InterfaceBody:

{ FieldDeclarations }

Arrays

ArrayInitializer:

{ ElementInitializersopt ,opt }

ElementInitializers:

Element
ElementInitializers , Element

Element:

Expression
ArrayInitializer

Blocks and Statements

Block:

{ LocalVarDeclarationsAndStatements }

LocalVarDeclarationsAndStatements:

Block LocalVarDeclarationOrStatement
LocalVarDeclarationsAndStatements LocalVarDeclarationOrStatement

LocalVarDeclarationOrStatement:

LocalVariableDeclarationStatement
Statement

LocalVariableDeclarationStatement:

TypeSpecifier VariableDeclarators ;

Statement:

EmptyStatement LabeledStatement ExpressionStatement ; SelectionStatement IterationStatement JumpStatement
GuardingStatement

EmptyStatement:

;

LabeledStatement:

Identifier : Statement case ConstantExpression : Statement
default : Statement

ExpressionStatement:

Assignment PreIncrement PreDecrement PostIncrement PostDecrement MethodCall
AllocationExpression

SelectionStatement:

if ( Expression ) Statement if ( Expression ) Statement else Statement
switch ( Expression ) Block

IterationStatement:

while ( Expression ) Statement do Statement while ( Expression ) ;
for ( ForInit Expressionopt ; ForIncropt )

ForInit:

ExpressionStatements ;
LocalVariableDeclarationStatement

ForIncr:

ExpressionStatements

ExpressionStatements:

ExpressionStatement
ExpressionStatements , ExpressionStatement

JumpStatement:

break Identifieropt ; continue Identifieropt ; return Expressionopt ;
throw Expression ;

GuardingStatement:

synchronized ( Expression ) Statement try Block Finally try Block Catches
try Block Catches Finally

Catches:

Catch
Catches Catch

Catch:

catch ( Argument ) Block

Finally:

finally Block

Expressions

Primary Expressions

Primary Expressions

PrimaryExpression:

Name
NotJustName

NotJustName:

AllocationExpression
ComplexPrimary

ComplexPrimary:

Literal ( Expression ) ArrayAccess FieldAccess
MethodCall

Name:

QualifiedName this super
null

QualifiedName:

Identifier
QualifiedName . Identifier

Array and Field Access

ArrayAccess:

Name [ Expression ]
ComplexPrimary [ Expression ]

FieldAccess:

PrimaryExpression . Identifier

Method Calls

MethodCall:

MethodAccess ( ArgumentListopt )

MethodAccess:

Name
PrimaryExpression . Identifier

ArgumentList:

Expression
ArgumentList , Expression

Allocation Expressions

AllocationExpression:

new TypeName ( ArgumentListopt )
new TypeName DimExprs Dimsopt

TypeName:

TypeKeyword
QualifiedName

TypeKeyword: one of

boolean char byte short int float
long double

ArgumentList:

Expression
ArgumentList , Expression

DimExprs:

DimExpr
DimExprs DimExpr

DimExpr:

[ Expression ]

Dims:

[ ]
Dims [ ]

Unary Operators

PostfixExpression:

PrimaryExpression PostIncrement
PostDecrement

PostIncrement:

PrimaryExpression ++

PostDecrement:

PrimaryExpression --

UnaryExpression:

PreIncrement PreDecrement + UnaryExpression - UnaryExpression
UnaryExpressionNotPlusMinus

PreIncrement:

++ PrimaryExpression

PreDecrement:

-- PrimaryExpression

UnaryExpressionNotPlusMinus:

PostfixExpression ~ UnaryExpression ! UnaryExpression
CastExpression

CastExpression:

( TypeKeyword ) UnaryExpression
( TypeExpression ) UnaryExpressionNotPlusMinus

Arithmetic Operators

MultiplicativeExpression:

UnaryExpression MultiplicativeExpression * UnaryExpression MultiplicativeExpression / UnaryExpression

MultiplicativeExpression % UnaryExpression

AdditiveExpression:

MultiplicativeExpression AdditiveExpression + MultiplicativeExpression
AdditiveExpression - MultiplicativeExpression

Shift Operators

ShiftExpression:

AdditiveExpression ShiftExpression << AdditiveExpression ShiftExpression >> AdditiveExpression

ShiftExpression >>> AdditiveExpression

Relational and Equality Operators

RelationalExpression:

ShiftExpression RelationalExpression < ShiftExpression RelationalExpression > ShiftExpression RelationalExpression <= ShiftExpression RelationalExpression >= ShiftExpression

RelationalExpression instanceof TypeSpecifier Dimsopt

EqualityExpression:

RelationalExpression EqualityExpression == RelationalExpression

EqualityExpression != RelationalExpression

Bitwise and Logical Operators

AndExpression:

EqualityExpression
AndExpression & EqualityExpression

ExclusiveOrExpression:

AndExpression
ExclusiveOrExpression ^ AndExpression

InclusiveOrExpression:

ExclusiveOr
InclusiveOrExpression | ExclusiveOrExpression

Conditional Operators

ConditionalAndExpression:

InclusiveOrExpression
ConditionalAndExpression && InclusiveOrExpression

ConditionalOrExpression:

ConditionalAndExpression
ConditionalOrExpression || ConditionalAndExpression

ConditionalExpression:

ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression

Assignments

AssignmentExpression:

ConditionalExpression
Assignment

Assignment:

UnaryExpression AssignmentOperator AssignmentExpression

AssignmentOperator: one of

= *= /= %= += -= <<= >>= >>>= &=
^= |=

Expression:

AssignmentExpression